text:
<?php
namespace Disque\Connection;

use Disque\Connection\Node\Node;
use Disque\Connection\Node\NodePrioritizerInterface;
use Disque\Connection\Node\ConservativeJobCountPrioritizer;
use Disque\Command\CommandInterface;
use Disque\Command\GetJob;
use Disque\Command\Response\HelloResponse;
use Disque\Command\Response\JobsResponse;
use Disque\Connection\Factory\ConnectionFactoryInterface;
use Disque\Connection\Factory\SocketFactory;

/**
 * The connection manager connects to Disque nodes and chooses the best of them
 *
 * If there are multiple nodes to connect, the first connection is always
 * random. The manager then switches to the best nodes according to its
 * NodePriority strategy.
 *
 * If the manager knows the credentials of only one node, it will automatically
 * discover other nodes in the cluster and connect to them if needed (unless
 * they are password-protected).
 */
class Manager implements ManagerInterface
{
    /**
     * Servers we can connect to initially, without knowing the cluster
     *
     * After connecting to one, the server returns a list of other nodes
     * in the cluster so we can connect to them automatically, unless
     * the discovered nodes are secured with a password.
     *
     * 'serverAddress' => Credentials
     *
     * @var Credentials[]
     */
    protected $credentials = [];

    /**
     * A strategy to prioritize nodes and find the best one to switch to
     *
     * The default strategy is the ConservativeJobCountPrioritizer. It
     * prioritizes nodes by their job count, but prefers the current node
     * in order to avoid switching until there is a clearly better node.
     *
     * @var NodePrioritizerInterface
     */
    protected $priorityStrategy;

    /**
     * List of nodes, ie Disque instances available in the cluster
     *
     * 'nodeId' => Node
     *
     * @var Node[]
     */
    protected $nodes = [];

    /**
     * Node prefixes and their corresponding node ID
     *
     * Node prefix consists of the first 8 bytes from the node ID. Because job
     * IDs contain the node prefix, it can be used to identify on which node
     * a job lives.
     *
     * 'nodePrefix' => 'nodeId'
     *
     * @var array
     */
    protected $nodePrefixes = [];

    /**
     * The ID of the node we are currently connected to
     *
     * @var string
     */
    protected $nodeId;

    /**
     * @var ConnectionFactoryInterface
     */
    private $connectionFactory;

    public function __construct()
    {
        $this->connectionFactory = new SocketFactory();
        $this->priorityStrategy = new ConservativeJobCountPrioritizer();
    }

    /**
     * @inheritdoc
     */
    public function getConnectionFactory()
    {
        return $this->connectionFactory;
    }

    /**
     * @inheritdoc
     */
    public function setConnectionFactory(
        ConnectionFactoryInterface $connectionFactory
    ) {
        $this->connectionFactory = $connectionFactory;
    }

    /**
     * @inheritdoc
     */
    public function getCredentials()
    {
        return $this->credentials;
    }

    /**
     * @inheritdoc
     */
    public function addServer(Credentials $credentials)
    {
        $address = $credentials->getAddress();
        $this->credentials[$address] = $credentials;
    }

    /**
     * @inheritdoc
     */
    public function getPriorityStrategy()
    {
        return $this->priorityStrategy;
    }

    /**
     * @inheritdoc
     */
    public function setPriorityStrategy($priorityStrategy)
    {
        $this->priorityStrategy = $priorityStrategy;
    }

    /**
     * @inheritdoc
     */
    public function isConnected()
    {
        return (
            isset($this->nodeId) &&
            $this->nodes[$this->nodeId]->getConnection()->isConnected()
        );
    }

    /**
     * @inheritdoc
     */
    public function connect()
    {
        $currentNode = $this->findAvailableConnection();
        $this->switchToNode($currentNode);
        return $currentNode;
    }

    /**
     * @inheritdoc
     */
    public function execute(CommandInterface $command)
    {
        $this->shouldBeConnected();
        $command = $this->preprocessExecution($command);
        $response = $this->nodes[$this->nodeId]->getConnection()->execute($command);
        $response = $this->postprocessExecution($command, $response);
        return $response;
    }

    /**
     * Get a functional connection to any known node
     *
     * Disque suggests the first connection should be chosen randomly
     *
     * @return Node A connected node
     *
     * @throws AuthenticationException
     * @throws ConnectionException
     */
    protected function findAvailableConnection()
    {
        $servers = $this->credentials;
        while (!empty($servers)) {
            $key = array_rand($servers);
            $server = $servers[$key];
            $node = $this->getNodeConnection($server);
            if ($node->getConnection()->isConnected()) {
                return $node;
            }
            unset($servers[$key]);
        }

        throw new ConnectionException('No servers available');
    }

    /**
     * Connect to the node given in the credentials
     *
     * @param Credentials $server
     *
     * @return Node A connected node
     */
    protected function getNodeConnection(Credentials $server)
    {
        $node = $this->createNode($server);
        $node->connect();
        return $node;
    }

    /**
     * Reset node counters that should be reset upon node switch
     */
    protected function resetNodeCounters()
    {
        foreach($this->nodes as $node) {
            $node->resetJobCount();
        }
    }

    /**
     * Hook into the command execution and do anything before it's executed
     *
     * Eg. start measuring node latency etc.
     *
     * @param CommandInterface $command
     *
     * @return CommandInterface $command
     */
    protected function preprocessExecution(CommandInterface $command)
    {
        return $command;
    }

    /**
     * Postprocess the command execution, eg. update node stats
     *
     * @param CommandInterface $command
     * @param mixed            $response
     *
     * @return mixed
     * @throws ConnectionException
     */
    protected function postprocessExecution(
        CommandInterface $command,
        $response
    ) {
        if ($command instanceof GetJob) {
            $this->updateNodeStats($command->parse($response));
            $this->switchNodeIfNeeded();
        }

        return $response;
    }

    /**
     * Update node counters indicating how many jobs the node has produced
     *
     * @param array $jobs Jobs
     */
    protected function updateNodeStats(array $jobs)
    {
        foreach ($jobs as $job) {
            $nodeId = $this->getNodeIdFromJobId($job[JobsResponse::KEY_ID]);
            if (!isset($nodeId) or !isset($this->nodes[$nodeId])) {
                continue;
            }

            $node = $this->nodes[$nodeId];
            $node->addJobCount(1);
        }
    }

    /**
     * Decide if we should switch to a better node
     *
     * @throws ConnectionException
     */
    private function switchNodeIfNeeded()
    {
        $sortedNodes = $this->priorityStrategy->sort(
            $this->nodes,
            $this->nodeId
        );

        // Try to connect by priority, continue on error, return on success
        foreach($sortedNodes as $nodeCandidate) {
            if ($nodeCandidate->getId() === $this->nodeId) {
                return;
            }

            try {
                if ($nodeCandidate->getConnection()->isConnected()) {
                    // Say a new HELLO to the node, the cluster might have changed
                    $nodeCandidate->sayHello();
                } else {
                    $nodeCandidate->connect();
                }
            } catch (ConnectionException $e) {
                continue;
            }

            $this->switchToNode($nodeCandidate);
            return;
        }

        throw new ConnectionException('Could not switch to any node');
    }

    /**
     * Get a node ID based off a Job ID
     *
     * @param string       $jobId Job ID
     * @return string|null        Node ID
     */
    private function getNodeIdFromJobId($jobId)
    {
        $nodePrefix = $this->getNodePrefixFromJobId($jobId);
        if (
            isset($this->nodePrefixes[$nodePrefix]) and
            array_key_exists($this->nodePrefixes[$nodePrefix], $this->nodes)
        ) {
            return $this->nodePrefixes[$nodePrefix];
        }

        return null;
    }

    /**
     * Get the node prefix from the job ID
     *
     * @param string  $jobId
     * @return string        Node prefix
     */
    private function getNodePrefixFromJobId($jobId)
    {
        $nodePrefix = substr(
            $jobId,
            JobsResponse::ID_NODE_PREFIX_START,
            Node::PREFIX_LENGTH
        );

        return $nodePrefix;
    }

    /**
     * We should be connected
     *
     * @return void
     * @throws ConnectionException
     */
    private function shouldBeConnected()
    {
        if (!$this->isConnected()) {
            throw new ConnectionException('Not connected');
        }
    }

    /**
     * Create a new Node object
     *
     * @param Credentials $credentials
     *
     * @return Node An unconnected Node
     */
    private function createNode(Credentials $credentials)
    {
        $host = $credentials->getHost();
        $port = $credentials->getPort();
        $connection = $this->connectionFactory->create($host, $port);

        return new Node($credentials, $connection);
    }

    /**
     * Switch to the given node and map the cluster from its HELLO
     *
     * @param Node $node
     */
    private function switchToNode(Node $node)
    {
        $nodeId = $node->getId();
        if ($this->nodeId === $nodeId) {
            return;
        }

        $this->resetNodeCounters();

        $this->nodeId = $nodeId;
        $this->nodes[$nodeId] = $node;
        $this->revealClusterFromHello($node);
    }

    /**
     * Reveal the whole Disque cluster from a node HELLO response
     *
     * The HELLO response from a Disque node contains addresses of all other
     * nodes in the cluster. We want to learn about them and save them, so that
     * we can switch to them later, if needed.
     *
     * @param Node $node The current node
     */
    private function revealClusterFromHello(Node $node)
    {
        $hello = $node->getHello();
        $revealedNodes = [];

        foreach ($hello[HelloResponse::NODES] as $node) {
            $id = $node[HelloResponse::NODE_ID];

            $prefix = substr($id, Node::PREFIX_START, Node::PREFIX_LENGTH);
            $this->nodePrefixes[$prefix] = $id;

            // Copy existing nodes over, don't overwrite them. We would lose
            // their stats and connection
            if (isset($this->nodes[$id])) {
                $revealedNodes[$id] = $this->nodes[$id];
                continue;
            }

            $host = $node[HelloResponse::NODE_HOST];
            $port = $node[HelloResponse::NODE_PORT];
            $credentials = new Credentials($host, $port);

            $address = $credentials->getAddress();
            // If there are user-supplied credentials for this node, use them.
            // They may contain a password
            if (isset($this->credentials[$address])) {
                $credentials = $this->credentials[$address];
            }

            // Create a new Node object for a newly revealed node
            $revealedNodes[$id] = $this->createNode($credentials);
        }

        $this->nodes = $revealedNodes;
    }
}


