text:
import Axon

from Axon.Component import component
from Axon.Ipc import WaitComplete, producerFinished, shutdownMicroprocess
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Visualisation.PhysicsGraph.chunks_to_lines import chunks_to_lines
from Kamaelia.Visualisation.PhysicsGraph.lines_to_tokenlists import lines_to_tokenlists as text_to_tokenlists

from Kamaelia.Apps.Whiteboard.Tokenisation import tokenlists_to_lines, lines_to_tokenlists

import sys

from Kamaelia.Apps.Whiteboard.Entuple import Entuple

class Timestamp(component):
    def shutdown(self):
        while self.dataReady("control"):
            msg = self.recv("control")
            self.send(msg,"signal")
            if isinstance(msg, (producerFinished, shutdownMicroprocess)):
                return True
        return False

    def main(self):
        import time
        start=time.time()

        while not self.shutdown():
            while self.dataReady("inbox"):
                data = self.recv("inbox")
                msg = str(time.time()-start) + " " + data
                self.send( msg, "outbox" )
            self.pause()
            yield 1

class DeTimestamp(component):
    Outboxes = { "outbox" : "Detimestamped string data",
                 "signal" : "Shutdown signalling",
                 "next"   : "Requests for more timestamped data (number of items needed)",
               }

    def shutdown(self):
        while self.dataReady("control"):
            msg = self.recv("control")
            if isinstance(msg, (producerFinished, shutdownMicroprocess)):
                return msg
        return False

    def main(self):
        import time
        start=None
        waiting = []
        shuttingdown=False
        BUFFERSIZE=10

        self.send(BUFFERSIZE, "next")

        while not shuttingdown or waiting or self.dataReady("inbox"):
            shuttingdown = shuttingdown or self.shutdown()

            if self.dataReady("inbox"):
                msg = self.recv("inbox")
                when, data = msg.split(" ",1)
                if start==None:
                    start=time.time()
                when = start+ float(when)
                waiting.append( (when,data) )

            sentcount=0
            while waiting and waiting[0][0] <= time.time():
                when, data = waiting.pop(0)
                self.send(data,"outbox")
                sentcount+=1
            if sentcount:
                self.send(sentcount, "next")

            if not waiting and not shuttingdown and not self.dataReady("inbox"):
                self.pause()
            yield 1
        self.send(shuttingdown,"signal")

class IntersperseNewlines(component):
    def shutdown(self):
        while self.dataReady("control"):
            msg = self.recv("control")
            self.send(msg,"signal")
            if isinstance(msg, (producerFinished, shutdownMicroprocess)):
                return True
        return False

    def main(self):
        while not self.shutdown():
            while self.dataReady("inbox"):
                data = self.recv("inbox")
                self.send( data, "outbox" )
                self.send("\n", "outbox" )
            self.pause()
            yield 1

if __name__=="__main__":
    from Kamaelia.Internet.TCPClient import TCPClient
    from Kamaelia.File.Reading import PromptedFileReader
    from Kamaelia.File.Writing import SimpleFileWriter
    from Kamaelia.Apps.Whiteboard.SingleShot import OneShot

    try:
        if "--help" in sys.argv:
            sys.stderr.write("Usage:\n    ./WhiteboardRecorder.py filename host port\n\n")
            sys.exit(0)
        filename = sys.argv[1]
        rhost = sys.argv[2]
        rport = int(sys.argv[3])
    except:
        sys.stderr.write("Usage:\n    ./WhiteboardRecorder.py filename host port\n\n")
        sys.exit(1)

    print "Recording..."
    Pipeline(
        OneShot(msg=[["GETIMG"]]),
        tokenlists_to_lines(),
        TCPClient(host=rhost, port=rport),
        chunks_to_lines(),
        Timestamp(),
        IntersperseNewlines(),
        SimpleFileWriter(filename),
    ).run()


text:
<?php

    class Model
    {
        private $db = null;

        /**
         * @param object $db A PDO database connection
         */
        function __construct()
        {
            try {
                $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
                $this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS, $options);

            } catch (PDOException $e) {
                exit('Database connection could not be established.');
            }
        }

    }

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author yzimroni
 */

package com.yanayzimroni.bukkit.offlinemessage;

import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;

import com.yanayzimroni.bukkit.offlinemessage.messages.ConfigMessagesManager;
import com.yanayzimroni.bukkit.offlinemessage.messages.MessagesManager;
import com.yanayzimroni.bukkit.offlinemessage.messages.MySqlMessagesManager;

public class OfflineMessagePlugin extends JavaPlugin implements Listener {
	private static MessagesManager messagesmanager;
	public static OfflineMessagePlugin plugin;

	@Override
	public void onEnable() {
		Bukkit.getPluginManager().registerEvents(this, this);
		getConfig().options().copyDefaults(true);
		saveConfig();
		System.out.println("OfflineMessage version " + super.getDescription().getVersion() + " enabled!");
		if (messagesmanager == null) {
			switch (getConfig().getString("manager_type")) {
			case "mysql":
				setMessagesManager(new MySqlMessagesManager(getConfig().getString("db_host"), getConfig().getInt("db_port"), getConfig().getString("db_name"), getConfig().getString("db_user"), getConfig().getString("db_pass"), getConfig().getString("db_prefix")));
				break;
			case "config":
			default:
				setMessagesManager(new ConfigMessagesManager(this));
				break;
			}
		}
		plugin = this;
	}

	@Override
	public void onDisable() {
		System.out.println("OfflineMessage version " + super.getDescription().getVersion() + " disabled!");
	}

	/**
	 * @return the messages manager
	 */
	public static MessagesManager getMessagesManager() {
		return messagesmanager;
	}

	/**
	 * @param messagesmanager
	 *            the messages manager to set
	 */
	public static void setMessagesManager(MessagesManager messagesmanager) {
		if (messagesmanager == null) {
			throw new NullPointerException("messagesmanager cannot be null!");
		}
		OfflineMessagePlugin.messagesmanager = messagesmanager;
		System.out.println("Message Manager set to " + messagesmanager.getType());
	}

	@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
	public void onPlayerJoin(final PlayerJoinEvent e) {
		if (!e.getPlayer().isOnline()) return;
		Runnable message_task = new Runnable() {
			@Override
			public void run() {
				List<String> messages = getMessagesManager().getMessages(e.getPlayer());
				if (messages != null && !messages.isEmpty()) {
					for (String message : messages) {
						String formattedmessage = message;
						formattedmessage = ChatColor.translateAlternateColorCodes('&', formattedmessage);
						formattedmessage = formattedmessage.replaceAll("%player%", e.getPlayer().getName());
						e.getPlayer().sendMessage(formattedmessage);
					}
					getMessagesManager().resetMessages(e.getPlayer());
				}
			}
		};
		if (getMessagesManager().isAsync()) {
			Bukkit.getScheduler().runTaskAsynchronously(this, message_task);
		} else {
			Bukkit.getScheduler().runTask(this, message_task);
		}
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <!--虚线, 需要配合 android:layerType="software" -->
    <stroke
        android:width="2dp"
        android:color="@color/base_white"
        android:dashGap="2dp"
        android:dashWidth="6dp"/>
</shape>


text:
short-description: Running external commands
...

# External commands

As a part of the software configuration, you may want to get extra
data by running external commands. The basic syntax is the following.

```meson
r = run_command('command', 'arg1', 'arg2', 'arg3')
if r.returncode() != 0
  # it failed
endif
output = r.stdout().strip()
errortxt = r.stderr().strip()
```

Since 0.52.0, you can pass the command environment as a dictionary:

```meson
run_command('command', 'arg1', 'arg2', env: {'FOO': 'bar'})
```

Since 0.50.0, you can also pass the command
[`environment`](Reference-manual.md#environment-object) object:

```meson
env = environment()
env.set('FOO', 'bar')
run_command('command', 'arg1', 'arg2', env: env)
```

The `run_command` function returns an object that can be queried for
return value and text written to stdout and stderr. The `strip` method
call is used to strip trailing and leading whitespace from
strings. Usually output from command line programs ends in a newline,
which is unwanted in string variables. The first argument can be
either a string or an executable you have detected earlier with
`find_program`.

Meson will autodetect scripts with a shebang line and run them with
the executable/interpreter specified in it both on Windows and on Unixes.

Note that you can not pass your command line as a single string. That
is, calling `run_command('do_something foo bar')` will not work. You
must either split up the string into separate arguments or pass the
split command as an array. It should also be noted that Meson will not
pass the command to the shell, so any command lines that try to use
things such as environment variables, backticks or pipelines will not
work. If you require shell semantics, write your command into a script
file and call that with `run_command`.


text:
package com.unikre.yandex.params;

public enum LookupFlag {
    FAMILY(0x0001),
    MORPHO(0x0004),
    POS_FILTER(0x0008);

    private final int bitmask;

    private LookupFlag(int bitmask) {
        this.bitmask = bitmask;
    }

    public int getBitmask() {
        return bitmask;
    }
}


text:
require 'test_helper'

class PregnancyTest < ActiveSupport::TestCase
  before do
    @user = create :user
    @pt_1 = create :patient, name: 'Susan Everywoman', primary_phone: '123-456-6789'
    @pt_2 = create :patient, name: 'Susan Everyteen', primary_phone: '123-456-6789'
    @pt_3 = create :patient, name: 'Susan Everygirl', secondary_phone: '999-999-9999'
    [@pt_1, @pt_2, @pt_3].each do |pt|
      create :pregnancy, patient: pt, created_by: @user
    end
    @pregnancy = @pt_1.pregnancies.first
  end

  describe 'validations' do
    it 'should be able to build an object' do
      assert @pregnancy.valid?
    end

    %w(initial_call_date created_by).each do |field|
      it "should enforce presence of #{field}" do
        @pregnancy[field.to_sym] = nil
        refute @pregnancy.valid?
      end
    end
  end

  describe 'search method' do
    it 'should respond to search' do
      assert Patient.respond_to? :search
    end

    it 'should find a patient' do
      assert_equal Patient.search('Susan Everywoman').count, 1
    end

    it 'should find multiple patients if there are multiple' do
      assert_equal Patient.search('123-456-6789').count, 2
    end

    it 'should be able to find based on secondary phones too' do
      assert_equal Patient.search('999-999-9999').count, 1
    end
  end

  describe 'status method' do
    it 'should default to "No Contact Made" when a pregnancy has no calls' do
      assert_equal 'No Contact Made', @pregnancy.status
    end

    it 'should default to "No Contact Made" when a pregnancy has an unsuccessful call' do
      create :call, pregnancy: @pregnancy, status: 'Left voicemail'
      assert_equal 'No Contact Made', @pregnancy.status
    end

    it 'should update to "Needs Appointment" once patient has been reached' do
      create :call, pregnancy: @pregnancy, status: 'Reached patient'
      assert_equal 'Needs Appointment', @pregnancy.status
    end

    it 'should update to "Fundraising" once an appointment has been made' do
      @pregnancy.appointment_date = '01/01/2017'
      assert_equal 'Fundraising', @pregnancy.status
    end

    # it 'should update to "Sent Pledge" after a pledge has been sent' do
    # end

    # it 'should update to "Pledge Paid" after a pledge has been paid' do
    # end

    # it 'should update to "Resolved Without DCAF" if a pregnancy is marked resolved' do
    # end
  end

  describe 'contact_made? method' do
    it 'should return false if no calls have been made' do
      refute @pregnancy.send :contact_made?
    end

    it 'should return false if an unsuccessful call has been made' do
      create :call, pregnancy: @pregnancy, status: 'Left voicemail'
      refute @pregnancy.send :contact_made?
    end

    it 'should return true if a successful call has been made' do
      create :call, pregnancy: @pregnancy, status: 'Reached patient'
      assert @pregnancy.send :contact_made?
    end
  end

  describe 'mongoid attachments' do
    it 'should have timestamps from Mongoid::Timestamps' do
      [:created_at, :updated_at].each do |field|
        assert @pregnancy.respond_to? field
        assert @pregnancy[field]
      end
    end

    it 'should respond to history methods' do
      assert @pregnancy.respond_to? :history_tracks
      assert @pregnancy.history_tracks.count > 0
    end

    it 'should have accessible userstamp methods' do
      assert @pregnancy.respond_to? :created_by
      assert @pregnancy.created_by
    end
  end
end


text:
package file

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"text/template"

	"github.com/Masterminds/sprig/v3"
	"github.com/traefik/paerser/file"
	"github.com/traefik/traefik/v2/pkg/config/dynamic"
	"github.com/traefik/traefik/v2/pkg/log"
	"github.com/traefik/traefik/v2/pkg/provider"
	"github.com/traefik/traefik/v2/pkg/safe"
	"github.com/traefik/traefik/v2/pkg/tls"
	"gopkg.in/fsnotify.v1"
)

const providerName = "file"

var _ provider.Provider = (*Provider)(nil)

// Provider holds configurations of the provider.
type Provider struct {
	Directory                 string `description:"Load dynamic configuration from one or more .yml or .toml files in a directory." json:"directory,omitempty" toml:"directory,omitempty" yaml:"directory,omitempty" export:"true"`
	Watch                     bool   `description:"Watch provider." json:"watch,omitempty" toml:"watch,omitempty" yaml:"watch,omitempty" export:"true"`
	Filename                  string `description:"Load dynamic configuration from a file." json:"filename,omitempty" toml:"filename,omitempty" yaml:"filename,omitempty" export:"true"`
	DebugLogGeneratedTemplate bool   `description:"Enable debug logging of generated configuration template." json:"debugLogGeneratedTemplate,omitempty" toml:"debugLogGeneratedTemplate,omitempty" yaml:"debugLogGeneratedTemplate,omitempty" export:"true"`
}

// SetDefaults sets the default values.
func (p *Provider) SetDefaults() {
	p.Watch = true
	p.Filename = ""
}

// Init the provider.
func (p *Provider) Init() error {
	return nil
}

// Provide allows the file provider to provide configurations to traefik
// using the given configuration channel.
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
	configuration, err := p.BuildConfiguration()
	if err != nil {
		return err
	}

	if p.Watch {
		var watchItem string

		switch {
		case len(p.Directory) > 0:
			watchItem = p.Directory
		case len(p.Filename) > 0:
			watchItem = filepath.Dir(p.Filename)
		default:
			return errors.New("error using file configuration provider, neither filename or directory defined")
		}

		if err := p.addWatcher(pool, watchItem, configurationChan, p.watcherCallback); err != nil {
			return err
		}
	}

	sendConfigToChannel(configurationChan, configuration)
	return nil
}

// BuildConfiguration loads configuration either from file or a directory
// specified by 'Filename'/'Directory' and returns a 'Configuration' object.
func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) {
	ctx := log.With(context.Background(), log.Str(log.ProviderName, providerName))

	if len(p.Directory) > 0 {
		return p.loadFileConfigFromDirectory(ctx, p.Directory, nil)
	}

	if len(p.Filename) > 0 {
		return p.loadFileConfig(ctx, p.Filename, true)
	}

	return nil, errors.New("error using file configuration provider, neither filename or directory defined")
}