text:
package error

import (
	"errors"
	"fmt"
)

type error interface {
	Error() string
}

// START MYERROR OMIT
type myError struct {
	reason string
}

func (e myError) Error() string {
	return e.reason
}

// END MYERROR OMIT

func add(x, y int) (int, error) {
	if x > 10 && y > 10 {
		return 0, errors.New("number too big")
	}
	return x + y, nil
}

func example() {
	// START HANDLE OMIT
	sum, err := add(4, 5)
	if err != nil {
		fmt.Println("something bad happened")
	}
	// END HANDLE OMIT
}

redpajama_set_name: RedPajamaGithub


text:
// ==========================================================================
// Project: MySystem
// MySystem.RubricScore
// Copyright: ©2011 Concord Consortium
// ==========================================================================
/*globals MySystem  */

/** @class MySystem.RubricScore

  Stores students grade for diagram.

  @extends SC.Record
  @version 0.1
*/
MySystem.RubricScore = SC.Record.extend(
/** @scope MySystem.RubricScore.prototype */ {

  timeStamp:      SC.Record.attr(String),  // time of the score
  score:          SC.Record.attr(Number),  // score
  categories:     SC.Record.attr(String),  // rubric categories that were matched

  update: function(score,categories) {
    var data = [], exporter;
    var timestamp = new Date().getTime();
    this.set('timeStamp', timestamp);
    this.set('score',score);
    this.set('categories',categories);

  }
});

// we only ever want a single one of these records to exist per student state.
MySystem.RubricScore.LAST_SCORE_ID = "LAST_SCORE_ID";

MySystem.RubricScore.instance = function() {
  var store = MySystem.store;
  var lastScore  = store.find(MySystem.RubricScore,MySystem.RubricScore.LAST_SCORE_ID);
  if (lastScore && (lastScore.get('status') & SC.Record.READY)){
    return lastScore;
  }
  lastScore = store.createRecord( MySystem.RubricScore,
    { timeStamp: new Date() },
    MySystem.RubricScore.LAST_SCORE_ID);
  store.flush();
  store.commitRecords();
  return lastScore;
};


text: Jasmine unit & integration tests for classes that represents participating in BstokJS meeting.


text: A ring progress control sample using layer.mask & CoreAnimation


text:
defaul: up

up:
	vagrant up

list-vm:
	VBoxManage list runningvms

destroy:
	vagrant destroy

ssh:
	vagrant ssh $(name)

status:
	vagrant status

nodes:
	@echo "getting nodes, please waiting"
	kubectl -s http://192.168.20.10:8080 get nodes


text:
#import "NSObject.h"

@class NSArray;

@interface MPArtistGalleryArtworkLink : NSObject
{
    NSArray *_artworkVariants;
}

- (void).cxx_destruct;
- (id)bestImageURLForSize:(struct CGSize)arg1;
- (id)_initWithArtworkVariants:(id)arg1;

@end


text:
package com.mblinn.oo.tinyweb;

import java.util.List;
import java.util.Map;

public interface RenderingStrategy {

	public String renderView(Map<String, List<String>> model);

}


text:
Just another library to do asynchronous communication between applications (message-based).
## Getting Started
Create a console app and install the following NuGet package:
* [Jal.Router.Azure.Standard.LightInject.Installer.All](https://www.nuget.org/packages/Jal.Router.Azure.Standard.LightInject.Installer.All/)

Create a message class
```csharp
public class Message
{
    public string Text { get; set; }
}
```
Create a class to handle the message
```csharp
public interface IMessageHandler
{
    Task Handle(Message message);
}

public class MessageHandler : IMessageHandler
{
    public Task Handle(Message message)
    {
        Console.WriteLine("Hello world!!");
        return Task.CompletedTask;
    }
}
```
Create a router configuration class
```csharp
public class RouterConfigurationSource : AbstractRouterConfigurationSource
{
    public RouterConfigurationSource()
    {
        RegisterHandler("handler")
            .ToListen(x=>x.AddPointToPointChannel("path","connectionstring"))
            .With(x =>
            {
                x.ForMessage<Message>().Use<MessageHandler, MessageHandler>((request, handler, context) => handler.Handle(request));
            });

        RegisterEndPoint("endpoint")
            .To(x => x.AddPointToPointChannel("connectionstring", "path"));
    }
}
```
And on the Program.cs file setup the host
```csharp

var container = new ServiceContainer();

container.AddRouter(c=>{
    c.AddSource<RouterConfigurationSource>();
    c.AddNewtonsoft();
    c.AddMessageHandlerAsSingleton<IMessageHandler, MessageHandler>();
});

var bus = container.GetInstance<IBus>();

var host = container.GetInstance<IHost>();

host.Configuration
    .AddMemoryAsDefaultTransport()
    .UseNewtonsoftAsSerializer()
    .UseMemoryAsStorage();

await host.Startup();

await bus.Send(new Message(), Options.Create("endpoint"));

Console.ReadLine();

await host.Shutdown();
```
## Documentation
Documentation can be found on the project [Wiki](https://github.com/raulnq/Jal.Router/wiki/10.-Home).
## Contributing
Contributions, issues and feature requests are welcome.
Feel free to check [issues page](https://github.com/raulnq/Jal.Router/issues) if you want to contribute.
[Check the contributing guide](https://github.com/raulnq/Jal.Router/blob/master/CONTRIBUTING.md).
## Versioning
We use [SemVer](https://semver.org/) for versioning. For the versions available, [see the tags on this repository](https://github.com/raulnq/Jal.Router/tags).
## License
Jal.Router is licensed under the [Apache2 license](https://github.com/raulnq/Jal.Router/blob/master/LICENSE).
## Authors
* Raul Naupari (raulnq@gmail.com)
## RoadMap
* Feature: SqlServer transport
* Feature: Compression/encryption (middleware).
* Feature: Message consumption during scheduled periods of time.
* Feature: Non native duplicate detection (middleware).
* Feature: Non native message defering (middleware).
* Feature: Non native partition listening/sending.
* Feature: Message expiration.
* Feature: Message polling.
* Feature: Message translator (x.Translate<Translator>("sendto")).
* Feature: Return address and Message reply to (context.ReplyToReturnAddress(...)).
* Feature: Recipient list (x.SentTo(new []{"a","b"}))
* Feature: Message resequencer (x.Resequence("sentto", batchsize, timeout, x => x.Sequence, allowduplicates)).


text:
layout: post
title: RDBMS Specific Migrations With Rails

tags: Migration,Mysql,Postgresql,Programming,Rdbms,Ruby On Rails,Technology
---
I have been running into a problem recently with my development over at Type Aloud; some of my column data types differ from MySQL (my development database) and PostgreSQL (my production database). I store two copies of the story in the database: the first is the "human readable" version that uses the Markdown syntax and the second is the HTML version of that syntax so it is easier to fragment cache and display when someone is viewing the chapter. This problem is particularly irritating because when it first happened in MySQL the text was merely truncated, but in PostgreSQL it correctly does not allow the insertion into the table if the text is too long.

For the past couple of days I have been doing some light searching trying to figure out a way to have a RDBMS specific database migration, and I once I did some pecking in the ActiveRecord::Migration class I was able to figure this out pretty easily. I figured that I would share it below since it took me a little while to find it. Now normally I do not believe in migrations being platform specific, but in this case because I wanted to actually have the application work on two types of platforms (in this case, two RDBMS).

class AddLongtextToPostgresql < ActiveRecord::Migration
  def self.up
    case ActiveRecord::Base.connection.adapter_name
    when 'PostgreSQL'
      execute "CREATE DOMAIN longtext as text"
      execute "ALTER TABLE chapters ALTER COLUMN html TYPE longtext"
      execute "ALTER TABLE chapters ALTER COLUMN body TYPE longtext"
    else
      puts "This migration is not supported on this platform."
    end
  end

  def self.down
  end
end


text:
package com.github.eyce9000.spark.bes.client.xml;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import org.joda.time.DateTime;

import com.bigfix.schemas.relevance.ResultList;

public class WRResultParser {
	private JAXBContext jc;
	private Unmarshaller unmarshaller;
	private boolean columnsProcessed;
	public WRResultParser() throws JAXBException{

		jc = JAXBContext.newInstance(ResultList.class);
        unmarshaller = jc.createUnmarshaller();
	}

	public WRResult parse(InputStream in) throws XMLStreamException, JAXBException{
		XMLInputFactory factory = XMLInputFactory.newInstance();
		factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
		XMLEventReader reader = factory.createXMLEventReader(new BufferedReader(new InputStreamReader(in)));

		boolean inResults = false;

		WRResult result = new WRResult();
		result.results = new ArrayList<>();

		while(reader.hasNext()){
			reader.nextEvent();
			XMLEvent event = reader.peek();
			if(event==null)
				break;
			if(event.isStartElement()){
				StartElement el = event.asStartElement();
				String localName = el.getName().getLocalPart();

				if(localName.equals("sessionToken")){
					JAXBElement<String> element = unmarshaller.unmarshal(reader,String.class);
					result.token = element.getValue();
				}
				if(localName.equals("faultstring")){
					JAXBElement<String> element = unmarshaller.unmarshal(reader,String.class);
					result.error = element.getValue();
					return result;
				}
				if(localName.equals("error")){
					JAXBElement<String> element = unmarshaller.unmarshal(reader,String.class);
					result.error = element.getValue();
					return result;
				}

				if(localName.equals("results")){
					inResults = true;
				}
				else if(inResults){
					result.results.add(processElement(el,reader));
				}
			}
			if(event.isEndElement()){
				EndElement el = event.asEndElement();
				String localName = el.getName().getLocalPart();
				if(localName.equals("results"))
					inResults = false;

			}
		}
		return result;
	}

	private List<Object> processElement(StartElement el,XMLEventReader reader) throws JAXBException{
		ResultList row = null;

		JAXBElement element = null;
		String localName = el.getName().getLocalPart();
		if(localName.equals("String"))
			element = unmarshaller.unmarshal(reader,String.class);
		else if(localName.equals("Boolean"))
			element = unmarshaller.unmarshal(reader,Boolean.class);
		else if(localName.equals("Integer"))
			element = unmarshaller.unmarshal(reader,Integer.class);
		else if(localName.equals("DateTime"))
			element = unmarshaller.unmarshal(reader,XMLGregorianCalendar.class);
		else if(localName.equals("FloatingPoint"))
			element = unmarshaller.unmarshal(reader,Double.class);
		else if(localName.equals("Tuple")){
			JAXBElement<ResultList> jb = unmarshaller.unmarshal(reader, ResultList.class);
			row = jb.getValue();
		}
		if(row==null){
			row = new ResultList();
			row.getBooleanOrIntegerOrString().add(element.getValue());
		}
		return processResultList(row);
	}

	private List<Object> processResultList(ResultList result){
		List<Object> processed = new ArrayList<Object>(result.getBooleanOrIntegerOrString().size());
		for(Object rawValue : result.getBooleanOrIntegerOrString()){
			Object value;
			if(rawValue instanceof BigDecimal)
				value = ((BigDecimal)rawValue).doubleValue();
			else if(rawValue instanceof BigInteger)
				value = ((BigInteger)rawValue).intValue();
			else if(rawValue instanceof XMLGregorianCalendar){
				value = new Timestamp(((XMLGregorianCalendar)rawValue).toGregorianCalendar().getTimeInMillis());
			}
			else
				value = rawValue;

			processed.add(value);
    	}
		return processed;
	}

	public class WRResult{
		String token;
		List<List<Object>> results;
		String error;
		public String getToken() {
			return token;
		}
		public List<List<Object>> getResults() {
			return results;
		}
		public String getError() {
			return error;
		}
	}
}


text:
package org.apache.shardingsphere.sql.parser.core.visitor;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
import org.apache.shardingsphere.spi.ShardingSphereServiceLoader;
import org.apache.shardingsphere.sql.parser.api.visitor.SQLVisitorFacade;
import org.apache.shardingsphere.sql.parser.exception.SQLParsingException;
import org.apache.shardingsphere.sql.parser.spi.SQLParserConfiguration;
import org.apache.shardingsphere.sql.parser.sql.statement.SQLStatementType;

/**
 * Parse tree visitor factory.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ParseTreeVisitorFactory {

    /**
     * New instance of SQL visitor.
     *
     * @param databaseTypeName name of database type
     * @param visitorRule visitor rule
     * @return parse tree visitor
     */
    public static ParseTreeVisitor newInstance(final String databaseTypeName, final VisitorRule visitorRule) {
        for (SQLParserConfiguration each : ShardingSphereServiceLoader.newServiceInstances(SQLParserConfiguration.class)) {
            if (each.getDatabaseTypeName().equals(databaseTypeName)) {
                return createParseTreeVisitor(each, visitorRule.getType());
            }
        }
        throw new UnsupportedOperationException(String.format("Cannot support database type '%s'", databaseTypeName));
    }

    @SneakyThrows
    private static ParseTreeVisitor createParseTreeVisitor(final SQLParserConfiguration configuration, final SQLStatementType type) {
        SQLVisitorFacade visitorFacade = configuration.getVisitorFacadeClass().getConstructor().newInstance();
        switch (type) {
            case DML:
                return (ParseTreeVisitor) visitorFacade.getDMLVisitorClass().getConstructor().newInstance();
            case DDL:
                return (ParseTreeVisitor) visitorFacade.getDDLVisitorClass().getConstructor().newInstance();
            case TCL:
                return (ParseTreeVisitor) visitorFacade.getTCLVisitorClass().getConstructor().newInstance();
            case DCL:
                return (ParseTreeVisitor) visitorFacade.getDCLVisitorClass().getConstructor().newInstance();
            case DAL:
                return (ParseTreeVisitor) visitorFacade.getDALVisitorClass().getConstructor().newInstance();
            case RL:
                return (ParseTreeVisitor) visitorFacade.getRLVisitorClass().getConstructor().newInstance();
            default:
                throw new SQLParsingException("Can not support SQL statement type: `%s`", type);
        }
    }
}


text:
package org.apache.struts2.dispatcher.mapper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.dispatcher.ServletRedirectResult;
import org.apache.struts2.util.PrefixTrie;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 *

 * Default action mapper implementation, using the standard *.[ext] (where ext
 * usually "action") pattern. The extension is looked up from the Struts
 * configuration key struts.action.extension.
 *

 *
 To help with dealing with buttons and other related requirements, this
 * mapper (and other {@link ActionMapper}s, we hope) has the ability to name a
 * button with some predefined prefix and have that button name alter the
 * execution behaviour. The four prefixes are:
 *

 *

 *

 *
Method prefix - method:default

 *

 *
Action prefix - action:dashboard

 *

 *
Redirect prefix - redirect:cancel.jsp

 *

 *
Redirect-action prefix - redirectAction:cancel

 *

 *

 *

 *
 In addition to these four prefixes, this mapper also understands the
 * action naming pattern of foo!bar in either the extension form (eg:
 * foo!bar.action) or in the prefix form (eg: action:foo!bar). This syntax tells
 * this mapper to map to the action named foo and the method bar.
 *

 *
 *

 *
 Method Prefix

 *

 *
 *

 * With method-prefix, instead of calling baz action's execute() method (by
 * default if it isn't overriden in struts.xml to be something else), the baz
 * action's anotherMethod() will be called. A very elegant way determine which
 * button is clicked. Alternatively, one would have submit button set a
 * particular value on the action when clicked, and the execute() method decides
 * on what to do with the setted value depending on which button is clicked.
 *

 *
 *

 *

 *  <!-- START SNIPPET: method-example -->
 *  <s:form action="baz">
 *      <s:textfield label="Enter your name" name="person.name"/>
 *      <s:submit value="Create person"/>
 *      <s:submit name="method:anotherMethod" value="Cancel"/>
 *  </s:form>
 *  <!-- END SNIPPET: method-example -->
 *

 *

 *
 Action prefix

 *

 *
 *

 * With action-prefix, instead of executing baz action's execute() method (by
 * default if it isn't overriden in struts.xml to be something else), the
 * anotherAction action's execute() method (assuming again if it isn't overriden
 * with something else in struts.xml) will be executed.
 *

 *
 *

 *

 *  <!-- START SNIPPET: action-example -->
 *  <s:form action="baz">
 *      <s:textfield label="Enter your name" name="person.name"/>
 *      <s:submit value="Create person"/>
 *      <s:submit name="action:anotherAction" value="Cancel"/>
 *  </s:form>
 *  <!-- END SNIPPET: action-example -->
 *

 *

 *
 Redirect prefix

 *

 *
 *

 * With redirect-prefix, instead of executing baz action's execute() method (by
 * default it isn't overriden in struts.xml to be something else), it will get
 * redirected to, in this case to www.google.com. Internally it uses
 * ServletRedirectResult to do the task.
 *

 *
 *

 *

 *  <!-- START SNIPPET: redirect-example -->
 *  <s:form action="baz">
 *      <s:textfield label="Enter your name" name="person.name"/>
 *      <s:submit value="Create person"/>
 *      <s:submit name="redirect:www.google.com" value="Cancel"/>
 *  </s:form>
 *  <!-- END SNIPPET: redirect-example -->
 *

 *

 *
 Redirect-action prefix

 *

 *
 *

 * With redirect-action-prefix, instead of executing baz action's execute()
 * method (by default it isn't overriden in struts.xml to be something else), it
 * will get redirected to, in this case 'dashboard.action'. Internally it uses
 * ServletRedirectResult to do the task and read off the extension from the
 * struts.properties.
 *

 *
 *

 *

 *  <!-- START SNIPPET: redirect-action-example -->
 *  <s:form action="baz">
 *      <s:textfield label="Enter your name" name="person.name"/>
 *      <s:submit value="Create person"/>
 *      <s:submit name="redirectAction:dashboard" value="Cancel"/>
 *  </s:form>
 *  <!-- END SNIPPET: redirect-action-example -->
 *

 */
public class DefaultActionMapper implements ActionMapper {

    protected static final String METHOD_PREFIX = "method:";

    protected static final String ACTION_PREFIX = "action:";

    protected static final String REDIRECT_PREFIX = "redirect:";

    protected static final String REDIRECT_ACTION_PREFIX = "redirectAction:";

    protected boolean allowDynamicMethodCalls = true;

    protected boolean allowSlashesInActionNames = false;

    protected boolean alwaysSelectFullNamespace = false;

    protected PrefixTrie prefixTrie = null;

    protected List<String> extensions = new ArrayList<String>() {{
        add("action");
        add("");
    }};

    protected Container container;

    /**
     * <ĬÈϹ¹Ô캯Êý>
     * ÓÖÊǸö±È½ÏºÃÍæµÄд·¨
     */
    public DefaultActionMapper() {
        prefixTrie = new PrefixTrie() {
            {
                put(METHOD_PREFIX, new ParameterAction() {
                    public void execute(String key, ActionMapping mapping) {
                        if (allowDynamicMethodCalls) {
                            mapping.setMethod(key.substring(
                                    METHOD_PREFIX.length()));
                        }
                    }
                });

                put(ACTION_PREFIX, new ParameterAction() {
                    public void execute(String key, ActionMapping mapping) {
                        String name = key.substring(ACTION_PREFIX.length());
                        if (allowDynamicMethodCalls) {
                            int bang = name.indexOf('!');
                            if (bang != -1) {
                                String method = name.substring(bang + 1);
                                mapping.setMethod(method);
                                name = name.substring(0, bang);
                            }
                        }
                        mapping.setName(name);
                    }
                });

                put(REDIRECT_PREFIX, new ParameterAction() {
                    public void execute(String key, ActionMapping mapping) {
                        ServletRedirectResult redirect = new ServletRedirectResult();
                        container.inject(redirect);
                        redirect.setLocation(key.substring(REDIRECT_PREFIX
                                .length()));
                        mapping.setResult(redirect);
                    }
                });

                put(REDIRECT_ACTION_PREFIX, new ParameterAction() {
                    public void execute(String key, ActionMapping mapping) {
                        String location = key.substring(REDIRECT_ACTION_PREFIX
                                .length());
                        ServletRedirectResult redirect = new ServletRedirectResult();
                        container.inject(redirect);
                        String extension = getDefaultExtension();
                        if (extension != null && extension.length() > 0) {
                            location += "." + extension;
                        }
                        redirect.setLocation(location);
                        mapping.setResult(redirect);
                    }
                });
            }
        };
    }

    /**
     * Adds a parameter action.  Should only be called during initialization
     *
     * @param prefix          The string prefix to trigger the action
     * @param parameterAction The parameter action to execute
     * @since 2.1.0
     */
    protected void addParameterAction(String prefix, ParameterAction parameterAction) {
        prefixTrie.put(prefix, parameterAction);
    }

    @Inject(StrutsConstants.STRUTS_ENABLE_DYNAMIC_METHOD_INVOCATION)
    public void setAllowDynamicMethodCalls(String allow) {
        allowDynamicMethodCalls = "true".equals(allow);
    }

    @Inject(StrutsConstants.STRUTS_ENABLE_SLASHES_IN_ACTION_NAMES)
    public void setSlashesInActionNames(String allow) {
        allowSlashesInActionNames = "true".equals(allow);
    }

    @Inject(StrutsConstants.STRUTS_ALWAYS_SELECT_FULL_NAMESPACE)
    public void setAlwaysSelectFullNamespace(String val) {
        this.alwaysSelectFullNamespace = "true".equals(val);
    }

    @Inject
    public void setContainer(Container container) {
        this.container = container;
    }

    @Inject(StrutsConstants.STRUTS_ACTION_EXTENSION)
    public void setExtensions(String extensions) {
        if (extensions != null && !"".equals(extensions)) {
            List<String> list = new ArrayList<String>();
            String[] tokens = extensions.split(",");
            for (String token : tokens) {
                list.add(token);
            }
            if (extensions.endsWith(",")) {
                list.add("");
            }
            this.extensions = Collections.unmodifiableList(list);
        } else {
            this.extensions = null;
        }
    }

    public ActionMapping getMappingFromActionName(String actionName) {
        ActionMapping mapping = new ActionMapping();
        mapping.setName(actionName);
        return parseActionName(mapping);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.struts2.dispatcher.mapper.ActionMapper#getMapping(javax.servlet.http.HttpServletRequest)
     */

    public ActionMapping getMapping(HttpServletRequest request,
                                    ConfigurationManager configManager) {
        ActionMapping mapping = new ActionMapping();
        String uri = getUri(request);

        int indexOfSemicolon = uri.indexOf(";");
        uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;

        uri = dropExtension(uri, mapping);
        if (uri == null) {
            return null;
        }

        parseNameAndNamespace(uri, mapping, configManager);

        handleSpecialParameters(request, mapping);

        if (mapping.getName() == null) {
            return null;
        }

        parseActionName(mapping);

        return mapping;
    }

    protected ActionMapping parseActionName(ActionMapping mapping) {
        if (mapping.getName() == null) {
            return mapping;
        }
        if (allowDynamicMethodCalls) {
            // handle "name!method" convention.
            String name = mapping.getName();
            int exclamation = name.lastIndexOf("!");
            if (exclamation != -1) {
                mapping.setName(name.substring(0, exclamation));
                mapping.setMethod(name.substring(exclamation + 1));
            }
        }
        return mapping;
    }

    /**
     * Special parameters, as described in the class-level comment, are searched
     * for and handled.
     *
     * @param request The request
     * @param mapping The action mapping
     */
    public void handleSpecialParameters(HttpServletRequest request,
                                        ActionMapping mapping) {
        // handle special parameter prefixes.
        Set<String> uniqueParameters = new HashSet<String>();
        Map parameterMap = request.getParameterMap();
        for (Iterator iterator = parameterMap.keySet().iterator(); iterator
                .hasNext();) {
            String key = (String) iterator.next();

            // Strip off the image button location info, if found
            if (key.endsWith(".x") || key.endsWith(".y")) {
                key = key.substring(0, key.length() - 2);
            }

            // Ensure a parameter doesn't get processed twice
            if (!uniqueParameters.contains(key)) {
                ParameterAction parameterAction = (ParameterAction) prefixTrie
                        .get(key);
                if (parameterAction != null) {
                    parameterAction.execute(key, mapping);
                    uniqueParameters.add(key);
                    break;
                }
            }
        }
    }

    /**
     * Parses the name and namespace from the uri
     *
     * @param uri     The uri
     * @param mapping The action mapping to populate
     */
    protected void parseNameAndNamespace(String uri, ActionMapping mapping,
                                         ConfigurationManager configManager) {
        String namespace, name;
        int lastSlash = uri.lastIndexOf("/");
        if (lastSlash == -1) {
            namespace = "";
            name = uri;
        } else if (lastSlash == 0) {
            // ww-1046, assume it is the root namespace, it will fallback to
            // default
            // namespace anyway if not found in root namespace.
            namespace = "/";
            name = uri.substring(lastSlash + 1);
        } else if (alwaysSelectFullNamespace) {
            // Simply select the namespace as everything before the last slash
            namespace = uri.substring(0, lastSlash);
            name = uri.substring(lastSlash + 1);
        } else {
            // Try to find the namespace in those defined, defaulting to ""
            Configuration config = configManager.getConfiguration();
            String prefix = uri.substring(0, lastSlash);
            namespace = "";
            boolean rootAvailable = false;
            // Find the longest matching namespace, defaulting to the default
            for (Object cfg : config.getPackageConfigs().values()) {
                String ns = ((PackageConfig) cfg).getNamespace();
                if (ns != null && prefix.startsWith(ns) && (prefix.length() == ns.length() || prefix.charAt(ns.length()) == '/')) {
                    if (ns.length() > namespace.length()) {
                        namespace = ns;
                    }
                }
                if ("/".equals(ns)) {
                    rootAvailable = true;
                }
            }

            name = uri.substring(namespace.length() + 1);

            // Still none found, use root namespace if found
            if (rootAvailable && "".equals(namespace)) {
                namespace = "/";
            }
        }

        if (!allowSlashesInActionNames && name != null) {
            int pos = name.lastIndexOf('/');
            if (pos > -1 && pos < name.length() - 1) {
                name = name.substring(pos + 1);
            }
        }

        mapping.setNamespace(namespace);
        mapping.setName(name);
    }

    /**
     * Drops the extension from the action name
     *
     * @param name The action name
     * @return The action name without its extension
     * @deprecated Since 2.1, use {@link #dropExtension(java.lang.String,org.apache.struts2.dispatcher.mapper.ActionMapping)} instead
     */
    protected String dropExtension(String name) {
        return dropExtension(name, new ActionMapping());
    }

    /**
     * Drops the extension from the action name, storing it in the mapping for later use
     *
     * @param name    The action name
     * @param mapping The action mapping to store the extension in
     * @return The action name without its extension
     */
    protected String dropExtension(String name, ActionMapping mapping) {
        if (extensions == null) {
            return name;
        }
        for (String ext : extensions) {
            if ("".equals(ext)) {
                // This should also handle cases such as /foo/bar-1.0/description. It is tricky to
                // distinquish /foo/bar-1.0 but perhaps adding a numeric check in the future could
                // work
                int index = name.lastIndexOf('.');
                if (index == -1 || name.indexOf('/', index) >= 0) {
                    return name;
                }
            } else {
                String extension = "." + ext;
                if (name.endsWith(extension)) {
                    name = name.substring(0, name.length() - extension.length());
                    mapping.setExtension(ext);
                    return name;
                }
            }
        }
        return null;
    }

    /**
     * Returns null if no extension is specified.
     */
    protected String getDefaultExtension() {
        if (extensions == null) {
            return null;
        } else {
            return (String) extensions.get(0);
        }
    }

    /**
     * Gets the uri from the request
     *
     * @param request The request
     * @return The uri
     */
    protected String getUri(HttpServletRequest request) {
        // handle http dispatcher includes.
        String uri = (String) request
                .getAttribute("javax.servlet.include.servlet_path");
        if (uri != null) {
            return uri;
        }

        uri = RequestUtils.getServletPath(request);
        if (uri != null && !"".equals(uri)) {
            return uri;
        }

        uri = request.getRequestURI();
        return uri.substring(request.getContextPath().length());
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.struts2.dispatcher.mapper.ActionMapper#getUriFromActionMapping(org.apache.struts2.dispatcher.mapper.ActionMapping)
     */

    public String getUriFromActionMapping(ActionMapping mapping) {
        StringBuilder uri = new StringBuilder();

        if (mapping.getNamespace() != null) {
            uri.append(mapping.getNamespace());
            if (!"/".equals(mapping.getNamespace())) {
                uri.append("/");
            }
        }
        String name = mapping.getName();
        String params = "";
        if (name.indexOf('?') != -1) {
            params = name.substring(name.indexOf('?'));
            name = name.substring(0, name.indexOf('?'));
        }
        uri.append(name);

        if (null != mapping.getMethod() && !"".equals(mapping.getMethod())) {
            uri.append("!").append(mapping.getMethod());
        }

        String extension = mapping.getExtension();
        if (extension == null) {
            // Look for the current extension, if available
            ActionContext context = ActionContext.getContext();
            if (context != null) {
                ActionMapping orig = (ActionMapping) context.get(ServletActionContext.ACTION_MAPPING);
                if (orig != null) {
                    extension = orig.getExtension();
                }
            }
            if (extension == null) {
                extension = getDefaultExtension();
            }
        }

        if (extension != null) {
            if (extension.length() == 0 || (extension.length() > 0 && uri.indexOf('.' + extension) == -1)) {
                if (extension.length() > 0) {
                    uri.append(".").append(extension);
                }
            }
        }
        if (params.length() > 0) {
            uri.append(params);
        }

        return uri.toString();
    }

    public boolean isSlashesInActionNames() {
        return allowSlashesInActionNames;
    }

}


text:
#import <ParseUI/ParseUI.h>

@interface DeletionCollectionViewController : PFQueryCollectionViewController

@end


text:
package net.starlark.java.eval;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import net.starlark.java.syntax.TokenKind;

/**
 * Describe instruction operands of the Starlark bytecode.
 *
 *
This code is used only when assertions are enabled, because proper instruction validation
 * might be expensive.
 */
class BcInstrOperand {
  /** Bytecode operand is an integer, stored in the bytecode. */
  static final Operands NUMBER = new NumberOperand();
  /**
   * Bytecode operand is logically a string, stored in the strings storage; the index is stored in
   * the bytecode.
   */
  static final Operands STRING = new StringOperand();
  /**
   * Bytecode operand is logically an object, stored in the strings storage; the index is stored in
   * the bytecode.
   */
  static final Operands OBJECT = new ObjectArg();

  /**
   * Bytecode operand is an input register. Note current implementation does not validate that it is
   * actually read, not write register, it is used mostly as a hint when bytecode is printed.
   *
   *
Operand of this type can be a non-negative integer for regular slot, or negative integer for
   * constants.
   */
  static final Operands IN_SLOT = new Register("r");
  /**
   * Bytecode operand is an input register. Note current implementation does not validate that it is
   * actually read, not write register, it is used mostly as a hint when bytecode is printed.
   *
   *
Operand of this type can be a non-negative integer for regular slot, or negative integer for
   * constants.
   */
  static final Operands IN_LOCAL = new Local("r");
  /**
   * Bytecode operand is an output register.
   *
   *
The value of this operand must be a non-negative integer.
   */
  static final Operands OUT_SLOT = new Register("w");

  /** Bytecode operand is a fixed integer, storing {@link TokenKind}. */
  static final Operands TOKEN_KIND = new KindArg();

  /** Either length-delimited slots or an object array. */
  static final Operands IN_LIST = new ListOperand();

  /** Operand is a fixed number storing the instruction pointer. */
  static final Operands ADDR = new AddrArg();

  private BcInstrOperand() {}

  /** Fixed of operands, e. g. a pair of operands used to describe a dict key and value. */
  static Operands fixed(Operands... operands) {
    return new FixedOperandsOpcode(operands);
  }

  /** Length-delimited operands, e. g. list constructor arguments. */
  static Operands lengthDelimited(Operands element) {
    return new LengthDelimited(element);
  }

  /**
   * Sequence of operands.
   *
   *
Note in Starlark bytecode, the opcode operands are variable length: The number of operands
   * depend not just on the opcode, but it is encoded in the previous operands. E. g. a list
   * constructor is encoded as a length delimited sequence of register operands.
   */
  abstract static class Operands {
    private Operands() {}

    /** This is low level operation, do not use directly. */
    abstract void print(OpcodePrinter visitor);

    /**
     * Given the offset of the operand, return the position after the operand. In another words,
     * determine operand code size.
     *
     *
For example, length-delimited operand may return the different number of ints depending on
     * the actual bytecode.
     */
    protected abstract void consume(BcInstrParser parser);

    /**
     * Get the number of integers occupied by this operands object at the given bytecode offset.
     *
     *
For example, length-delimited operand may return the different number of ints depending on
     * the actual bytecode.
     */
    int codeSize(int[] text, int ip) {
      BcInstrParser parser = new BcInstrParser(text, ip);
      consume(parser);
      return parser.getIp() - ip;
    }

    /** Get both instruction count for this operand and the string representation. */
    String toStringAndCount(
        BcInstrParser parser,
        List<String> strings,
        List<Object> constantRegs,
        List<Object> objects,
        OpcodePrinterFunctionContext fnCtx) {
      OpcodePrinter printer = new OpcodePrinter(parser, strings, constantRegs, objects, fnCtx);
      print(printer);
      return printer.sb.toString();
    }

    abstract static class Decoded {
      AddrArg.Decoded asAddr() {
        return (AddrArg.Decoded) this;
      }

      FixedOperandsOpcode.Decoded asFixed() {
        return (FixedOperandsOpcode.Decoded) this;
      }

      KindArg.Decoded asKind() {
        return (KindArg.Decoded) this;
      }

      LengthDelimited.Decoded asLengthDelimited() {
        return (LengthDelimited.Decoded) this;
      }

      NumberOperand.Decoded asNumber() {
        return (NumberOperand.Decoded) this;
      }

      ObjectArg.Decoded asObject() {
        return (ObjectArg.Decoded) this;
      }

      Register.Decoded asRegister() {
        return (Register.Decoded) this;
      }

      StringOperand.Decoded asString() {
        return (StringOperand.Decoded) this;
      }
    }

    abstract Decoded decode(BcInstrParser parser);
  }

  static class OpcodePrinterFunctionContext {
    private final ImmutableList<String> locals;
    private final ImmutableList<String> globals;
    private final ImmutableList<String> freeVars;

    public OpcodePrinterFunctionContext(
        ImmutableList<String> locals,
        ImmutableList<String> globals,
        ImmutableList<String> freeVars) {
      this.locals = locals;
      this.globals = globals;
      this.freeVars = freeVars;
    }
  }

  /** This class is package-private only because it is referenced from {@link Operands}. */
  private static class OpcodePrinter {

    private final BcInstrParser parser;
    private final List<String> strings;
    private final List<Object> constantRegs;
    private final List<Object> objects;
    private final OpcodePrinterFunctionContext fnCtx;
    private StringBuilder sb = new StringBuilder();

    private OpcodePrinter(
        BcInstrParser parser,
        List<String> strings,
        List<Object> constantRegs,
        List<Object> objects,
        OpcodePrinterFunctionContext fnCtx) {
      this.parser = parser;
      this.objects = objects;
      this.fnCtx = fnCtx;
      this.strings = strings;
      this.constantRegs = constantRegs;
    }

    private void append(String s) {
      sb.append(s);
    }
  }

  /** One word operand (e. g. register). */
  private abstract static class OneWordOperand extends Operands {
    @Override
    protected final void consume(BcInstrParser parser) {
      parser.nextInt();
    }
  }

  static class NumberOperand extends OneWordOperand {
    @Override
    public void print(OpcodePrinter visitor) {
      visitor.append(Integer.toString(visitor.parser.nextInt()));
    }

    static class Decoded extends Operands.Decoded {
      final int value;

      Decoded(int value) {
        this.value = value;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextInt());
    }
  }

  static class StringOperand extends OneWordOperand {
    @Override
    public void print(OpcodePrinter visitor) {
      visitor.append(visitor.strings.get(visitor.parser.nextInt()));
    }

    static class Decoded extends Operands.Decoded {
      final int index;

      Decoded(int index) {
        this.index = index;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextInt());
    }
  }

  static class Local extends OneWordOperand {
    /** r or w, for read or write */
    private final String label;

    private Local(String label) {
      this.label = label;
    }

    @Override
    void print(OpcodePrinter visitor) {
      new Register(label).print(visitor);
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextInt());
    }

    static class Decoded extends Operands.Decoded {
      final int register;

      public Decoded(int register) {
        this.register = register;
      }
    }
  }

  static class Register extends OneWordOperand {
    /** r or w, for read or write */
    private final String label;

    private Register(String label) {
      this.label = label;
    }

    @Override
    public void print(OpcodePrinter visitor) {
      int reg = visitor.parser.nextInt();
      Object valueToPrint;
      int flag = reg & BcSlot.MASK;
      int index = reg & ~BcSlot.MASK;
      switch (flag) {
        case BcSlot.LOCAL_FLAG:
          if (index < visitor.fnCtx.locals.size()) {
            // local
            valueToPrint = "l$" + index + ":" + visitor.fnCtx.locals.get(index);
          } else {
            // temporary
            valueToPrint = "s$" + index;
          }
          break;
        case BcSlot.GLOBAL_FLAG:
          valueToPrint = "g$" + index + ":" + visitor.fnCtx.globals.get(index);
          break;
        case BcSlot.CELL_FLAG:
          valueToPrint = "c$" + index + ":" + visitor.fnCtx.locals.get(index);
          break;
        case BcSlot.FREE_FLAG:
          valueToPrint = "f$" + index + ":" + visitor.fnCtx.freeVars.get(index);
          break;
        case BcSlot.CONST_FLAG:
          Object constant = visitor.constantRegs.get(index);
          valueToPrint = "=" + Starlark.repr(constant);
          break;
        case BcSlot.NULL_FLAG:
          valueToPrint = "=null";
          break;
        default:
          throw new IllegalStateException("wrong slot");
      }
      visitor.sb.append(label).append(valueToPrint);
    }

    static class Decoded extends Operands.Decoded {
      final int register;

      public Decoded(int register) {
        this.register = register;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextInt());
    }
  }

  static class KindArg extends OneWordOperand {
    @Override
    public void print(OpcodePrinter visitor) {
      visitor.sb.append(TokenKind.values()[visitor.parser.nextInt()]);
    }

    static class Decoded extends Operands.Decoded {
      final TokenKind tokenKind;

      public Decoded(TokenKind tokenKind) {
        this.tokenKind = tokenKind;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextTokenKind());
    }
  }

  static class AddrArg extends OneWordOperand {
    private AddrArg() {}

    @Override
    public void print(OpcodePrinter visitor) {
      visitor.append("@" + visitor.parser.nextInt());
    }

    static class Decoded extends Operands.Decoded {
      final int addr;

      public Decoded(int addr) {
        this.addr = addr;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextInt());
    }
  }

  static class ObjectArg extends OneWordOperand {
    @Override
    public void print(OpcodePrinter visitor) {
      int objectIndex = visitor.parser.nextInt();
      Object o =
          objectIndex < visitor.objects.size() ? visitor.objects.get(objectIndex) : "invalid";
      visitor.append("o" + objectIndex + "=" + o);
    }

    static class Decoded extends Operands.Decoded {
      final int index;

      public Decoded(int index) {
        this.index = index;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(parser.nextInt());
    }
  }

  static class FixedOperandsOpcode extends Operands {
    private final Operands[] operands;

    private FixedOperandsOpcode(Operands[] operands) {
      this.operands = operands;
    }

    @Override
    public void print(OpcodePrinter visitor) {
      visitor.append("(");
      for (int i = 0; i < operands.length; i++) {
        if (i != 0) {
          visitor.sb.append(" ");
        }
        Operands operand = operands[i];
        operand.print(visitor);
      }
      visitor.append(")");
    }

    @Override
    protected void consume(BcInstrParser parser) {
      for (Operands operand : operands) {
        operand.consume(parser);
      }
    }

    static class Decoded extends Operands.Decoded {
      final ImmutableList<Operands.Decoded> operands;

      Decoded(ImmutableList<Operands.Decoded> operands) {
        this.operands = operands;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(
          Arrays.stream(operands)
              .map(o -> o.decode(parser))
              .collect(ImmutableList.toImmutableList()));
    }
  }

  static class LengthDelimited extends Operands {
    private final Operands element;

    private LengthDelimited(Operands element) {
      this.element = element;
    }

    @Override
    public void print(OpcodePrinter visitor) {
      visitor.append("[");
      int size = visitor.parser.nextInt();
      for (int i = 0; i != size; ++i) {
        if (i != 0) {
          visitor.append(" ");
        }
        element.print(visitor);
      }
      visitor.append("]");
    }

    @Override
    protected void consume(BcInstrParser parser) {
      int size = parser.nextInt();
      for (int i = 0; i != size; ++i) {
        element.consume(parser);
      }
    }

    static class Decoded extends Operands.Decoded {
      private final ImmutableList<Operands.Decoded> elements;

      Decoded(ImmutableList<Operands.Decoded> elements) {
        this.elements = elements;
      }
    }

    @Override
    Decoded decode(BcInstrParser parser) {
      return new Decoded(
          IntStream.range(0, parser.nextInt())
              .mapToObj(i -> element.decode(parser))
              .collect(ImmutableList.toImmutableList()));
    }
  }

  /** Length-delimited slot or an array in object pool. */
  static class ListOperand extends Operands {

    @Override
    void print(OpcodePrinter visitor) {
      int size = visitor.parser.nextInt();
      if (size < 0) {
        visitor.append("o" + (1 - size));
      } else {
        visitor.append("[");
        for (int i = 0; i != size; ++i) {
          if (i != 0) {
            visitor.append(" ");
          }
          IN_SLOT.print(visitor);
        }
        visitor.append("]");
      }
    }

    @Override
    protected void consume(BcInstrParser parser) {
      int size = parser.nextInt();
      if (size >= 0) {
        for (int i = 0; i != size; ++i) {
          IN_SLOT.consume(parser);
        }
      }
    }

    @Override
    Operands.Decoded decode(BcInstrParser parser) {
      int size = parser.nextInt();
      if (size < 0) {
        return new Decoded(size, ArraysForStarlark.EMPTY_INT_ARRAY);
      } else {
        int[] slots = parser.nextInts(size);
        return new Decoded(size, slots);
      }
    }

    static class Decoded extends Operands.Decoded {
      final int size;
      final int[] slots;

      Decoded(int size, int[] slots) {
        if (size < 0) {
          Preconditions.checkArgument(slots.length == 0);
        } else {
          Preconditions.checkArgument(size == slots.length);
        }
        this.size = size;
        this.slots = slots;
      }
    }
  }
}


text:
/**
 * @file    chschd.h
 * @brief   Scheduler macros and structures.
 *
 * @addtogroup scheduler
 * @{
 */

#ifndef CHSCHD_H
#define CHSCHD_H

/*===========================================================================*/
/* Module constants.                                                         */
/*===========================================================================*/

/**
 * @name    Wakeup status codes
 * @{
 */
#define MSG_OK              (msg_t)0    /**< @brief Normal wakeup message.  */
#define MSG_TIMEOUT         (msg_t)-1   /**< @brief Wakeup caused by a timeout
                                             condition.                     */
#define MSG_RESET           (msg_t)-2   /**< @brief Wakeup caused by a reset
                                             condition.                     */
/** @} */

/**
 * @name    Priority constants
 * @{
 */
#define NOPRIO              (tprio_t)0      /**< @brief Ready list header
                                                 priority.                  */
#define IDLEPRIO            (tprio_t)1      /**< @brief Idle priority.      */
#define LOWPRIO             (tprio_t)2      /**< @brief Lowest priority.    */
#define NORMALPRIO          (tprio_t)128    /**< @brief Normal priority.    */
#define HIGHPRIO            (tprio_t)255    /**< @brief Highest priority.   */
/** @} */

/**
 * @name    Thread states
 * @{
 */
#define CH_STATE_READY      (tstate_t)0      /**< @brief Waiting on the
                                                  ready list.               */
#define CH_STATE_CURRENT    (tstate_t)1      /**< @brief Currently running. */
#define CH_STATE_WTSTART    (tstate_t)2      /**< @brief Just created.      */
#define CH_STATE_SUSPENDED  (tstate_t)3      /**< @brief Suspended state.   */
#define CH_STATE_QUEUED     (tstate_t)4      /**< @brief On an I/O queue.   */
#define CH_STATE_WTSEM      (tstate_t)5      /**< @brief On a semaphore.    */
#define CH_STATE_WTMTX      (tstate_t)6      /**< @brief On a mutex.        */
#define CH_STATE_WTCOND     (tstate_t)7      /**< @brief On a cond.variable.*/
#define CH_STATE_SLEEPING   (tstate_t)8      /**< @brief Sleeping.          */
#define CH_STATE_WTEXIT     (tstate_t)9      /**< @brief Waiting a thread.  */
#define CH_STATE_WTOREVT    (tstate_t)10     /**< @brief One event.         */
#define CH_STATE_WTANDEVT   (tstate_t)11     /**< @brief Several events.    */
#define CH_STATE_SNDMSGQ    (tstate_t)12     /**< @brief Sending a message,
                                                  in queue.                 */
#define CH_STATE_SNDMSG     (tstate_t)13     /**< @brief Sent a message,
                                                  waiting answer.           */
#define CH_STATE_WTMSG      (tstate_t)14     /**< @brief Waiting for a
                                                  message.                  */
#define CH_STATE_FINAL      (tstate_t)15     /**< @brief Thread terminated. */

/**
 * @brief   Thread states as array of strings.
 * @details Each element in an array initialized with this macro can be
 *          indexed using the numeric thread state values.
 */
#define CH_STATE_NAMES                                                     \
  "READY", "CURRENT", "WTSTART", "SUSPENDED", "QUEUED", "WTSEM", "WTMTX",  \
  "WTCOND", "SLEEPING", "WTEXIT", "WTOREVT", "WTANDEVT", "SNDMSGQ",        \
  "SNDMSG", "WTMSG", "FINAL"
/** @} */

/**
 * @name    Thread flags and attributes
 * @{
 */
#define CH_FLAG_MODE_MASK   (tmode_t)3U     /**< @brief Thread memory mode
                                                 mask.                      */
#define CH_FLAG_MODE_STATIC (tmode_t)0U     /**< @brief Static thread.      */
#define CH_FLAG_MODE_HEAP   (tmode_t)1U     /**< @brief Thread allocated
                                                 from a Memory Heap.        */
#define CH_FLAG_MODE_MPOOL  (tmode_t)2U     /**< @brief Thread allocated
                                                 from a Memory Pool.        */
#define CH_FLAG_TERMINATE   (tmode_t)4U     /**< @brief Termination requested
                                                 flag.                      */
/** @} */

/*===========================================================================*/
/* Module pre-compile time settings.                                         */
/*===========================================================================*/

/*===========================================================================*/
/* Derived constants and error checks.                                       */
/*===========================================================================*/

#if !defined(CH_CFG_IDLE_ENTER_HOOK)
#error "CH_CFG_IDLE_ENTER_HOOK not defined in chconf.h"
#endif

#if !defined(CH_CFG_IDLE_LEAVE_HOOK)
#error "CH_CFG_IDLE_LEAVE_HOOK not defined in chconf.h"
#endif

#if !defined(CH_CFG_IDLE_LOOP_HOOK)
#error "CH_CFG_IDLE_LOOP_HOOK not defined in chconf.h"
#endif

/*===========================================================================*/
/* Module data structures and types.                                         */
/*===========================================================================*/

/**
 * @brief   Generic threads single link list, it works like a stack.
 */
struct ch_threads_list {
  thread_t              *next;      /**< @brief Next in the list/queue.     */
};

/**
 * @brief   Generic threads bidirectional linked list header and element.
 */
struct ch_threads_queue {
  thread_t              *next;      /**< @brief Next in the list/queue.     */
  thread_t              *prev;      /**< @brief Previous in the queue.      */
};

/**
 * @brief   Structure representing a thread.
 * @note    Not all the listed fields are always needed, by switching off some
 *          not needed ChibiOS/RT subsystems it is possible to save RAM space
 *          by shrinking this structure.
 */
struct ch_thread {
  threads_queue_t       queue;      /**< @brief Threads queue header.       */
  tprio_t               prio;       /**< @brief Thread priority.            */
  struct port_context   ctx;        /**< @brief Processor context.          */
#if (CH_CFG_USE_REGISTRY == TRUE) || defined(__DOXYGEN__)
  thread_t              *newer;     /**< @brief Newer registry element.     */
  thread_t              *older;     /**< @brief Older registry element.     */
#endif
  /* End of the fields shared with the ReadyList structure. */
#if (CH_CFG_USE_REGISTRY == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Thread name or @p NULL.
   */
  const char            *name;
#endif
#if (CH_DBG_ENABLE_STACK_CHECK == TRUE) || (CH_CFG_USE_DYNAMIC == TRUE) ||  \
    defined(__DOXYGEN__)
  /**
   * @brief   Working area base address.
   * @note    This pointer is used for stack overflow checks and for
   *          dynamic threading.
   */
  stkalign_t            *wabase;
#endif
  /**
   * @brief   Current thread state.
   */
  tstate_t              state;
  /**
   * @brief   Various thread flags.
   */
  tmode_t               flags;
#if (CH_CFG_USE_REGISTRY == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   References to this thread.
   */
  trefs_t               refs;
#endif
  /**
   * @brief   Number of ticks remaining to this thread.
   */
#if (CH_CFG_TIME_QUANTUM > 0) || defined(__DOXYGEN__)
  tslices_t             preempt;
#endif
#if (CH_DBG_THREADS_PROFILING == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Thread consumed time in ticks.
   * @note    This field can overflow.
   */
  volatile systime_t    time;
#endif
  /**
   * @brief   State-specific fields.
   * @note    All the fields declared in this union are only valid in the
   *          specified state or condition and are thus volatile.
   */
  union {
    /**
     * @brief   Thread wakeup code.
     * @note    This field contains the low level message sent to the thread
     *          by the waking thread or interrupt handler. The value is valid
     *          after exiting the @p chSchWakeupS() function.
     */
    msg_t               rdymsg;
    /**
     * @brief   Thread exit code.
     * @note    The thread termination code is stored in this field in order
     *          to be retrieved by the thread performing a @p chThdWait() on
     *          this thread.
     */
    msg_t               exitcode;
    /**
     * @brief   Pointer to a generic "wait" object.
     * @note    This field is used to get a generic pointer to a synchronization
     *          object and is valid when the thread is in one of the wait
     *          states.
     */
    void                *wtobjp;
    /**
     * @brief   Pointer to a generic thread reference object.
     * @note    This field is used to get a pointer to a synchronization
     *          object and is valid when the thread is in @p CH_STATE_SUSPENDED
     *          state.
     */
    thread_reference_t  *wttrp;
#if (CH_CFG_USE_MESSAGES == TRUE) || defined(__DOXYGEN__)
    /**
     * @brief   Thread sent message.
     */
    msg_t               sentmsg;
#endif
#if (CH_CFG_USE_SEMAPHORES == TRUE) || defined(__DOXYGEN__)
    /**
     * @brief   Pointer to a generic semaphore object.
     * @note    This field is used to get a pointer to a synchronization
     *          object and is valid when the thread is in @p CH_STATE_WTSEM
     *          state.
     */
    struct ch_semaphore *wtsemp;
#endif
#if (CH_CFG_USE_MUTEXES == TRUE) || defined(__DOXYGEN__)
    /**
     * @brief   Pointer to a generic mutex object.
     * @note    This field is used to get a pointer to a synchronization
     *          object and is valid when the thread is in @p CH_STATE_WTMTX
     *          state.
     */
    struct ch_mutex     *wtmtxp;
#endif
#if (CH_CFG_USE_EVENTS == TRUE) || defined(__DOXYGEN__)
    /**
     * @brief   Enabled events mask.
     * @note    This field is only valid while the thread is in the
     *          @p CH_STATE_WTOREVT or @p CH_STATE_WTANDEVT states.
     */
    eventmask_t         ewmask;
#endif
  }                     u;
#if (CH_CFG_USE_WAITEXIT == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Termination waiting list.
   */
  threads_list_t        waiting;
#endif
#if (CH_CFG_USE_MESSAGES == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Messages queue.
   */
  threads_queue_t       msgqueue;
#endif
#if (CH_CFG_USE_EVENTS == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Pending events mask.
   */
  eventmask_t           epending;
#endif
#if (CH_CFG_USE_MUTEXES == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   List of the mutexes owned by this thread.
   * @note    The list is terminated by a @p NULL in this field.
   */
  struct ch_mutex       *mtxlist;
  /**
   * @brief   Thread's own, non-inherited, priority.
   */
  tprio_t               realprio;
#endif
#if ((CH_CFG_USE_DYNAMIC == TRUE) && (CH_CFG_USE_MEMPOOLS == TRUE)) ||      \
    defined(__DOXYGEN__)
  /**
   * @brief   Memory Pool where the thread workspace is returned.
   */
  void                  *mpool;
#endif
#if (CH_DBG_STATISTICS == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Thread statistics.
   */
  time_measurement_t    stats;
#endif
#if defined(CH_CFG_THREAD_EXTRA_FIELDS)
  /* Extra fields defined in chconf.h.*/
  CH_CFG_THREAD_EXTRA_FIELDS
#endif
};

/**
 * @extends virtual_timers_list_t
 *
 * @brief   Virtual Timer descriptor structure.
 */
struct ch_virtual_timer {
  virtual_timer_t       *next;      /**< @brief Next timer in the list.     */
  virtual_timer_t       *prev;      /**< @brief Previous timer in the list. */
  systime_t             delta;      /**< @brief Time delta before timeout.  */
  vtfunc_t              func;       /**< @brief Timer callback function
                                                pointer.                    */
  void                  *par;       /**< @brief Timer callback function
                                                parameter.                  */
};

/**
 * @brief   Virtual timers list header.
 * @note    The timers list is implemented as a double link bidirectional list
 *          in order to make the unlink time constant, the reset of a virtual
 *          timer is often used in the code.
 */
struct ch_virtual_timers_list {
  virtual_timer_t       *next;      /**< @brief Next timer in the delta
                                                list.                       */
  virtual_timer_t       *prev;      /**< @brief Last timer in the delta
                                                list.                       */
  systime_t             delta;      /**< @brief Must be initialized to -1.  */
#if (CH_CFG_ST_TIMEDELTA == 0) || defined(__DOXYGEN__)
  volatile systime_t    systime;    /**< @brief System Time counter.        */
#endif
#if (CH_CFG_ST_TIMEDELTA > 0) || defined(__DOXYGEN__)
  /**
   * @brief   System time of the last tick event.
   */
  systime_t             lasttime;   /**< @brief System time of the last
                                                tick event.                 */
#endif
};

/**
 * @extends threads_queue_t
 */
struct ch_ready_list {
  threads_queue_t       queue;      /**< @brief Threads queue.              */
  tprio_t               prio;       /**< @brief This field must be
                                                initialized to zero.        */
  struct port_context   ctx;        /**< @brief Not used, present because
                                                offsets.                    */
#if (CH_CFG_USE_REGISTRY == TRUE) || defined(__DOXYGEN__)
  thread_t              *newer;     /**< @brief Newer registry element.     */
  thread_t              *older;     /**< @brief Older registry element.     */
#endif
  /* End of the fields shared with the thread_t structure.*/
  thread_t              *current;   /**< @brief The currently running
                                                thread.                     */
};

/**
 * @brief   System debug data structure.
 */
struct ch_system_debug {
  /**
   * @brief   Pointer to the panic message.
   * @details This pointer is meant to be accessed through the debugger, it is
   *          written once and then the system is halted.
   * @note    Accesses to this pointer must never be optimized out so the
   *          field itself is declared volatile.
   */
  const char            * volatile panic_msg;
#if (CH_DBG_SYSTEM_STATE_CHECK == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   ISR nesting level.
   */
  cnt_t                 isr_cnt;
  /**
   * @brief   Lock nesting level.
   */
  cnt_t                 lock_cnt;
#endif
#if (CH_DBG_TRACE_MASK != CH_DBG_TRACE_MASK_DISABLED) || defined(__DOXYGEN__)
  /**
   * @brief   Public trace buffer.
   */
  ch_trace_buffer_t     trace_buffer;
#endif
};

/**
 * @brief   System data structure.
 * @note    This structure contain all the data areas used by the OS except
 *          stacks.
 */
struct ch_system {
  /**
   * @brief   Ready list header.
   */
  ready_list_t          rlist;
  /**
   * @brief   Virtual timers delta list header.
   */
  virtual_timers_list_t vtlist;
  /**
   * @brief   System debug.
   */
  system_debug_t        dbg;
  /**
   * @brief   Main thread descriptor.
   */
  thread_t              mainthread;
#if (CH_CFG_USE_TM == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Time measurement calibration data.
   */
  tm_calibration_t      tm;
#endif
#if (CH_DBG_STATISTICS == TRUE) || defined(__DOXYGEN__)
  /**
   * @brief   Global kernel statistics.
   */
  kernel_stats_t        kernel_stats;
#endif
};

/*===========================================================================*/
/* Module macros.                                                            */
/*===========================================================================*/

/**
 * @brief   Returns the priority of the first thread on the given ready list.
 *
 * @notapi
 */
#define firstprio(rlp)  ((rlp)->next->prio)

/**
 * @brief   Current thread pointer access macro.
 * @note    This macro is not meant to be used in the application code but
 *          only from within the kernel, use @p chThdGetSelfX() instead.
 */
#define currp ch.rlist.current

/*===========================================================================*/
/* External declarations.                                                    */
/*===========================================================================*/

#if !defined(__DOXYGEN__)
extern ch_system_t ch;
#endif

/*
 * Scheduler APIs.
 */
#ifdef __cplusplus
extern "C" {
#endif
  void _scheduler_init(void);
  thread_t *chSchReadyI(thread_t *tp);
  thread_t *chSchReadyAheadI(thread_t *tp);
  void chSchGoSleepS(tstate_t newstate);
  msg_t chSchGoSleepTimeoutS(tstate_t newstate, systime_t time);
  void chSchWakeupS(thread_t *ntp, msg_t msg);
  void chSchRescheduleS(void);
  bool chSchIsPreemptionRequired(void);
  void chSchDoRescheduleBehind(void);
  void chSchDoRescheduleAhead(void);
  void chSchDoReschedule(void);
#if CH_CFG_OPTIMIZE_SPEED == FALSE
  void queue_prio_insert(thread_t *tp, threads_queue_t *tqp);
  void queue_insert(thread_t *tp, threads_queue_t *tqp);
  thread_t *queue_fifo_remove(threads_queue_t *tqp);
  thread_t *queue_lifo_remove(threads_queue_t *tqp);
  thread_t *queue_dequeue(thread_t *tp);
  void list_insert(thread_t *tp, threads_list_t *tlp);
  thread_t *list_remove(threads_list_t *tlp);
#endif /* CH_CFG_OPTIMIZE_SPEED == FALSE */
#ifdef __cplusplus
}
#endif

/*===========================================================================*/
/* Module inline functions.                                                  */
/*===========================================================================*/

/**
 * @brief   Threads list initialization.
 *
 * @param[in] tlp       pointer to the threads list object
 *
 * @notapi
 */
static inline void list_init(threads_list_t *tlp) {

  tlp->next = (thread_t *)tlp;
}

/**
 * @brief   Evaluates to @p true if the specified threads list is empty.
 *
 * @param[in] tlp       pointer to the threads list object
 * @return              The status of the list.
 *
 * @notapi
 */
static inline bool list_isempty(threads_list_t *tlp) {

  return (bool)(tlp->next == (thread_t *)tlp);
}

/**
 * @brief   Evaluates to @p true if the specified threads list is not empty.
 *
 * @param[in] tlp       pointer to the threads list object
 * @return              The status of the list.
 *
 * @notapi
 */
static inline bool list_notempty(threads_list_t *tlp) {

  return (bool)(tlp->next != (thread_t *)tlp);
}

/**
 * @brief   Threads queue initialization.
 *
 * @param[in] tqp       pointer to the threads queue object
 *
 * @notapi
 */
static inline void queue_init(threads_queue_t *tqp) {

  tqp->next = (thread_t *)tqp;
  tqp->prev = (thread_t *)tqp;
}

/**
 * @brief   Evaluates to @p true if the specified threads queue is empty.
 *
 * @param[in] tqp       pointer to the threads queue object
 * @return              The status of the queue.
 *
 * @notapi
 */
static inline bool queue_isempty(const threads_queue_t *tqp) {

  return (bool)(tqp->next == (const thread_t *)tqp);
}

/**
 * @brief   Evaluates to @p true if the specified threads queue is not empty.
 *
 * @param[in] tqp       pointer to the threads queue object
 * @return              The status of the queue.
 *
 * @notapi
 */
static inline bool queue_notempty(const threads_queue_t *tqp) {

  return (bool)(tqp->next != (const thread_t *)tqp);
}

/* If the performance code path has been chosen then all the following
   functions are inlined into the various kernel modules.*/
#if CH_CFG_OPTIMIZE_SPEED == TRUE
static inline void list_insert(thread_t *tp, threads_list_t *tlp) {

  tp->queue.next = tlp->next;
  tlp->next = tp;
}

static inline thread_t *list_remove(threads_list_t *tlp) {

  thread_t *tp = tlp->next;
  tlp->next = tp->queue.next;

  return tp;
}

static inline void queue_prio_insert(thread_t *tp, threads_queue_t *tqp) {

  thread_t *cp = (thread_t *)tqp;
  do {
    cp = cp->queue.next;
  } while ((cp != (thread_t *)tqp) && (cp->prio >= tp->prio));
  tp->queue.next             = cp;
  tp->queue.prev             = cp->queue.prev;
  tp->queue.prev->queue.next = tp;
  cp->queue.prev             = tp;
}

static inline void queue_insert(thread_t *tp, threads_queue_t *tqp) {

  tp->queue.next             = (thread_t *)tqp;
  tp->queue.prev             = tqp->prev;
  tp->queue.prev->queue.next = tp;
  tqp->prev                  = tp;
}

static inline thread_t *queue_fifo_remove(threads_queue_t *tqp) {
  thread_t *tp = tqp->next;

  tqp->next             = tp->queue.next;
  tqp->next->queue.prev = (thread_t *)tqp;

  return tp;
}

static inline thread_t *queue_lifo_remove(threads_queue_t *tqp) {
  thread_t *tp = tqp->prev;

  tqp->prev             = tp->queue.prev;
  tqp->prev->queue.next = (thread_t *)tqp;

  return tp;
}

static inline thread_t *queue_dequeue(thread_t *tp) {

  tp->queue.prev->queue.next = tp->queue.next;
  tp->queue.next->queue.prev = tp->queue.prev;

  return tp;
}
#endif /* CH_CFG_OPTIMIZE_SPEED == TRUE */

/**
 * @brief   Determines if the current thread must reschedule.
 * @details This function returns @p true if there is a ready thread with
 *          higher priority.
 *
 * @return              The priorities situation.
 * @retval false        if rescheduling is not necessary.
 * @retval true         if there is a ready thread at higher priority.
 *
 * @iclass
 */
static inline bool chSchIsRescRequiredI(void) {

  chDbgCheckClassI();

  return firstprio(&ch.rlist.queue) > currp->prio;
}

/**
 * @brief   Determines if yielding is possible.
 * @details This function returns @p true if there is a ready thread with
 *          equal or higher priority.
 *
 * @return              The priorities situation.
 * @retval false        if yielding is not possible.
 * @retval true         if there is a ready thread at equal or higher priority.
 *
 * @sclass
 */
static inline bool chSchCanYieldS(void) {

  chDbgCheckClassS();

  return firstprio(&ch.rlist.queue) >= currp->prio;
}

/**
 * @brief   Yields the time slot.
 * @details Yields the CPU control to the next thread in the ready list with
 *          equal or higher priority, if any.
 *
 * @sclass
 */
static inline void chSchDoYieldS(void) {

  chDbgCheckClassS();

  if (chSchCanYieldS()) {
    chSchDoRescheduleBehind();
  }
}

/**
 * @brief   Inline-able preemption code.
 * @details This is the common preemption code, this function must be invoked
 *          exclusively from the port layer.
 *
 * @special
 */
static inline void chSchPreemption(void) {
  tprio_t p1 = firstprio(&ch.rlist.queue);
  tprio_t p2 = currp->prio;

#if CH_CFG_TIME_QUANTUM > 0
  if (currp->preempt > (tslices_t)0) {
    if (p1 > p2) {
      chSchDoRescheduleAhead();
    }
  }
  else {
    if (p1 >= p2) {
      chSchDoRescheduleBehind();
    }
  }
#else /* CH_CFG_TIME_QUANTUM == 0 */
  if (p1 > p2) {
    chSchDoRescheduleAhead();
  }
#endif /* CH_CFG_TIME_QUANTUM == 0 */
}

#endif /* CHSCHD_H */

/** @} */


text:
// <copyright file="DelayCalculation.cs" company="MS">
// Copyright (c) 2016 MS.
// </copyright>

namespace MS.MulticastDownloader.Core.Server
{
    /// <summary>
    /// The delay calculation method.
    /// </summary>
    public enum DelayCalculation
    {
        /// <summary>
        /// Delay calculation by maximum throughput
        /// </summary>
        MaximumThroughput,

        /// <summary>
        /// Delay calculation by minimum throughput
        /// </summary>
        MinimumThroughput,

        /// <summary>
        /// Delay calculation by average throughput
        /// </summary>
        AverageThroughput
    }
}


text:
    text-align:center;
}

#hauntedwall image {
    transition-property: width, height, opacity;
    transition-duration: 8s;
    opacity:0;
    width:10px;
    height:10px;
}

#hauntedwall:hover image {
    opacity:0.5;
    width:100px;
    height:100px;
}


text:
A .NET implementation of FizzBuzz with NUnit tests.

By default, this library's `Get()` method will return "fizz" when a number is evenly divisible by 3, "buzz" when a number is evenly divisible by 5, and "fizzbuzz" when a number is evenly divisible by both.

Usage:
  * Reference FizzBuzzDotNet.dll in your project.
  * Create a new instance of the `FizzBuzzDotNet.Business.FizzBuzz` class.
  * Enumerate through the results using the `All()` method.
  * Arbitrary FizzBuzz elements can be fetched using the `Get()` method.
  * FizzBuzzDotNet supports removing the default rules and adding new ones.
  * Supports the full range of UInt64 numbers.

Custom Rules:
  A `FizzBuzz` instance supports adding or removing rules via its `Rules` object.  The order of the rules is significant.  It is OK to have more than one rule that applies for a given divisor.

**Example:**
```c#

var fb = new FizzBuzz();

fb.Get(30); //fizzbuzz

fb.Rules.Add(new Rule(2, "pop"));

fb.Get(30); //fizzbuzzpop

fb.Rules.Insert(0, new Rule(2, "bang")); //add at first index

fb.Get(30); //bangfizzbuzzpop

```

An example console application is available in the FizzBuzzConsole project.

To test, run NUnit against the `FizzBuzzTests.dll`.