func (p *Provider) addWatcher(pool *safe.Pool, directory string, configurationChan chan<- dynamic.Message, callback func(chan<- dynamic.Message, fsnotify.Event)) error {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("error creating file watcher: %w", err)
	}

	err = watcher.Add(directory)
	if err != nil {
		return fmt.Errorf("error adding file watcher: %w", err)
	}

	// Process events
	pool.GoCtx(func(ctx context.Context) {
		defer watcher.Close()
		for {
			select {
			case <-ctx.Done():
				return
			case evt := <-watcher.Events:
				if p.Directory == "" {
					_, evtFileName := filepath.Split(evt.Name)
					_, confFileName := filepath.Split(p.Filename)
					if evtFileName == confFileName {
						callback(configurationChan, evt)
					}
				} else {
					callback(configurationChan, evt)
				}
			case err := <-watcher.Errors:
				log.WithoutContext().WithField(log.ProviderName, providerName).Errorf("Watcher event error: %s", err)
			}
		}
	})
	return nil
}

func (p *Provider) watcherCallback(configurationChan chan<- dynamic.Message, event fsnotify.Event) {
	watchItem := p.Filename
	if len(p.Directory) > 0 {
		watchItem = p.Directory
	}

	logger := log.WithoutContext().WithField(log.ProviderName, providerName)

	if _, err := os.Stat(watchItem); err != nil {
		logger.Errorf("Unable to watch %s : %v", watchItem, err)
		return
	}

	configuration, err := p.BuildConfiguration()
	if err != nil {
		logger.Errorf("Error occurred during watcher callback: %s", err)
		return
	}

	sendConfigToChannel(configurationChan, configuration)
}

func sendConfigToChannel(configurationChan chan<- dynamic.Message, configuration *dynamic.Configuration) {
	configurationChan <- dynamic.Message{
		ProviderName:  "file",
		Configuration: configuration,
	}
}

func (p *Provider) loadFileConfig(ctx context.Context, filename string, parseTemplate bool) (*dynamic.Configuration, error) {
	var err error
	var configuration *dynamic.Configuration
	if parseTemplate {
		configuration, err = p.CreateConfiguration(ctx, filename, template.FuncMap{}, false)
	} else {
		configuration, err = p.DecodeConfiguration(filename)
	}
	if err != nil {
		return nil, err
	}

	if configuration.TLS != nil {
		configuration.TLS.Certificates = flattenCertificates(ctx, configuration.TLS)

		// TLS Options
		if configuration.TLS.Options != nil {
			for name, options := range configuration.TLS.Options {
				var caCerts []tls.FileOrContent

				for _, caFile := range options.ClientAuth.CAFiles {
					content, err := caFile.Read()
					if err != nil {
						log.FromContext(ctx).Error(err)
						continue
					}

					caCerts = append(caCerts, tls.FileOrContent(content))
				}
				options.ClientAuth.CAFiles = caCerts

				configuration.TLS.Options[name] = options
			}
		}

		// TLS stores
		if len(configuration.TLS.Stores) > 0 {
			for name, store := range configuration.TLS.Stores {
				if store.DefaultCertificate == nil {
					continue
				}

				content, err := store.DefaultCertificate.CertFile.Read()
				if err != nil {
					log.FromContext(ctx).Error(err)
					continue
				}
				store.DefaultCertificate.CertFile = tls.FileOrContent(content)

				content, err = store.DefaultCertificate.KeyFile.Read()
				if err != nil {
					log.FromContext(ctx).Error(err)
					continue
				}
				store.DefaultCertificate.KeyFile = tls.FileOrContent(content)

				configuration.TLS.Stores[name] = store
			}
		}
	}

	// ServersTransport
	if configuration.HTTP != nil && len(configuration.HTTP.ServersTransports) > 0 {
		for name, st := range configuration.HTTP.ServersTransports {
			var certificates []tls.Certificate
			for _, cert := range st.Certificates {
				content, err := cert.CertFile.Read()
				if err != nil {
					log.FromContext(ctx).Error(err)
					continue
				}
				cert.CertFile = tls.FileOrContent(content)

				content, err = cert.KeyFile.Read()
				if err != nil {
					log.FromContext(ctx).Error(err)
					continue
				}
				cert.KeyFile = tls.FileOrContent(content)

				certificates = append(certificates, cert)
			}

			configuration.HTTP.ServersTransports[name].Certificates = certificates

			var rootCAs []tls.FileOrContent
			for _, rootCA := range st.RootCAs {
				content, err := rootCA.Read()
				if err != nil {
					log.FromContext(ctx).Error(err)
					continue
				}

				rootCAs = append(rootCAs, tls.FileOrContent(content))
			}

			st.RootCAs = rootCAs
		}
	}

	return configuration, nil
}

func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores {
	var certs []*tls.CertAndStores
	for _, cert := range tlsConfig.Certificates {
		content, err := cert.Certificate.CertFile.Read()
		if err != nil {
			log.FromContext(ctx).Error(err)
			continue
		}
		cert.Certificate.CertFile = tls.FileOrContent(string(content))

		content, err = cert.Certificate.KeyFile.Read()
		if err != nil {
			log.FromContext(ctx).Error(err)
			continue
		}
		cert.Certificate.KeyFile = tls.FileOrContent(string(content))

		certs = append(certs, cert)
	}

	return certs
}

func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory string, configuration *dynamic.Configuration) (*dynamic.Configuration, error) {
	fileList, err := os.ReadDir(directory)
	if err != nil {
		return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err)
	}

	if configuration == nil {
		configuration = &dynamic.Configuration{
			HTTP: &dynamic.HTTPConfiguration{
				Routers:           make(map[string]*dynamic.Router),
				Middlewares:       make(map[string]*dynamic.Middleware),
				Services:          make(map[string]*dynamic.Service),
				ServersTransports: make(map[string]*dynamic.ServersTransport),
			},
			TCP: &dynamic.TCPConfiguration{
				Routers:     make(map[string]*dynamic.TCPRouter),
				Services:    make(map[string]*dynamic.TCPService),
				Middlewares: make(map[string]*dynamic.TCPMiddleware),
			},
			TLS: &dynamic.TLSConfiguration{
				Stores:  make(map[string]tls.Store),
				Options: make(map[string]tls.Options),
			},
			UDP: &dynamic.UDPConfiguration{
				Routers:  make(map[string]*dynamic.UDPRouter),
				Services: make(map[string]*dynamic.UDPService),
			},
		}
	}

	configTLSMaps := make(map[*tls.CertAndStores]struct{})

	for _, item := range fileList {
		logger := log.FromContext(log.With(ctx, log.Str("filename", item.Name())))

		if item.IsDir() {
			configuration, err = p.loadFileConfigFromDirectory(ctx, filepath.Join(directory, item.Name()), configuration)
			if err != nil {
				return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %w", item, err)
			}
			continue
		}

		switch strings.ToLower(filepath.Ext(item.Name())) {
		case ".toml", ".yaml", ".yml":
			// noop
		default:
			continue
		}

		var c *dynamic.Configuration
		c, err = p.loadFileConfig(ctx, filepath.Join(directory, item.Name()), true)
		if err != nil {
			return configuration, fmt.Errorf("%s: %w", filepath.Join(directory, item.Name()), err)
		}

		for name, conf := range c.HTTP.Routers {
			if _, exists := configuration.HTTP.Routers[name]; exists {
				logger.WithField(log.RouterName, name).Warn("HTTP router already configured, skipping")
			} else {
				configuration.HTTP.Routers[name] = conf
			}
		}

		for name, conf := range c.HTTP.Middlewares {
			if _, exists := configuration.HTTP.Middlewares[name]; exists {
				logger.WithField(log.MiddlewareName, name).Warn("HTTP middleware already configured, skipping")
			} else {
				configuration.HTTP.Middlewares[name] = conf
			}
		}

		for name, conf := range c.HTTP.Services {
			if _, exists := configuration.HTTP.Services[name]; exists {
				logger.WithField(log.ServiceName, name).Warn("HTTP service already configured, skipping")
			} else {
				configuration.HTTP.Services[name] = conf
			}
		}

		for name, conf := range c.HTTP.ServersTransports {
			if _, exists := configuration.HTTP.ServersTransports[name]; exists {
				logger.WithField(log.ServersTransportName, name).Warn("HTTP servers transport already configured, skipping")
			} else {
				configuration.HTTP.ServersTransports[name] = conf
			}
		}

		for name, conf := range c.TCP.Routers {
			if _, exists := configuration.TCP.Routers[name]; exists {
				logger.WithField(log.RouterName, name).Warn("TCP router already configured, skipping")
			} else {
				configuration.TCP.Routers[name] = conf
			}
		}

		for name, conf := range c.TCP.Middlewares {
			if _, exists := configuration.TCP.Middlewares[name]; exists {
				logger.WithField(log.MiddlewareName, name).Warn("TCP middleware already configured, skipping")
			} else {
				configuration.TCP.Middlewares[name] = conf
			}
		}

		for name, conf := range c.TCP.Services {
			if _, exists := configuration.TCP.Services[name]; exists {
				logger.WithField(log.ServiceName, name).Warn("TCP service already configured, skipping")
			} else {
				configuration.TCP.Services[name] = conf
			}
		}

		for name, conf := range c.UDP.Routers {
			if _, exists := configuration.UDP.Routers[name]; exists {
				logger.WithField(log.RouterName, name).Warn("UDP router already configured, skipping")
			} else {
				configuration.UDP.Routers[name] = conf
			}
		}

		for name, conf := range c.UDP.Services {
			if _, exists := configuration.UDP.Services[name]; exists {
				logger.WithField(log.ServiceName, name).Warn("UDP service already configured, skipping")
			} else {
				configuration.UDP.Services[name] = conf
			}
		}

		for _, conf := range c.TLS.Certificates {
			if _, exists := configTLSMaps[conf]; exists {
				logger.Warnf("TLS configuration %v already configured, skipping", conf)
			} else {
				configTLSMaps[conf] = struct{}{}
			}
		}

		for name, conf := range c.TLS.Options {
			if _, exists := configuration.TLS.Options[name]; exists {
				logger.Warnf("TLS options %v already configured, skipping", name)
			} else {
				if configuration.TLS.Options == nil {
					configuration.TLS.Options = map[string]tls.Options{}
				}
				configuration.TLS.Options[name] = conf
			}
		}

		for name, conf := range c.TLS.Stores {
			if _, exists := configuration.TLS.Stores[name]; exists {
				logger.Warnf("TLS store %v already configured, skipping", name)
			} else {
				if configuration.TLS.Stores == nil {
					configuration.TLS.Stores = map[string]tls.Store{}
				}
				configuration.TLS.Stores[name] = conf
			}
		}
	}

	if len(configTLSMaps) > 0 && configuration.TLS == nil {
		configuration.TLS = &dynamic.TLSConfiguration{}
	}

	for conf := range configTLSMaps {
		configuration.TLS.Certificates = append(configuration.TLS.Certificates, conf)
	}

	return configuration, nil
}

// CreateConfiguration creates a provider configuration from content using templating.
func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) {
	tmplContent, err := readFile(filename)
	if err != nil {
		return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
	}

	defaultFuncMap := sprig.TxtFuncMap()
	defaultFuncMap["normalize"] = provider.Normalize
	defaultFuncMap["split"] = strings.Split
	for funcID, funcElement := range funcMap {
		defaultFuncMap[funcID] = funcElement
	}

	tmpl := template.New(p.Filename).Funcs(defaultFuncMap)

	_, err = tmpl.Parse(tmplContent)
	if err != nil {
		return nil, err
	}

	var buffer bytes.Buffer
	err = tmpl.Execute(&buffer, templateObjects)
	if err != nil {
		return nil, err
	}

	renderedTemplate := buffer.String()
	if p.DebugLogGeneratedTemplate {
		logger := log.FromContext(ctx)
		logger.Debugf("Template content: %s", tmplContent)
		logger.Debugf("Rendering results: %s", renderedTemplate)
	}

	return p.decodeConfiguration(filename, renderedTemplate)
}

// DecodeConfiguration Decodes a *types.Configuration from a content.
func (p *Provider) DecodeConfiguration(filename string) (*dynamic.Configuration, error) {
	content, err := readFile(filename)
	if err != nil {
		return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
	}

	return p.decodeConfiguration(filename, content)
}

func (p *Provider) decodeConfiguration(filePath, content string) (*dynamic.Configuration, error) {
	configuration := &dynamic.Configuration{
		HTTP: &dynamic.HTTPConfiguration{
			Routers:           make(map[string]*dynamic.Router),
			Middlewares:       make(map[string]*dynamic.Middleware),
			Services:          make(map[string]*dynamic.Service),
			ServersTransports: make(map[string]*dynamic.ServersTransport),
		},
		TCP: &dynamic.TCPConfiguration{
			Routers:     make(map[string]*dynamic.TCPRouter),
			Services:    make(map[string]*dynamic.TCPService),
			Middlewares: make(map[string]*dynamic.TCPMiddleware),
		},
		TLS: &dynamic.TLSConfiguration{
			Stores:  make(map[string]tls.Store),
			Options: make(map[string]tls.Options),
		},
		UDP: &dynamic.UDPConfiguration{
			Routers:  make(map[string]*dynamic.UDPRouter),
			Services: make(map[string]*dynamic.UDPService),
		},
	}

	err := file.DecodeContent(content, strings.ToLower(filepath.Ext(filePath)), configuration)
	if err != nil {
		return nil, err
	}

	return configuration, nil
}

func readFile(filename string) (string, error) {
	if len(filename) > 0 {
		buf, err := os.ReadFile(filename)
		if err != nil {
			return "", err
		}
		return string(buf), nil
	}
	return "", fmt.Errorf("invalid filename: %s", filename)
}


text:
//
/*
=======================================================================

GAME OPTIONS MENU

=======================================================================
*/

#include "ui_local.h"

#define ART_FRAMEL "menu/" MENU_ART_DIR "/frame2_l"
#define ART_FRAMER "menu/" MENU_ART_DIR "/frame1_r"
#define ART_BACK0 "menu/" MENU_ART_DIR "/back_0"
#define ART_BACK1 "menu/" MENU_ART_DIR "/back_1"

#define PREFERENCES_X_POS 360

#define ID_CROSSHAIR 127
#define ID_SIMPLEITEMS 128
#define ID_HIGHQUALITYSKY 129
#define ID_EJECTINGBRASS 130
#define ID_WALLMARKS 131
#define ID_DYNAMICLIGHTS 132
#define ID_IDENTIFYTARGET 133
#define ID_SYNCEVERYFRAME 134
#define ID_FORCEMODEL 135
#define ID_DRAWTEAMOVERLAY 136
#define ID_ALLOWDOWNLOAD 137
#define ID_BACK 138
//Elimination
#define ID_WEAPONBAR 139
#define ID_DELAGHITSCAN 140
#define ID_COLORRED 141
#define ID_COLORGREEN 142
#define ID_COLORBLUE 143
#define ID_CROSSHAIRHEALTH 144
#define ID_CHATBEEP 145
#define ID_TEAMCHATBEEP 146

#undef NUM_CROSSHAIRS
#define NUM_CROSSHAIRS 99

typedef struct {
    menuframework_s menu;

    menutext_s banner;
    menubitmap_s framel;
    menubitmap_s framer;

    menulist_s crosshair;
    menuradiobutton_s crosshairHealth;

    //Crosshair colors:
    menuslider_s crosshairColorRed;
    menuslider_s crosshairColorGreen;
    menuslider_s crosshairColorBlue;

    menuradiobutton_s simpleitems;
    menuradiobutton_s alwaysweaponbar;
    menuradiobutton_s brass;
    menuradiobutton_s wallmarks;
    menuradiobutton_s dynamiclights;
    menuradiobutton_s identifytarget;
    menuradiobutton_s highqualitysky;
    menuradiobutton_s synceveryframe;
    menuradiobutton_s forcemodel;
    menulist_s drawteamoverlay;
    menuradiobutton_s delaghitscan;
    menuradiobutton_s allowdownload;
    menuradiobutton_s chatbeep;
    menuradiobutton_s teamchatbeep;
    menubitmap_s back;

    qhandle_t crosshairShader[NUM_CROSSHAIRS];
} preferences_t;

static preferences_t s_preferences;

static const char* teamoverlay_names[] = {
    "off",
    "upper right",
    "lower right",
    "lower left",
    NULL
};

static void Preferences_SetMenuItems(void) {
    s_preferences.crosshair.curvalue = (int)trap_Cvar_VariableValue("cg_drawCrosshair") % NUM_CROSSHAIRS;
    s_preferences.crosshairHealth.curvalue = trap_Cvar_VariableValue("cg_crosshairHealth") != 0;
    s_preferences.crosshairColorRed.curvalue = trap_Cvar_VariableValue("cg_crosshairColorRed") * 255.0f;
    s_preferences.crosshairColorGreen.curvalue = trap_Cvar_VariableValue("cg_crosshairColorGreen") * 255.0f;
    s_preferences.crosshairColorBlue.curvalue = trap_Cvar_VariableValue("cg_crosshairColorBlue") * 255.0f;
    s_preferences.simpleitems.curvalue = trap_Cvar_VariableValue("cg_simpleItems") != 0;
    s_preferences.alwaysweaponbar.curvalue = trap_Cvar_VariableValue("cg_alwaysWeaponBar") != 0;
    s_preferences.brass.curvalue = trap_Cvar_VariableValue("cg_brassTime") != 0;
    s_preferences.wallmarks.curvalue = trap_Cvar_VariableValue("cg_marks") != 0;
    s_preferences.identifytarget.curvalue = trap_Cvar_VariableValue("cg_drawCrosshairNames") != 0;
    s_preferences.dynamiclights.curvalue = trap_Cvar_VariableValue("r_dynamiclight") != 0;
    s_preferences.highqualitysky.curvalue = trap_Cvar_VariableValue("r_fastsky") == 0;
    s_preferences.synceveryframe.curvalue = trap_Cvar_VariableValue("r_finish") != 0;
    s_preferences.forcemodel.curvalue = trap_Cvar_VariableValue("cg_forcemodel") != 0;
    s_preferences.drawteamoverlay.curvalue = Com_Clamp(0, 3, trap_Cvar_VariableValue("cg_drawTeamOverlay"));
    s_preferences.allowdownload.curvalue = trap_Cvar_VariableValue("cl_allowDownload") != 0;
    s_preferences.delaghitscan.curvalue = trap_Cvar_VariableValue("cg_delag") != 0;
    s_preferences.chatbeep.curvalue = trap_Cvar_VariableValue("cg_chatBeep") != 0;
    s_preferences.teamchatbeep.curvalue = trap_Cvar_VariableValue("cg_teamChatBeep") != 0;
}

static void Preferences_Event(void* ptr, int notification) {
    if (notification != QM_ACTIVATED) {
        return;
    }
    switch (((menucommon_s*)ptr)->id) {
    case ID_CROSSHAIR:
        s_preferences.crosshair.curvalue++;
        if (s_preferences.crosshair.curvalue == NUM_CROSSHAIRS || s_preferences.crosshairShader[s_preferences.crosshair.curvalue] == 0) {
            s_preferences.crosshair.curvalue = 0;
        }
        trap_Cvar_SetValue("cg_drawCrosshair", s_preferences.crosshair.curvalue);
        break;
    case ID_CROSSHAIRHEALTH:
        trap_Cvar_SetValue("cg_crosshairHealth", s_preferences.crosshairHealth.curvalue);
        if (s_preferences.crosshairHealth.curvalue) {
            //If crosshairHealth is on: Don't allow color selection
            s_preferences.crosshairColorRed.generic.flags |= QMF_INACTIVE;
            s_preferences.crosshairColorGreen.generic.flags |= QMF_INACTIVE;
            s_preferences.crosshairColorBlue.generic.flags |= QMF_INACTIVE;
        } else {
            //If crosshairHealth is off: Allow color selection
            s_preferences.crosshairColorRed.generic.flags &= ~QMF_INACTIVE;
            s_preferences.crosshairColorGreen.generic.flags &= ~QMF_INACTIVE;
            s_preferences.crosshairColorBlue.generic.flags &= ~QMF_INACTIVE;
        }
        break;
    case ID_COLORRED:
        trap_Cvar_SetValue("cg_crosshairColorRed", ((float)s_preferences.crosshairColorRed.curvalue) / 255.f);
        break;
    case ID_COLORGREEN:
        trap_Cvar_SetValue("cg_crosshairColorGreen", ((float)s_preferences.crosshairColorGreen.curvalue) / 255.f);
        break;
    case ID_COLORBLUE:
        trap_Cvar_SetValue("cg_crosshairColorBlue", ((float)s_preferences.crosshairColorBlue.curvalue) / 255.f);
        break;
    case ID_SIMPLEITEMS:
        trap_Cvar_SetValue("cg_simpleItems", s_preferences.simpleitems.curvalue);
        break;
    case ID_WEAPONBAR:
        trap_Cvar_SetValue("cg_alwaysWeaponBar", s_preferences.alwaysweaponbar.curvalue);
        break;
    case ID_HIGHQUALITYSKY:
        trap_Cvar_SetValue("r_fastsky", !s_preferences.highqualitysky.curvalue);
        break;
    case ID_EJECTINGBRASS:
        if (s_preferences.brass.curvalue) {
            trap_Cvar_Reset("cg_brassTime");
        } else {
            trap_Cvar_SetValue("cg_brassTime", 0);
        }
        break;
    case ID_WALLMARKS:
        trap_Cvar_SetValue("cg_marks", s_preferences.wallmarks.curvalue);
        break;
    case ID_DYNAMICLIGHTS:
        trap_Cvar_SetValue("r_dynamiclight", s_preferences.dynamiclights.curvalue);
        break;
    case ID_IDENTIFYTARGET:
        trap_Cvar_SetValue("cg_drawCrosshairNames", s_preferences.identifytarget.curvalue);
        break;
    case ID_SYNCEVERYFRAME:
        trap_Cvar_SetValue("r_finish", s_preferences.synceveryframe.curvalue);
        break;
    case ID_FORCEMODEL:
        trap_Cvar_SetValue("cg_forcemodel", s_preferences.forcemodel.curvalue);
        break;
    case ID_DRAWTEAMOVERLAY:
        trap_Cvar_SetValue("cg_drawTeamOverlay", s_preferences.drawteamoverlay.curvalue);
        break;
    case ID_ALLOWDOWNLOAD:
        trap_Cvar_SetValue("cl_allowDownload", s_preferences.allowdownload.curvalue);
        trap_Cvar_SetValue("sv_allowDownload", s_preferences.allowdownload.curvalue);
        break;
    case ID_DELAGHITSCAN:
        trap_Cvar_SetValue("g_delagHitscan", s_preferences.delaghitscan.curvalue);
        trap_Cvar_SetValue("cg_delag", s_preferences.delaghitscan.curvalue);
        break;
    case ID_CHATBEEP:
        trap_Cvar_SetValue("cg_chatBeep", s_preferences.chatbeep.curvalue);
        break;
    case ID_TEAMCHATBEEP:
        trap_Cvar_SetValue("cg_teamChatBeep", s_preferences.teamchatbeep.curvalue);
        break;
    case ID_BACK:
        UI_PopMenu();
        break;
    }
}

/*
=================
Crosshair_Draw
=================
*/
static void Crosshair_Draw(void* self) {
    menulist_s* s;
    float* color;
    int x, y;
    int style;
    qboolean focus;
    vec4_t color4;
    s = (menulist_s*)self;
    x = s->generic.x;
    y = s->generic.y;
    style = UI_SMALLFONT;
    focus = (s->generic.parent->cursor == s->generic.menuPosition);
    if (s->generic.flags & QMF_GRAYED) {
        color = text_color_disabled;
    } else if (focus) {
        color = text_color_highlight;
        style |= UI_PULSE;
    } else if (s->generic.flags & QMF_BLINK) {
        color = text_color_highlight;
        style |= UI_BLINK;
    } else {
        color = text_color_normal;
    }
    if (focus) {
        // draw cursor
        UI_FillRect(s->generic.left, s->generic.top, s->generic.right - s->generic.left + 1, s->generic.bottom - s->generic.top + 1, listbar_color);
        UI_DrawChar(x, y, 13, UI_CENTER | UI_BLINK | UI_SMALLFONT, color);
    }
    UI_DrawString(x - SMALLCHAR_WIDTH, y, s->generic.name, style | UI_RIGHT, color);
    if (!s->curvalue) {
        return;
    }
    color4[0] = ((float)s_preferences.crosshairColorRed.curvalue) / 255.f;
    color4[1] = ((float)s_preferences.crosshairColorGreen.curvalue) / 255.f;
    color4[2] = ((float)s_preferences.crosshairColorBlue.curvalue) / 255.f;
    color4[3] = 1.0f;
    trap_R_SetColor(color4);
    UI_DrawHandlePic(x + SMALLCHAR_WIDTH, y - 4, 24, 24, s_preferences.crosshairShader[s->curvalue]);
}

static void Preferences_MenuInit(void) {
    int y;
    UI_SetDefaultCvar("cg_crosshairHealth", "1");
    UI_SetDefaultCvar("cg_crosshairColorRed", "1");
    UI_SetDefaultCvar("cg_crosshairColorBlue", "1");
    UI_SetDefaultCvar("cg_crosshairColorGreen", "1");
    memset(&s_preferences, 0, sizeof(preferences_t));
    Preferences_Cache();
    s_preferences.menu.wrapAround = qtrue;
    s_preferences.menu.fullscreen = qtrue;
    s_preferences.banner.generic.type = MTYPE_BTEXT;
    s_preferences.banner.generic.x = 320;
    s_preferences.banner.generic.y = 16;
    s_preferences.banner.string = "GAME OPTIONS";
    s_preferences.banner.color = color_white;
    s_preferences.banner.style = UI_CENTER;
    s_preferences.framel.generic.type = MTYPE_BITMAP;
    s_preferences.framel.generic.name = ART_FRAMEL;
    s_preferences.framel.generic.flags = QMF_INACTIVE;
    s_preferences.framel.generic.x = 0;
    s_preferences.framel.generic.y = 78;
    s_preferences.framel.width = 256;
    s_preferences.framel.height = 329;
    s_preferences.framer.generic.type = MTYPE_BITMAP;
    s_preferences.framer.generic.name = ART_FRAMER;
    s_preferences.framer.generic.flags = QMF_INACTIVE;
    s_preferences.framer.generic.x = 376;
    s_preferences.framer.generic.y = 76;
    s_preferences.framer.width = 256;
    s_preferences.framer.height = 334;
    y = 82;
    s_preferences.crosshair.generic.type = MTYPE_TEXT;
    s_preferences.crosshair.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT | QMF_NODEFAULTINIT | QMF_OWNERDRAW;
    s_preferences.crosshair.generic.x = PREFERENCES_X_POS;
    s_preferences.crosshair.generic.y = y;
    s_preferences.crosshair.generic.name = "Crosshair:";
    s_preferences.crosshair.generic.callback = Preferences_Event;
    s_preferences.crosshair.generic.ownerdraw = Crosshair_Draw;
    s_preferences.crosshair.generic.id = ID_CROSSHAIR;
    s_preferences.crosshair.generic.top = y - 4;
    s_preferences.crosshair.generic.bottom = y + 20;
    s_preferences.crosshair.generic.left = PREFERENCES_X_POS - ((strlen(s_preferences.crosshair.generic.name) + 1) * SMALLCHAR_WIDTH);
    s_preferences.crosshair.generic.right = PREFERENCES_X_POS + 48;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.crosshairHealth.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.crosshairHealth.generic.name = "Crosshair shows health:";
    s_preferences.crosshairHealth.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.crosshairHealth.generic.callback = Preferences_Event;
    s_preferences.crosshairHealth.generic.id = ID_CROSSHAIRHEALTH;
    s_preferences.crosshairHealth.generic.x = PREFERENCES_X_POS;
    s_preferences.crosshairHealth.generic.y = y;
    y += BIGCHAR_HEIGHT;
    s_preferences.crosshairColorRed.generic.type = MTYPE_SLIDER;
    s_preferences.crosshairColorRed.generic.name = "Crosshair red:";
    s_preferences.crosshairColorRed.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.crosshairColorRed.generic.callback = Preferences_Event;
    s_preferences.crosshairColorRed.generic.id = ID_COLORRED;
    s_preferences.crosshairColorRed.generic.x = PREFERENCES_X_POS;
    s_preferences.crosshairColorRed.generic.y = y;
    s_preferences.crosshairColorRed.minvalue = 0.0f;
    s_preferences.crosshairColorRed.maxvalue = 255.0f;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.crosshairColorGreen.generic.type = MTYPE_SLIDER;
    s_preferences.crosshairColorGreen.generic.name = "Crosshair green:";
    s_preferences.crosshairColorGreen.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.crosshairColorGreen.generic.callback = Preferences_Event;
    s_preferences.crosshairColorGreen.generic.id = ID_COLORGREEN;
    s_preferences.crosshairColorGreen.generic.x = PREFERENCES_X_POS;
    s_preferences.crosshairColorGreen.generic.y = y;
    s_preferences.crosshairColorGreen.minvalue = 0.0f;
    s_preferences.crosshairColorGreen.maxvalue = 255.0f;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.crosshairColorBlue.generic.type = MTYPE_SLIDER;
    s_preferences.crosshairColorBlue.generic.name = "Crosshair blue:";
    s_preferences.crosshairColorBlue.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.crosshairColorBlue.generic.callback = Preferences_Event;
    s_preferences.crosshairColorBlue.generic.id = ID_COLORBLUE;
    s_preferences.crosshairColorBlue.generic.x = PREFERENCES_X_POS;
    s_preferences.crosshairColorBlue.generic.y = y;
    s_preferences.crosshairColorBlue.minvalue = 0.0f;
    s_preferences.crosshairColorBlue.maxvalue = 255.0f;
    if (s_preferences.crosshairHealth.curvalue) {
        s_preferences.crosshairColorRed.generic.flags |= QMF_INACTIVE;
        s_preferences.crosshairColorGreen.generic.flags |= QMF_INACTIVE;
        s_preferences.crosshairColorBlue.generic.flags |= QMF_INACTIVE;
    }
    y += BIGCHAR_HEIGHT + 2 + 4;
    s_preferences.simpleitems.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.simpleitems.generic.name = "Simple Items:";
    s_preferences.simpleitems.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.simpleitems.generic.callback = Preferences_Event;
    s_preferences.simpleitems.generic.id = ID_SIMPLEITEMS;
    s_preferences.simpleitems.generic.x = PREFERENCES_X_POS;
    s_preferences.simpleitems.generic.y = y;
    //Elimination
    y += BIGCHAR_HEIGHT;
    s_preferences.alwaysweaponbar.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.alwaysweaponbar.generic.name = "Always show weapons:";
    s_preferences.alwaysweaponbar.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.alwaysweaponbar.generic.callback = Preferences_Event;
    s_preferences.alwaysweaponbar.generic.id = ID_WEAPONBAR;
    s_preferences.alwaysweaponbar.generic.x = PREFERENCES_X_POS;
    s_preferences.alwaysweaponbar.generic.y = y;
    y += BIGCHAR_HEIGHT;
    s_preferences.wallmarks.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.wallmarks.generic.name = "Marks on Walls:";
    s_preferences.wallmarks.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.wallmarks.generic.callback = Preferences_Event;
    s_preferences.wallmarks.generic.id = ID_WALLMARKS;
    s_preferences.wallmarks.generic.x = PREFERENCES_X_POS;
    s_preferences.wallmarks.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.brass.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.brass.generic.name = "Ejecting Brass:";
    s_preferences.brass.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.brass.generic.callback = Preferences_Event;
    s_preferences.brass.generic.id = ID_EJECTINGBRASS;
    s_preferences.brass.generic.x = PREFERENCES_X_POS;
    s_preferences.brass.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.dynamiclights.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.dynamiclights.generic.name = "Dynamic Lights:";
    s_preferences.dynamiclights.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.dynamiclights.generic.callback = Preferences_Event;
    s_preferences.dynamiclights.generic.id = ID_DYNAMICLIGHTS;
    s_preferences.dynamiclights.generic.x = PREFERENCES_X_POS;
    s_preferences.dynamiclights.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.identifytarget.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.identifytarget.generic.name = "Identify Target:";
    s_preferences.identifytarget.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.identifytarget.generic.callback = Preferences_Event;
    s_preferences.identifytarget.generic.id = ID_IDENTIFYTARGET;
    s_preferences.identifytarget.generic.x = PREFERENCES_X_POS;
    s_preferences.identifytarget.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.highqualitysky.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.highqualitysky.generic.name = "High Quality Sky:";
    s_preferences.highqualitysky.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.highqualitysky.generic.callback = Preferences_Event;
    s_preferences.highqualitysky.generic.id = ID_HIGHQUALITYSKY;
    s_preferences.highqualitysky.generic.x = PREFERENCES_X_POS;
    s_preferences.highqualitysky.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.synceveryframe.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.synceveryframe.generic.name = "Sync Every Frame:";
    s_preferences.synceveryframe.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.synceveryframe.generic.callback = Preferences_Event;
    s_preferences.synceveryframe.generic.id = ID_SYNCEVERYFRAME;
    s_preferences.synceveryframe.generic.x = PREFERENCES_X_POS;
    s_preferences.synceveryframe.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.forcemodel.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.forcemodel.generic.name = "Force Player Models:";
    s_preferences.forcemodel.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.forcemodel.generic.callback = Preferences_Event;
    s_preferences.forcemodel.generic.id = ID_FORCEMODEL;
    s_preferences.forcemodel.generic.x = PREFERENCES_X_POS;
    s_preferences.forcemodel.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.drawteamoverlay.generic.type = MTYPE_SPINCONTROL;
    s_preferences.drawteamoverlay.generic.name = "Draw Team Overlay:";
    s_preferences.drawteamoverlay.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.drawteamoverlay.generic.callback = Preferences_Event;
    s_preferences.drawteamoverlay.generic.id = ID_DRAWTEAMOVERLAY;
    s_preferences.drawteamoverlay.generic.x = PREFERENCES_X_POS;
    s_preferences.drawteamoverlay.generic.y = y;
    s_preferences.drawteamoverlay.itemnames = teamoverlay_names;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.delaghitscan.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.delaghitscan.generic.name = "Unlag hitscan:";
    s_preferences.delaghitscan.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.delaghitscan.generic.callback = Preferences_Event;
    s_preferences.delaghitscan.generic.id = ID_DELAGHITSCAN;
    s_preferences.delaghitscan.generic.x = PREFERENCES_X_POS;
    s_preferences.delaghitscan.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.allowdownload.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.allowdownload.generic.name = "Automatic Downloading:";
    s_preferences.allowdownload.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.allowdownload.generic.callback = Preferences_Event;
    s_preferences.allowdownload.generic.id = ID_ALLOWDOWNLOAD;
    s_preferences.allowdownload.generic.x = PREFERENCES_X_POS;
    s_preferences.allowdownload.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.chatbeep.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.chatbeep.generic.name = "Beep on chat:";
    s_preferences.chatbeep.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.chatbeep.generic.callback = Preferences_Event;
    s_preferences.chatbeep.generic.id = ID_CHATBEEP;
    s_preferences.chatbeep.generic.x = PREFERENCES_X_POS;
    s_preferences.chatbeep.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.teamchatbeep.generic.type = MTYPE_RADIOBUTTON;
    s_preferences.teamchatbeep.generic.name = "Beep on team chat:";
    s_preferences.teamchatbeep.generic.flags = QMF_PULSEIFFOCUS | QMF_SMALLFONT;
    s_preferences.teamchatbeep.generic.callback = Preferences_Event;
    s_preferences.teamchatbeep.generic.id = ID_TEAMCHATBEEP;
    s_preferences.teamchatbeep.generic.x = PREFERENCES_X_POS;
    s_preferences.teamchatbeep.generic.y = y;
    y += BIGCHAR_HEIGHT + 2;
    s_preferences.back.generic.type = MTYPE_BITMAP;
    s_preferences.back.generic.name = ART_BACK0;
    s_preferences.back.generic.flags = QMF_LEFT_JUSTIFY | QMF_PULSEIFFOCUS;
    s_preferences.back.generic.callback = Preferences_Event;
    s_preferences.back.generic.id = ID_BACK;
    s_preferences.back.generic.x = 0;
    s_preferences.back.generic.y = 480 - 64;
    s_preferences.back.width = 128;
    s_preferences.back.height = 64;
    s_preferences.back.focuspic = ART_BACK1;
    Menu_AddItem(&s_preferences.menu, &s_preferences.banner);
    Menu_AddItem(&s_preferences.menu, &s_preferences.framel);
    Menu_AddItem(&s_preferences.menu, &s_preferences.framer);
    Menu_AddItem(&s_preferences.menu, &s_preferences.crosshair);
    Menu_AddItem(&s_preferences.menu, &s_preferences.crosshairHealth);
    Menu_AddItem(&s_preferences.menu, &s_preferences.crosshairColorRed);
    Menu_AddItem(&s_preferences.menu, &s_preferences.crosshairColorGreen);
    Menu_AddItem(&s_preferences.menu, &s_preferences.crosshairColorBlue);
    Menu_AddItem(&s_preferences.menu, &s_preferences.simpleitems);
    Menu_AddItem(&s_preferences.menu, &s_preferences.alwaysweaponbar);
    Menu_AddItem(&s_preferences.menu, &s_preferences.wallmarks);
    Menu_AddItem(&s_preferences.menu, &s_preferences.brass);
    Menu_AddItem(&s_preferences.menu, &s_preferences.dynamiclights);
    Menu_AddItem(&s_preferences.menu, &s_preferences.identifytarget);
    Menu_AddItem(&s_preferences.menu, &s_preferences.highqualitysky);
    Menu_AddItem(&s_preferences.menu, &s_preferences.synceveryframe);
    Menu_AddItem(&s_preferences.menu, &s_preferences.forcemodel);
    Menu_AddItem(&s_preferences.menu, &s_preferences.drawteamoverlay);
    Menu_AddItem(&s_preferences.menu, &s_preferences.delaghitscan);
    Menu_AddItem(&s_preferences.menu, &s_preferences.allowdownload);
    Menu_AddItem(&s_preferences.menu, &s_preferences.teamchatbeep);
    Menu_AddItem(&s_preferences.menu, &s_preferences.chatbeep);
    Menu_AddItem(&s_preferences.menu, &s_preferences.back);
    Preferences_SetMenuItems();
}

/*
===============
Preferences_Cache
===============
*/
void Preferences_Cache(void) {
    int n;
    trap_R_RegisterShaderNoMip(ART_FRAMEL);
    trap_R_RegisterShaderNoMip(ART_FRAMER);
    trap_R_RegisterShaderNoMip(ART_BACK0);
    trap_R_RegisterShaderNoMip(ART_BACK1);
    for (n = 0; n < NUM_CROSSHAIRS; n++) {
        if (n < 10) {
            s_preferences.crosshairShader[n] = trap_R_RegisterShaderNoMip(va("gfx/2d/crosshair%c", 'a' + n));
        } else {
            s_preferences.crosshairShader[n] = trap_R_RegisterShaderNoMip(va("gfx/2d/crosshair%02d", n - 10));
        }
    }
}

/*
===============
UI_PreferencesMenu
===============
*/
void UI_PreferencesMenu(void) {
    Preferences_MenuInit();
    UI_PushMenu(&s_preferences.menu);
}


text:
package com.peterpotts.mobius

case class Tensor(left: Matrix, right: Matrix) {
  lazy val transpose = Tensor(Matrix(left.left, right.left), Matrix(left.right, right.right))
  lazy val gcd = left.gcd gcd right.gcd
  lazy val normal = gcd == BigInt(0) || gcd == BigInt(1)
  lazy val normalize = if (normal) this else this / gcd
  lazy val magnitude = left.magnitude max right.magnitude
  lazy val valid = left.valid && right.valid
  lazy val min = Matrix(left.min, right.min).min
  lazy val max = Matrix(left.max, right.max).max

  lazy val isPositive =
    left.left.signum == left.right.signum &&
      left.right.signum == right.left.signum &&
      right.left.signum == right.right.signum &&
      right.right.signum != 0

  lazy val info = Matrix(max, min)
  lazy val empty = info.isPositive == info.inverse.isPositive

  def isSubsetOf(that: Matrix): Boolean = (that.inverse * this).isPositive

  def *(that: BigInt): Tensor = Tensor(left * that, right * that)

  def /(that: BigInt): Tensor = Tensor(left / that, right / that)

  def *(that: Vector): Matrix = transpose ** that

  def **(that: Vector): Matrix = Matrix(left * that, right * that)

  def *(that: Matrix): Tensor = (transpose ** that).transpose

  def **(that: Matrix): Tensor = Tensor(left * that, right * that)
}

object Tensor {
  val plus = Tensor(Matrix(Vector(0, 0), Vector(1, 0)), Matrix(Vector(1, 0), Vector(0, 1)))
  val minus = Tensor(Matrix(Vector(0, 0), Vector(1, 0)), Matrix(Vector(-1, 0), Vector(0, 1)))
  val times = Tensor(Matrix(Vector(1, 0), Vector(0, 0)), Matrix(Vector(0, 0), Vector(0, 1)))
  val divide = Tensor(Matrix(Vector(0, 0), Vector(1, 0)), Matrix(Vector(0, 1), Vector(0, 0)))
}


text:
'use strict';

var fs = require('fs');
var vm = require('vm');
var context = vm.createContext({});

var file = fs.readFileSync('./build/webpack.js', 'utf8');

module.exports = function () {
    vm.runInContext(file, context);
};


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.05.03 at 03:15:27 PM EDT
//

package API.amazon.mws.xml.JAXB;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

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

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="value" maxOccurs="unbounded" minOccurs="0">
 *           <simpleType>
 *             <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *               <enumeration value="3do"/>
 *               <enumeration value="atari_2600"/>
 *               <enumeration value="atari_jaguar"/>
 *               <enumeration value="atari_st"/>
 *               <enumeration value="be_os"/>
 *               <enumeration value="colecovision"/>
 *               <enumeration value="cybiko"/>
 *               <enumeration value="dos"/>
 *               <enumeration value="dreamcast"/>
 *               <enumeration value="electronic_games"/>
 *               <enumeration value="epoc"/>
 *               <enumeration value="game_boy_advance"/>
 *               <enumeration value="gameboy"/>
 *               <enumeration value="gameboy_color"/>
 *               <enumeration value="gamecube"/>
 *               <enumeration value="linux"/>
 *               <enumeration value="mac_os_9_0_and_below"/>
 *               <enumeration value="mac_os_x"/>
 *               <enumeration value="mac_os_x_cheetah"/>
 *               <enumeration value="mac_os_x_intel"/>
 *               <enumeration value="mac_os_x_jaguar"/>
 *               <enumeration value="mac_os_x_leopard"/>
 *               <enumeration value="mac_os_x_panther"/>
 *               <enumeration value="mac_os_x_puma"/>
 *               <enumeration value="mac_os_x_tiger"/>
 *               <enumeration value="macintosh"/>
 *               <enumeration value="microsoft_xbox_360"/>
 *               <enumeration value="microsoft_xp_media_center"/>
 *               <enumeration value="n_gage"/>
 *               <enumeration value="neo_geo"/>
 *               <enumeration value="neo_geo_pocket"/>
 *               <enumeration value="netware"/>
 *               <enumeration value="nintendo_NES"/>
 *               <enumeration value="nintendo_super_NES"/>
 *               <enumeration value="nintendo64"/>
 *               <enumeration value="no_operating_system"/>
 *               <enumeration value="not_machine_specific"/>
 *               <enumeration value="os/2"/>
 *               <enumeration value="palm"/>
 *               <enumeration value="pda"/>
 *               <enumeration value="playstation"/>
 *               <enumeration value="playstation_2"/>
 *               <enumeration value="pocket_pc"/>
 *               <enumeration value="pocket_pc_2002"/>
 *               <enumeration value="pocket_pc_2003"/>
 *               <enumeration value="powermac"/>
 *               <enumeration value="sega_game_gear"/>
 *               <enumeration value="sega_genesis"/>
 *               <enumeration value="sega_master_system"/>
 *               <enumeration value="sega_mega_cd"/>
 *               <enumeration value="sega_saturn"/>
 *               <enumeration value="sony_playstation3"/>
 *               <enumeration value="sony_psp"/>
 *               <enumeration value="sun_solaris"/>
 *               <enumeration value="super_nintendo"/>
 *               <enumeration value="trs_80"/>
 *               <enumeration value="unix"/>
 *               <enumeration value="virtual_boy"/>
 *               <enumeration value="windows"/>
 *               <enumeration value="windows_2000_server"/>
 *               <enumeration value="windows_2003_server"/>
 *               <enumeration value="windows_mobile"/>
 *               <enumeration value="windows_mobile_2003"/>
 *               <enumeration value="windows_mobile_5"/>
 *               <enumeration value="windows_vista"/>
 *               <enumeration value="windows_vista_business"/>
 *               <enumeration value="windows_vista_enterprise"/>
 *               <enumeration value="windows_vista_home_basic"/>
 *               <enumeration value="windows_vista_home_premium"/>
 *               <enumeration value="windows_vista_ultimate"/>
 *               <enumeration value="windows_xp"/>
 *               <enumeration value="windows_xp_home"/>
 *               <enumeration value="windows_xp_professional"/>
 *               <enumeration value="windows_xp_tablet_pc"/>
 *               <enumeration value="windows2000"/>
 *               <enumeration value="windows3_1"/>
 *               <enumeration value="windows3_x"/>
 *               <enumeration value="windows95"/>
 *               <enumeration value="windows98"/>
 *               <enumeration value="windowsCE"/>
 *               <enumeration value="windowsME"/>
 *               <enumeration value="windowsNT"/>
 *               <enumeration value="windowsNT3_5"/>
 *               <enumeration value="windowsNT4"/>
 *               <enumeration value="windowsNT5"/>
 *               <enumeration value="wonderswan"/>
 *               <enumeration value="wonderswan_color"/>
 *               <enumeration value="xbox"/>
 *             </restriction>
 *           </simpleType>
 *         </element>
 *       </sequence>
 *       <attribute name="delete" type="{}BooleanType" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "value"
})
@XmlRootElement(name = "platform")
public class Platform {

    protected List<String> value;
    @XmlAttribute(name = "delete")
    protected BooleanType delete;

    /**
     * Gets the value of the value property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the value property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getValue().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link String }
     *
     *
     */
    public List<String> getValue() {
        if (value == null) {
            value = new ArrayList<String>();
        }
        return this.value;
    }

    /**
     * Gets the value of the delete property.
     *
     * @return
     *     possible object is
     *     {@link BooleanType }
     *
     */
    public BooleanType getDelete() {
        return delete;
    }

    /**
     * Sets the value of the delete property.
     *
     * @param value
     *     allowed object is
     *     {@link BooleanType }
     *
     */
    public void setDelete(BooleanType value) {
        this.delete = value;
    }

}


text:
package com.wills.help.utils;

import android.util.Log;

public class LogUtils {

    public static void v(String tag, String message) {
        if(AppConfig.TEST) {
            Log.v(tag, message);
        }
    }

    public static void d(String tag, String message) {
        if(AppConfig.TEST) {
            Log.d(tag, message);
        }
    }

    public static void i(String tag, String message) {
        if(AppConfig.TEST) {
            Log.i(tag, message);
        }
    }

    public static void w(String tag, String message) {
        if(AppConfig.TEST) {
            Log.w(tag, message);
        }
    }

    public static void e(String tag, String message) {
        if(AppConfig.TEST) {
            Log.e(tag, message);
        }
    }

    public static void e(String tag, String message, Exception e) {
        if(AppConfig.TEST) {
            Log.e(tag, message, e);
        }
    }
}


text:
$( document ).ready( function() {
	pingNotificationsTimeout();
	displayIdentifierSchemes();
} );

var pingTimeout = null;

function importDataValue()
{
	if ( !$( "#upload" ).val() )
	{
		setHeaderDelayMessage( "Please select a file to upload" );
		return false;
	}

	$( "#notificationTable" ).empty();
	$( "#importForm" ).submit();
}

function pingNotificationsTimeout()
{
	pingNotifications( 'DATAVALUE_IMPORT', 'notificationTable', displaySummaryLink );
	pingTimeout = setTimeout( "pingNotificationsTimeout()", 2500 );
}

function displaySummaryLink()
{
	var html = '
	Display import summary
';
	$( '#notificationTable' ).prepend( html );
}

function displaySummary()
{
	$( '#notificationDiv' ).hide();
	$( '#importSummaryDiv' ).show( 'fast' ).load( 'getDataValueImportSummary.action' );
}

function toggleOptions()
{
	$( ".moreOptions" ).toggle();
}

function displayIdentifierSchemes() {
	displayIdentifierScheme( "dataElementIdScheme", "filter=dataElementAttribute:eq:true" );
	displayIdentifierScheme( "orgUnitIdScheme", "filter=organisationUnitAttribute:eq:true" );
	displayIdentifierScheme( "idScheme", "filter=dataElementAttribute:eq:true&filter=organisationUnitAttribute:eq:true" );
}

function displayIdentifierScheme( id, filter ) {

	var url = "../api/attributes?fields=id,displayName&filter=unique:eq:true&" + filter;

	$.getJSON( url, function( json ) {
		var html = "";
		$.each( json.attributes, function( inx, attr ) {
			html += "<option value=\"ATTRIBUTE:" + attr.id + "\">" + attr.displayName + "</option>";
		} );

		$( "#" + id ).append( html );
	} );
}


text:
import { Component, OnInit, OnChanges, SimpleChanges, OnDestroy, Input } from '@angular/core';
import {Subscription, Observable} from 'rxjs';

import {TableViewComponent} from '../table-view/table-view.component';
import {SearchResponse} from '../../../model/search-response';
import {SearchService} from '../../../service/search.service';
import {TreeGroupData, TreeAlertsSubscription} from './tree-group-data';
import {GroupResponse} from '../../../model/group-response';
import {GroupResult} from '../../../model/group-result';
import {SortField} from '../../../model/sort-field';
import {Sort} from '../../../utils/enums';
import {ElasticsearchUtils} from '../../../utils/elasticsearch-utils';
import {SearchRequest} from '../../../model/search-request';
import {MetaAlertCreateRequest} from '../../../model/meta-alert-create-request';
import {MetaAlertService} from '../../../service/meta-alert.service';
import {INDEXES, MAX_ALERTS_IN_META_ALERTS} from '../../../utils/constants';
import {UpdateService} from '../../../service/update.service';
import {PatchRequest} from '../../../model/patch-request';
import {GetRequest} from '../../../model/get-request';
import { GlobalConfigService } from '../../../service/global-config.service';
import { DialogService } from '../../../service/dialog.service';
import { DialogType } from 'app/model/dialog-type';
import { ConfirmationType } from 'app/model/confirmation-type';

@Component({
  selector: 'app-tree-view',
  templateUrl: './tree-view.component.html',
  styleUrls: ['./tree-view.component.scss']
})

export class TreeViewComponent extends TableViewComponent implements OnInit, OnChanges, OnDestroy {

  @Input() globalConfig: {} = {};
  groupByFields: string[] = [];
  topGroups: TreeGroupData[] = [];
  groupResponse: GroupResponse = new GroupResponse();
  treeGroupSubscriptionMap: {[key: string]: TreeAlertsSubscription } = {};
  alertsChangedSubscription: Subscription;
  configSubscription: Subscription;
  dialogService: DialogService

  constructor(searchService: SearchService,
              updateService: UpdateService,
              metaAlertService: MetaAlertService,
              globalConfigService: GlobalConfigService,
              dialogService: DialogService) {
    super(searchService, updateService, metaAlertService, globalConfigService, dialogService);
  }

  addAlertChangedListner() {
    this.alertsChangedSubscription = this.updateService.alertChanged$.subscribe(patchRequest => {
      this.updateAlert(patchRequest);
    });
  }

  removeAlertChangedLister() {
    this.alertsChangedSubscription.unsubscribe();
  }

  collapseGroup(groupArray: TreeGroupData[], level: number, index: number) {
    for (let i = index + 1; i < groupArray.length; i++) {
      if (groupArray[i].level > (level)) {
        groupArray[i].show = false;
        groupArray[i].expand = false;
      } else {
        break;
      }
    }
  }

  createQuery(selectedGroup: TreeGroupData) {
    let searchQuery = this.queryBuilder.generateSelect();
    let groupQery = Object.keys(selectedGroup.groupQueryMap).map(key => {
      return key.replace(/:/g, '\\:') +
          ':' +
          String(selectedGroup.groupQueryMap[key])
          .replace(/[\*\+\-=~><\"\?^\${}\(\)\:\!\/[\]\\\s]/g, '\\$&') // replace single  special characters
          .replace(/\|\|/g, '\\||') // replace ||
          .replace(/\&\&/g, '\\&&'); // replace &&
    }).join(' AND ');

    groupQery += searchQuery === '*' ? '' : (' AND ' + searchQuery);
    return groupQery;
  }

  expandGroup(groupArray: TreeGroupData[], level: number, index: number) {
    for (let i = index + 1; i < groupArray.length; i++) {
      if (groupArray[i].level === (level + 1)) {
        groupArray[i].show = true;
      } else {
        break;
      }
    }
  }

  getAlerts(selectedGroup: TreeGroupData): Subscription {
    let searchRequest = new SearchRequest();
    searchRequest.query = this.createQuery(selectedGroup);
    searchRequest.from = selectedGroup.pagingData.from;
    searchRequest.size = selectedGroup.pagingData.size;
    searchRequest.sort = selectedGroup.sortField ? [selectedGroup.sortField] : [];

    return this.searchGroup(selectedGroup, searchRequest);
  }

  getGroups() {
    let groupRequest = this.getGroupRequest();
    groupRequest.query = this.queryBuilder.generateSelect();

    this.searchService.groups(groupRequest).subscribe(groupResponse => {
      this.updateGroupData(groupResponse);
    });
  }

  updateGroupData(groupResponse) {
    this.selectedAlerts = [];
    this.groupResponse = groupResponse;
    this.parseTopLevelGroup();
  }

  groupPageChange(group: TreeGroupData) {
    this.getAlerts(group);
  }

  createTopGroups(groupByFields: string[]) {
    this.topGroups = [];
    this.treeGroupSubscriptionMap = {};

    this.groupResponse.groupResults.forEach((groupResult: GroupResult) => {
      let treeGroupData = new TreeGroupData(groupResult.key, groupResult.total, groupResult.score, 0, false);
      treeGroupData.isLeafNode = (groupByFields.length === 1);

      if (groupByFields.length === 1) {
        treeGroupData.groupQueryMap  = this.createTopGroupQueryMap(groupByFields[0], groupResult);
      }

      this.topGroups.push(treeGroupData);
    });
  }

  createTopGroupQueryMap(groupByFields: string, groupResult: GroupResult) {
    let groupQueryMap = {};
    groupQueryMap[groupByFields] = groupResult.key;
    return groupQueryMap;
  }

  initTopGroups() {
    let groupByFields =  this.getGroupRequest().groups.map(group => group.field);
    let currentTopGroupKeys = this.groupResponse.groupResults.map(groupResult => groupResult.key);
    let previousTopGroupKeys = this.topGroups.map(group => group.key);

    if (this.topGroups.length === 0 || JSON.stringify(this.groupByFields) !== JSON.stringify(groupByFields) ||
        JSON.stringify(currentTopGroupKeys) !== JSON.stringify(previousTopGroupKeys)) {
      this.createTopGroups(groupByFields);
    }

    this.groupByFields = groupByFields;
  }

  search(resetPaginationParams = true, pageSize: number = null) {
    this.getGroups();
  }

  ngOnChanges(changes: SimpleChanges) {
    if ((changes['alerts'] && changes['alerts'].currentValue)) {
      this.search();
    }
  }

  ngOnInit() {
    this.addAlertChangedListner();
  }

  ngOnDestroy(): void {
    this.removeAlertChangedLister();
  }

  searchGroup(selectedGroup: TreeGroupData, searchRequest: SearchRequest): Subscription {
    return this.searchService.search(searchRequest).subscribe(results => {
      this.setData(selectedGroup, results);
    }, error => {
      this.dialogService.launchDialog(ElasticsearchUtils.extractESErrorMessage(error), DialogType.Error);
    });
  }

  setData(selectedGroup: TreeGroupData, results: SearchResponse) {
    selectedGroup.response.results = results.results;
    selectedGroup.pagingData.total = results.total;
    selectedGroup.total = results.total;

    this.topGroups.map(topGroup => {
      if (topGroup.treeSubGroups.length > 0) {
        topGroup.total = topGroup.treeSubGroups.reduce((total, subGroup) => { return total + subGroup.total; }, 0);
      }
    });
  }

  checkAndToSubscription(group: TreeGroupData) {
    if (group.isLeafNode) {
      let key = JSON.stringify(group.groupQueryMap);
      if (this.treeGroupSubscriptionMap[key]) {
        this.removeFromSubscription(group);
      }

      let subscription = this.getAlerts(group);
      this.treeGroupSubscriptionMap[key] = new TreeAlertsSubscription(subscription, group);
    }
  }

  removeFromSubscription(group: TreeGroupData) {
    if (group.isLeafNode) {
      let key = JSON.stringify(group.groupQueryMap);
      let subscription = this.treeGroupSubscriptionMap[key].refreshTimer;
      if (subscription && !subscription.closed) {
        subscription.unsubscribe();
      }
      delete this.treeGroupSubscriptionMap[key];
    }
  }

  toggleSubGroups(topLevelGroup: TreeGroupData, selectedGroup: TreeGroupData, index: number) {
    selectedGroup.expand = !selectedGroup.expand;

    if (selectedGroup.expand) {
      this.expandGroup(topLevelGroup.treeSubGroups, selectedGroup.level, index);
      this.checkAndToSubscription(selectedGroup);
    } else {
      this.collapseGroup(topLevelGroup.treeSubGroups, selectedGroup.level, index);
      this.removeFromSubscription(selectedGroup);
    }
  }

  toggleTopLevelGroup(group: TreeGroupData) {
    group.expand = !group.expand;
    group.show = !group.show;

    if (group.expand) {
      this.checkAndToSubscription(group);
    } else {
      this.removeFromSubscription(group);
    }
  }

  parseSubGroups(group: GroupResult, groupAsArray: TreeGroupData[],
                 parentQueryMap: {[key: string]: string}, currentGroupKey: string, level: number, index: number): number {
    index++;

    let currentTreeNodeData = (groupAsArray.length > 0) ? groupAsArray[index] : null;

    if (currentTreeNodeData && (currentTreeNodeData.key === group.key) && (currentTreeNodeData.level === level)) {
      currentTreeNodeData.total = group.total;
    } else {
      let newTreeNodeData = new TreeGroupData(group.key, group.total, group.score, level, level === 1);
      if (!currentTreeNodeData) {
        groupAsArray.push(newTreeNodeData);
      } else {
        groupAsArray.splice(index, 1, newTreeNodeData);
      }
    }

    groupAsArray[index].isLeafNode = false;
    groupAsArray[index].groupQueryMap = JSON.parse(JSON.stringify(parentQueryMap));
    groupAsArray[index].groupQueryMap[currentGroupKey] = group.key;

    if (!group.groupResults) {
      groupAsArray[index].isLeafNode = true;
      if (groupAsArray[index].expand && groupAsArray[index].show && groupAsArray[index].groupQueryMap) {
        this.checkAndToSubscription(groupAsArray[index]);
      }
      return index;
    }

    group.groupResults.forEach(subGroup => {
      index = this.parseSubGroups(subGroup, groupAsArray, groupAsArray[index].groupQueryMap, group.groupedBy, level + 1, index);
    });

    return index;
  }

  parseTopLevelGroup() {
    let groupedBy = this.groupResponse.groupedBy;

    this.initTopGroups();

    for (let i = 0; i < this.groupResponse.groupResults.length; i++) {
      let index = -1;
      let topGroup = this.topGroups[i];
      let resultGroup = this.groupResponse.groupResults[i];

      topGroup.total = resultGroup.total;
      topGroup.groupQueryMap = this.createTopGroupQueryMap(groupedBy, resultGroup);

      if (resultGroup.groupResults) {
        resultGroup.groupResults.forEach(subGroup => {
          index = this.parseSubGroups(subGroup, topGroup.treeSubGroups, topGroup.groupQueryMap, resultGroup.groupedBy, 1, index);
        });

        topGroup.treeSubGroups.splice(index + 1);
      }
    }

    if (this.groupByFields.length === 1) {
      this.refreshAllExpandedGroups();
    }
  }

  sortTreeSubGroup($event, treeGroup: TreeGroupData) {
    let sortBy = $event.sortBy === 'id' ? '_uid' : $event.sortBy;
    let sortOrder = $event.sortOrder === Sort.ASC ? 'asc' : 'desc';
    let sortField = new SortField(sortBy, sortOrder);

    treeGroup.sortEvent = $event;
    treeGroup.sortField = sortField;
    treeGroup.treeSubGroups.forEach(treeSubGroup => treeSubGroup.sortField = sortField);

    this.refreshAllExpandedGroups();
  }

  selectAllGroupRows($event, group: TreeGroupData) {
    this.selectedAlerts = [];

    if ($event.target.checked) {
      if (group.expand && group.show && group.response) {
        this.selectedAlerts = group.response.results;
      }

      group.treeSubGroups.forEach(subGroup => {
        if (subGroup.expand && subGroup.show && subGroup.response) {
          this.selectedAlerts = this.selectedAlerts.concat(subGroup.response.results);
        }
      });
    }

    this.onSelectedAlertsChange.emit(this.selectedAlerts);
  }

  refreshAllExpandedGroups() {
    Object.keys(this.treeGroupSubscriptionMap).forEach(key => {
      this.getAlerts(this.treeGroupSubscriptionMap[key].group);
    });
  }

  canCreateMetaAlert(count: number) {
    if (count > MAX_ALERTS_IN_META_ALERTS) {
      let errorMessage = 'Meta Alert cannot have more than ' + MAX_ALERTS_IN_META_ALERTS +' alerts within it';
      this.dialogService.launchDialog(errorMessage, DialogType.Error);
      return false;
    }
    return true;
  }

  createGetRequestArray(searchResponse: SearchResponse): any {
    return searchResponse.results.map(alert =>
      new GetRequest(alert.source.guid, alert.source[this.globalConfig['source.type.field']], alert.index));
  }

  getAllAlertsForSlectedGroup(group: TreeGroupData): Observable<SearchResponse> {
    let dashRowKey = Object.keys(group.groupQueryMap);
    let searchRequest = new SearchRequest();
    searchRequest.fields = ['guid', this.globalConfig['source.type.field']];
    searchRequest.from = 0;
    searchRequest.indices = INDEXES;
    searchRequest.query = this.createQuery(group);
    searchRequest.size =  MAX_ALERTS_IN_META_ALERTS;
    searchRequest.facetFields =  [];
    return this.searchService.search(searchRequest);
  }

  doCreateMetaAlert(group: TreeGroupData, index: number) {
    this.getAllAlertsForSlectedGroup(group).subscribe((searchResponse: SearchResponse) => {
      if (this.canCreateMetaAlert(searchResponse.total)) {
        let metaAlert = new MetaAlertCreateRequest();
        metaAlert.alerts = this.createGetRequestArray(searchResponse);
        metaAlert.groups = this.getGroupRequest().groups.map(grp => grp.field);

        this.metaAlertService.create(metaAlert).subscribe(() => {
          setTimeout(() => this.onRefreshData.emit(true), 1000);
          console.log('Meta alert created successfully');
        });
      }
    });
  }

  hasScore(alertSource) {
    if(alertSource[this.threatScoreFieldName()]) {
      return true;
    }
    else {
      return false;
    }
  }

  getScore(alertSource) {
    return alertSource[this.threatScoreFieldName()];
  }

  threatScoreFieldName() {
    return this.globalConfig['threat.triage.score.field'];
  }

  getGroupRequest() {
    return this.queryBuilder.groupRequest(this.threatScoreFieldName());
    }

  createMetaAlert($event, group: TreeGroupData, index: number) {
    if (this.canCreateMetaAlert(group.total)) {
      let confirmationMsg = 'Do you wish to create a meta alert with ' +
                            (group.total === 1 ? ' alert' : group.total + ' selected alerts') + '?';
      const confirmedSubscription = this.dialogService.launchDialog(confirmationMsg).subscribe(action => {
        if (action === ConfirmationType.Confirmed) {
          this.doCreateMetaAlert(group, index);
        }
        confirmedSubscription.unsubscribe();
      });
    }

    $event.stopPropagation();
    return false;
  }

  updateAlert(patchRequest: PatchRequest) {
    this.searchService.getAlert(patchRequest.sensorType, patchRequest.guid).subscribe(alertSource => {

      Object.keys(this.treeGroupSubscriptionMap).forEach(key => {
        let group = this.treeGroupSubscriptionMap[key].group;
        if (group.response && group.response.results && group.response.results.length > 0) {
          group.response.results.filter(alert => alert.source.guid === patchRequest.guid)
          .map(alert => alert.source = alertSource);
        }
      });
    });
  }
}


text:
from nltk.tag import RegexpTagger, BigramTagger, UnigramTagger
from nltk.corpus import brown
import nltk
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters

import cPickle as pickle

from time import time

brown_train = brown.tagged_sents()

try:
    unigram_time = time()
    unigram_tagger = pickle.load(open('unigram.object', 'r'))
    unigram_time = time() - unigram_time
    print('Loaded pickled unigram tagger: %.4f s' % unigram_time)
except:
    unigram_time = time()
    unigram_tagger = UnigramTagger(brown_train)
    pickle.dump(unigram_tagger, open('unigram.object', 'w'))
    unigram_time = time() - unigram_time
    print('Retrained and pickled unigram tagger: %.4f s' % unigram_time)

try:
    bigram_time = time()
    bigram_tagger = pickle.load(open('bigram.object', 'r'))
    bigram_time = time() - bigram_time
    print('Loaded pickled bigram tagger: %.4f s' % bigram_time)
except:
    bigram_time = time()
    bigram_tagger = BigramTagger(brown_train, backoff=unigram_tagger)
    pickle.dump(bigram_tagger, open('bigram.object', 'w'))
    bigram_time = time() - bigram_time
    print('Retrained and pickled bigram tagger: %.4f s' % bigram_time)

def summarize(body, pmid):
    if not body:
        return('No summary avialable for PMID %d' % pmid)

    punkt_param = PunktParameters()
    punkt_param.abbrev_types = set(['et al', 'i.e', 'e.g', 'ref', 'c.f',
                                    'fig', 'Fig', 'Eq', 'eq', 'eqn', 'Eqn'])
    sentence_splitter = PunktSentenceTokenizer(punkt_param)
    sentences = sentence_splitter.tokenize(body)

    tagged = []
    for sentence in sentences:
        tagged.append(bigram_tagger.tag(sentence.split()))

    summary = []
    for sentence in tagged:
        for (word, tag) in sentence:
            if tag == 'PPSS' and word.lower() == 'we':
                summary.append(' '.join(nltk.tag.untag(sentence)))

    return summary


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Caeoma cassiopae P.E. Crane

### Remarks
null


text:
class Admin::Fulfillment::OrdersController < Admin::Fulfillment::BaseController
  helper_method :sort_column, :sort_direction
  # GET /admin/fulfillment/orders
  def index
    @orders = Order.fulfillment_grid(params).order(sort_column + " " + sort_direction).
                                            paginate(:page => pagination_page, :per_page => pagination_rows)

  end

  # GET /admin/fulfillment/orders/1
  def show
    @order = Order.includes([:user, :shipments, {:order_items => [:shipment, :variant]}]).find(params[:id])
    add_to_recent_user(@order.user)
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @order }
    end
  end

  # GET /admin/fulfillment/orders/1/edit
  def edit
    @order = Order.includes([:user, :shipments, {:order_items => [:shipment, :variant]}]).find(params[:id])
    add_to_recent_user(@order.user)
  end

  def create_shipment
    @order = Order.find_by_id(params[:id])
    if @order
      Shipment.create_shipments_with_items(@order)
      @order.reload
    end
  end

  # PUT /admin/fulfillment/orders/1
  def update
    @order    = Order.find_by_id(params[:id])
    @invoice  = @order.invoices.find(params[:invoice_id])

    @payment = @order.capture_invoice(@invoice)

##  several things happen on this request
# => Payment is captured
# => Invoice is updated to log leger transactions
# => Shipment is marked as ready to send and associated to the order_items
# => If everything works send the user to the shipment page

## TODO
# => Allow partial payments
# => mark only order_items that will be shipped

    if @payment && @payment.success?
      render partial: 'success_message'
    else
      render partial: 'failure_message'
    end
  end

  # DELETE /admin/fulfillment/shipments/1
  # DELETE /admin/fulfillment/shipments/1.xml
  def destroy

    @order    = Order.find(params[:id])
    @invoice  = @order.invoices.find(params[:invoice_id])

    @order.cancel_unshipped_order(@invoice)
    respond_to do |format|
      format.html { render :partial => 'invoice_details', :locals => {:invoice => @invoice} }
      format.json { render :json => @order.to_json }
    end
  end

  protected

  def sort_column
    Order.column_names.include?(params[:sort]) ? params[:sort] : "number"
  end

  def pagination_rows
    params[:rows] ||= 25
    params[:rows].to_i
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end


text:
/*************************************************************************
Name:       Isabell Jansson, Jonathan Bosson, Ronja Grosz
File name:  CellList.h

This class contains the data structure for a cell list to make accessing
neighbouring particles faster.
*************************************************************************/

#include <iostream>
#include <vector>

#ifdef __linux__
#include "../glm/glm/glm.hpp"
#include "../glm/glm/gtc/type_ptr.hpp"
#include "../glm/glm/ext.hpp"
#elif __APPLE__
#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/ext.hpp"
#endif

#include "Particle.h"

using namespace std;
using namespace glm;

// g is the coordinate of the loweLeft corner in the scene.
// b is the coordinate of the "highestPoint" in the scene.
// Every point in the scene has to be inside the cube.
//                  y
//                  ^
//                  |
//                  e-------f
//                 /|      /|
//                / |     / |
//               a--|----b  |
//     (0, 0, 0) |  g----|--h ---> x
//               | /     | /
//               c-------d
//               /
//              z

class CellList
{
    public:
        CellList(dvec3 lowestPoint, dvec3 highestPoint, double H);
        ~CellList();

        void addParticle(Particle* particle, int pIndex);
        void moveParticle(Particle* particle, int pIndex);
        vector< int >* findNeighbours(vector< Particle* > *water, int pIndex);

    protected:
        vector< vector< vector< vector< int > > > > cellList;
        dvec3 lowerLeft;
        const double radius;

        ivec3 getCellPos(dvec3 pos);
        bool validCellPos(ivec3 pos);
};


text:
import unittest

from trac.core import TracError
from trac.test import EnvironmentStub, Mock, MockPerm
from trac.versioncontrol.web_ui.changeset import ChangesetModule

class ChangesetModuleTestCase(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub()
        self.cm = ChangesetModule(self.env)

    def test_default_repository_not_configured(self):
        """Test for regression of http://trac.edgewall.org/ticket/11599."""
        req = Mock(perm=MockPerm(), args={'new_path': '/'},
                   get_header=lambda self: None)
        self.assertRaises(TracError, self.cm.process_request, req)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(ChangesetModuleTestCase))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')


text:
package auth

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"testing"
)

type values map[string]string

var (
	mux    *http.ServeMux
	server *httptest.Server
)

func setUp() {
	mux = http.NewServeMux()
	server = httptest.NewServer(mux)
}

func tearDown() {
	server.Close()
}

func testMethod(t *testing.T, r *http.Request, want string) {
	if got := r.Method; got != want {
		t.Errorf("Request method: %v, want %v", got, want)
	}
}

func testContentType(t *testing.T, r *http.Request, want string) {
	contentType, ok := r.Header["Content-Type"]
	if !ok || len(contentType) < 1 {
		t.Errorf("Content-Type header not present, want: %v", want)
		return
	}
	if got := r.Header["Content-Type"][0]; got != want {
		t.Errorf("Content-type: %v, want %v", got, want)
	}
}

func testFormValues(t *testing.T, r *http.Request, values values) {
	want := url.Values{}
	for k, v := range values {
		want.Add(k, v)
	}

	r.ParseForm()
	if got := r.Form; !reflect.DeepEqual(got, want) {
		t.Errorf("Request parameters: %v, want %v", got, want)
	}
}