// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * OSS compatible sequencer driver
 *
 * MIDI device handlers
 *
 * Copyright (C) 1998,99 Takashi Iwai <tiwai@suse.de>
 */

#include <sound/asoundef.h>
#include "seq_oss_midi.h"
#include "seq_oss_readq.h"
#include "seq_oss_timer.h"
#include "seq_oss_event.h"
#include <sound/seq_midi_event.h>
#include "../seq_lock.h"
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/nospec.h>

/*
 * constants
 */
#define SNDRV_SEQ_OSS_MAX_MIDI_NAME	30

/*
 * definition of midi device record
 */
struct seq_oss_midi {
	int seq_device;		/* device number */
	int client;		/* sequencer client number */
	int port;		/* sequencer port number */
	unsigned int flags;	/* port capability */
	int opened;		/* flag for opening */
	unsigned char name[SNDRV_SEQ_OSS_MAX_MIDI_NAME];
	struct snd_midi_event *coder;	/* MIDI event coder */
	struct seq_oss_devinfo *devinfo;	/* assigned OSSseq device */
	snd_use_lock_t use_lock;
};

/*
 * midi device table
 */
static int max_midi_devs;
static struct seq_oss_midi *midi_devs[SNDRV_SEQ_OSS_MAX_MIDI_DEVS];

static DEFINE_SPINLOCK(register_lock);

/*
 * prototypes
 */
static struct seq_oss_midi *get_mdev(int dev);
static struct seq_oss_midi *get_mididev(struct seq_oss_devinfo *dp, int dev);
static int send_synth_event(struct seq_oss_devinfo *dp, struct snd_seq_event *ev, int dev);
static int send_midi_event(struct seq_oss_devinfo *dp, struct snd_seq_event *ev, struct seq_oss_midi *mdev);

/*
 * look up the existing ports
 * this looks a very exhausting job.
 */
int
snd_seq_oss_midi_lookup_ports(int client)
{
	struct snd_seq_client_info *clinfo;
	struct snd_seq_port_info *pinfo;

	clinfo = kzalloc(sizeof(*clinfo), GFP_KERNEL);
	pinfo = kzalloc(sizeof(*pinfo), GFP_KERNEL);
	if (! clinfo || ! pinfo) {
		kfree(clinfo);
		kfree(pinfo);
		return -ENOMEM;
	}
	clinfo->client = -1;
	while (snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_QUERY_NEXT_CLIENT, clinfo) == 0) {
		if (clinfo->client == client)
			continue; /* ignore myself */
		pinfo->addr.client = clinfo->client;
		pinfo->addr.port = -1;
		while (snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_QUERY_NEXT_PORT, pinfo) == 0)
			snd_seq_oss_midi_check_new_port(pinfo);
	}
	kfree(clinfo);
	kfree(pinfo);
	return 0;
}

/*
 */
static struct seq_oss_midi *
get_mdev(int dev)
{
	struct seq_oss_midi *mdev;
	unsigned long flags;

	spin_lock_irqsave(&register_lock, flags);
	mdev = midi_devs[dev];
	if (mdev)
		snd_use_lock_use(&mdev->use_lock);
	spin_unlock_irqrestore(&register_lock, flags);
	return mdev;
}

/*
 * look for the identical slot
 */
static struct seq_oss_midi *
find_slot(int client, int port)
{
	int i;
	struct seq_oss_midi *mdev;
	unsigned long flags;

	spin_lock_irqsave(&register_lock, flags);
	for (i = 0; i < max_midi_devs; i++) {
		mdev = midi_devs[i];
		if (mdev && mdev->client == client && mdev->port == port) {
			/* found! */
			snd_use_lock_use(&mdev->use_lock);
			spin_unlock_irqrestore(&register_lock, flags);
			return mdev;
		}
	}
	spin_unlock_irqrestore(&register_lock, flags);
	return NULL;
}

#define PERM_WRITE (SNDRV_SEQ_PORT_CAP_WRITE|SNDRV_SEQ_PORT_CAP_SUBS_WRITE)
#define PERM_READ (SNDRV_SEQ_PORT_CAP_READ|SNDRV_SEQ_PORT_CAP_SUBS_READ)
/*
 * register a new port if it doesn't exist yet
 */
int
snd_seq_oss_midi_check_new_port(struct snd_seq_port_info *pinfo)
{
	int i;
	struct seq_oss_midi *mdev;
	unsigned long flags;

	/* the port must include generic midi */
	if (! (pinfo->type & SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC))
		return 0;
	/* either read or write subscribable */
	if ((pinfo->capability & PERM_WRITE) != PERM_WRITE &&
	    (pinfo->capability & PERM_READ) != PERM_READ)
		return 0;

	/*
	 * look for the identical slot
	 */
	if ((mdev = find_slot(pinfo->addr.client, pinfo->addr.port)) != NULL) {
		/* already exists */
		snd_use_lock_free(&mdev->use_lock);
		return 0;
	}

	/*
	 * allocate midi info record
	 */
	mdev = kzalloc(sizeof(*mdev), GFP_KERNEL);
	if (!mdev)
		return -ENOMEM;

	/* copy the port information */
	mdev->client = pinfo->addr.client;
	mdev->port = pinfo->addr.port;
	mdev->flags = pinfo->capability;
	mdev->opened = 0;
	snd_use_lock_init(&mdev->use_lock);

	/* copy and truncate the name of synth device */
	strlcpy(mdev->name, pinfo->name, sizeof(mdev->name));

	/* create MIDI coder */
	if (snd_midi_event_new(MAX_MIDI_EVENT_BUF, &mdev->coder) < 0) {
		pr_err("ALSA: seq_oss: can't malloc midi coder\n");
		kfree(mdev);
		return -ENOMEM;
	}
	/* OSS sequencer adds running status to all sequences */
	snd_midi_event_no_status(mdev->coder, 1);

	/*
	 * look for en empty slot
	 */
	spin_lock_irqsave(&register_lock, flags);
	for (i = 0; i < max_midi_devs; i++) {
		if (midi_devs[i] == NULL)
			break;
	}
	if (i >= max_midi_devs) {
		if (max_midi_devs >= SNDRV_SEQ_OSS_MAX_MIDI_DEVS) {
			spin_unlock_irqrestore(&register_lock, flags);
			snd_midi_event_free(mdev->coder);
			kfree(mdev);
			return -ENOMEM;
		}
		max_midi_devs++;
	}
	mdev->seq_device = i;
	midi_devs[mdev->seq_device] = mdev;
	spin_unlock_irqrestore(&register_lock, flags);

	return 0;
}

/*
 * release the midi device if it was registered
 */
int
snd_seq_oss_midi_check_exit_port(int client, int port)
{
	struct seq_oss_midi *mdev;
	unsigned long flags;
	int index;

	if ((mdev = find_slot(client, port)) != NULL) {
		spin_lock_irqsave(&register_lock, flags);
		midi_devs[mdev->seq_device] = NULL;
		spin_unlock_irqrestore(&register_lock, flags);
		snd_use_lock_free(&mdev->use_lock);
		snd_use_lock_sync(&mdev->use_lock);
		snd_midi_event_free(mdev->coder);
		kfree(mdev);
	}
	spin_lock_irqsave(&register_lock, flags);
	for (index = max_midi_devs - 1; index >= 0; index--) {
		if (midi_devs[index])
			break;
	}
	max_midi_devs = index + 1;
	spin_unlock_irqrestore(&register_lock, flags);
	return 0;
}

/*
 * release the midi device if it was registered
 */
void
snd_seq_oss_midi_clear_all(void)
{
	int i;
	struct seq_oss_midi *mdev;
	unsigned long flags;

	spin_lock_irqsave(&register_lock, flags);
	for (i = 0; i < max_midi_devs; i++) {
		if ((mdev = midi_devs[i]) != NULL) {
			snd_midi_event_free(mdev->coder);
			kfree(mdev);
			midi_devs[i] = NULL;
		}
	}
	max_midi_devs = 0;
	spin_unlock_irqrestore(&register_lock, flags);
}

/*
 * set up midi tables
 */
void
snd_seq_oss_midi_setup(struct seq_oss_devinfo *dp)
{
	dp->max_mididev = max_midi_devs;
}

/*
 * clean up midi tables
 */
void
snd_seq_oss_midi_cleanup(struct seq_oss_devinfo *dp)
{
	int i;
	for (i = 0; i < dp->max_mididev; i++)
		snd_seq_oss_midi_close(dp, i);
	dp->max_mididev = 0;
}

/*
 * open all midi devices.  ignore errors.
 */
void
snd_seq_oss_midi_open_all(struct seq_oss_devinfo *dp, int file_mode)
{
	int i;
	for (i = 0; i < dp->max_mididev; i++)
		snd_seq_oss_midi_open(dp, i, file_mode);
}

/*
 * get the midi device information
 */
static struct seq_oss_midi *
get_mididev(struct seq_oss_devinfo *dp, int dev)
{
	if (dev < 0 || dev >= dp->max_mididev)
		return NULL;
	dev = array_index_nospec(dev, dp->max_mididev);
	return get_mdev(dev);
}

/*
 * open the midi device if not opened yet
 */
int
snd_seq_oss_midi_open(struct seq_oss_devinfo *dp, int dev, int fmode)
{
	int perm;
	struct seq_oss_midi *mdev;
	struct snd_seq_port_subscribe subs;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return -ENODEV;

	/* already used? */
	if (mdev->opened && mdev->devinfo != dp) {
		snd_use_lock_free(&mdev->use_lock);
		return -EBUSY;
	}

	perm = 0;
	if (is_write_mode(fmode))
		perm |= PERM_WRITE;
	if (is_read_mode(fmode))
		perm |= PERM_READ;
	perm &= mdev->flags;
	if (perm == 0) {
		snd_use_lock_free(&mdev->use_lock);
		return -ENXIO;
	}

	/* already opened? */
	if ((mdev->opened & perm) == perm) {
		snd_use_lock_free(&mdev->use_lock);
		return 0;
	}

	perm &= ~mdev->opened;

	memset(&subs, 0, sizeof(subs));

	if (perm & PERM_WRITE) {
		subs.sender = dp->addr;
		subs.dest.client = mdev->client;
		subs.dest.port = mdev->port;
		if (snd_seq_kernel_client_ctl(dp->cseq, SNDRV_SEQ_IOCTL_SUBSCRIBE_PORT, &subs) >= 0)
			mdev->opened |= PERM_WRITE;
	}
	if (perm & PERM_READ) {
		subs.sender.client = mdev->client;
		subs.sender.port = mdev->port;
		subs.dest = dp->addr;
		subs.flags = SNDRV_SEQ_PORT_SUBS_TIMESTAMP;
		subs.queue = dp->queue;		/* queue for timestamps */
		if (snd_seq_kernel_client_ctl(dp->cseq, SNDRV_SEQ_IOCTL_SUBSCRIBE_PORT, &subs) >= 0)
			mdev->opened |= PERM_READ;
	}

	if (! mdev->opened) {
		snd_use_lock_free(&mdev->use_lock);
		return -ENXIO;
	}

	mdev->devinfo = dp;
	snd_use_lock_free(&mdev->use_lock);
	return 0;
}

/*
 * close the midi device if already opened
 */
int
snd_seq_oss_midi_close(struct seq_oss_devinfo *dp, int dev)
{
	struct seq_oss_midi *mdev;
	struct snd_seq_port_subscribe subs;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return -ENODEV;
	if (! mdev->opened || mdev->devinfo != dp) {
		snd_use_lock_free(&mdev->use_lock);
		return 0;
	}

	memset(&subs, 0, sizeof(subs));
	if (mdev->opened & PERM_WRITE) {
		subs.sender = dp->addr;
		subs.dest.client = mdev->client;
		subs.dest.port = mdev->port;
		snd_seq_kernel_client_ctl(dp->cseq, SNDRV_SEQ_IOCTL_UNSUBSCRIBE_PORT, &subs);
	}
	if (mdev->opened & PERM_READ) {
		subs.sender.client = mdev->client;
		subs.sender.port = mdev->port;
		subs.dest = dp->addr;
		snd_seq_kernel_client_ctl(dp->cseq, SNDRV_SEQ_IOCTL_UNSUBSCRIBE_PORT, &subs);
	}

	mdev->opened = 0;
	mdev->devinfo = NULL;

	snd_use_lock_free(&mdev->use_lock);
	return 0;
}

/*
 * change seq capability flags to file mode flags
 */
int
snd_seq_oss_midi_filemode(struct seq_oss_devinfo *dp, int dev)
{
	struct seq_oss_midi *mdev;
	int mode;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return 0;

	mode = 0;
	if (mdev->opened & PERM_WRITE)
		mode |= SNDRV_SEQ_OSS_FILE_WRITE;
	if (mdev->opened & PERM_READ)
		mode |= SNDRV_SEQ_OSS_FILE_READ;

	snd_use_lock_free(&mdev->use_lock);
	return mode;
}

/*
 * reset the midi device and close it:
 * so far, only close the device.
 */
void
snd_seq_oss_midi_reset(struct seq_oss_devinfo *dp, int dev)
{
	struct seq_oss_midi *mdev;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return;
	if (! mdev->opened) {
		snd_use_lock_free(&mdev->use_lock);
		return;
	}

	if (mdev->opened & PERM_WRITE) {
		struct snd_seq_event ev;
		int c;

		memset(&ev, 0, sizeof(ev));
		ev.dest.client = mdev->client;
		ev.dest.port = mdev->port;
		ev.queue = dp->queue;
		ev.source.port = dp->port;
		if (dp->seq_mode == SNDRV_SEQ_OSS_MODE_SYNTH) {
			ev.type = SNDRV_SEQ_EVENT_SENSING;
			snd_seq_oss_dispatch(dp, &ev, 0, 0);
		}
		for (c = 0; c < 16; c++) {
			ev.type = SNDRV_SEQ_EVENT_CONTROLLER;
			ev.data.control.channel = c;
			ev.data.control.param = MIDI_CTL_ALL_NOTES_OFF;
			snd_seq_oss_dispatch(dp, &ev, 0, 0);
			if (dp->seq_mode == SNDRV_SEQ_OSS_MODE_MUSIC) {
				ev.data.control.param =
					MIDI_CTL_RESET_CONTROLLERS;
				snd_seq_oss_dispatch(dp, &ev, 0, 0);
				ev.type = SNDRV_SEQ_EVENT_PITCHBEND;
				ev.data.control.value = 0;
				snd_seq_oss_dispatch(dp, &ev, 0, 0);
			}
		}
	}
	// snd_seq_oss_midi_close(dp, dev);
	snd_use_lock_free(&mdev->use_lock);
}

/*
 * get client/port of the specified MIDI device
 */
void
snd_seq_oss_midi_get_addr(struct seq_oss_devinfo *dp, int dev, struct snd_seq_addr *addr)
{
	struct seq_oss_midi *mdev;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return;
	addr->client = mdev->client;
	addr->port = mdev->port;
	snd_use_lock_free(&mdev->use_lock);
}

/*
 * input callback - this can be atomic
 */
int
snd_seq_oss_midi_input(struct snd_seq_event *ev, int direct, void *private_data)
{
	struct seq_oss_devinfo *dp = (struct seq_oss_devinfo *)private_data;
	struct seq_oss_midi *mdev;
	int rc;

	if (dp->readq == NULL)
		return 0;
	if ((mdev = find_slot(ev->source.client, ev->source.port)) == NULL)
		return 0;
	if (! (mdev->opened & PERM_READ)) {
		snd_use_lock_free(&mdev->use_lock);
		return 0;
	}

	if (dp->seq_mode == SNDRV_SEQ_OSS_MODE_MUSIC)
		rc = send_synth_event(dp, ev, mdev->seq_device);
	else
		rc = send_midi_event(dp, ev, mdev);

	snd_use_lock_free(&mdev->use_lock);
	return rc;
}

/*
 * convert ALSA sequencer event to OSS synth event
 */
static int
send_synth_event(struct seq_oss_devinfo *dp, struct snd_seq_event *ev, int dev)
{
	union evrec ossev;

	memset(&ossev, 0, sizeof(ossev));

	switch (ev->type) {
	case SNDRV_SEQ_EVENT_NOTEON:
		ossev.v.cmd = MIDI_NOTEON; break;
	case SNDRV_SEQ_EVENT_NOTEOFF:
		ossev.v.cmd = MIDI_NOTEOFF; break;
	case SNDRV_SEQ_EVENT_KEYPRESS:
		ossev.v.cmd = MIDI_KEY_PRESSURE; break;
	case SNDRV_SEQ_EVENT_CONTROLLER:
		ossev.l.cmd = MIDI_CTL_CHANGE; break;
	case SNDRV_SEQ_EVENT_PGMCHANGE:
		ossev.l.cmd = MIDI_PGM_CHANGE; break;
	case SNDRV_SEQ_EVENT_CHANPRESS:
		ossev.l.cmd = MIDI_CHN_PRESSURE; break;
	case SNDRV_SEQ_EVENT_PITCHBEND:
		ossev.l.cmd = MIDI_PITCH_BEND; break;
	default:
		return 0; /* not supported */
	}

	ossev.v.dev = dev;

	switch (ev->type) {
	case SNDRV_SEQ_EVENT_NOTEON:
	case SNDRV_SEQ_EVENT_NOTEOFF:
	case SNDRV_SEQ_EVENT_KEYPRESS:
		ossev.v.code = EV_CHN_VOICE;
		ossev.v.note = ev->data.note.note;
		ossev.v.parm = ev->data.note.velocity;
		ossev.v.chn = ev->data.note.channel;
		break;
	case SNDRV_SEQ_EVENT_CONTROLLER:
	case SNDRV_SEQ_EVENT_PGMCHANGE:
	case SNDRV_SEQ_EVENT_CHANPRESS:
		ossev.l.code = EV_CHN_COMMON;
		ossev.l.p1 = ev->data.control.param;
		ossev.l.val = ev->data.control.value;
		ossev.l.chn = ev->data.control.channel;
		break;
	case SNDRV_SEQ_EVENT_PITCHBEND:
		ossev.l.code = EV_CHN_COMMON;
		ossev.l.val = ev->data.control.value + 8192;
		ossev.l.chn = ev->data.control.channel;
		break;
	}

	snd_seq_oss_readq_put_timestamp(dp->readq, ev->time.tick, dp->seq_mode);
	snd_seq_oss_readq_put_event(dp->readq, &ossev);

	return 0;
}

/*
 * decode event and send MIDI bytes to read queue
 */
static int
send_midi_event(struct seq_oss_devinfo *dp, struct snd_seq_event *ev, struct seq_oss_midi *mdev)
{
	char msg[32];
	int len;

	snd_seq_oss_readq_put_timestamp(dp->readq, ev->time.tick, dp->seq_mode);
	if (!dp->timer->running)
		len = snd_seq_oss_timer_start(dp->timer);
	if (ev->type == SNDRV_SEQ_EVENT_SYSEX) {
		snd_seq_oss_readq_sysex(dp->readq, mdev->seq_device, ev);
	} else {
		len = snd_midi_event_decode(mdev->coder, msg, sizeof(msg), ev);
		if (len > 0)
			snd_seq_oss_readq_puts(dp->readq, mdev->seq_device, msg, len);
	}

	return 0;
}

/*
 * dump midi data
 * return 0 : enqueued
 *        non-zero : invalid - ignored
 */
int
snd_seq_oss_midi_putc(struct seq_oss_devinfo *dp, int dev, unsigned char c, struct snd_seq_event *ev)
{
	struct seq_oss_midi *mdev;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return -ENODEV;
	if (snd_midi_event_encode_byte(mdev->coder, c, ev)) {
		snd_seq_oss_fill_addr(dp, ev, mdev->client, mdev->port);
		snd_use_lock_free(&mdev->use_lock);
		return 0;
	}
	snd_use_lock_free(&mdev->use_lock);
	return -EINVAL;
}

/*
 * create OSS compatible midi_info record
 */
int
snd_seq_oss_midi_make_info(struct seq_oss_devinfo *dp, int dev, struct midi_info *inf)
{
	struct seq_oss_midi *mdev;

	if ((mdev = get_mididev(dp, dev)) == NULL)
		return -ENXIO;
	inf->device = dev;
	inf->dev_type = 0; /* FIXME: ?? */
	inf->capabilities = 0; /* FIXME: ?? */
	strlcpy(inf->name, mdev->name, sizeof(inf->name));
	snd_use_lock_free(&mdev->use_lock);
	return 0;
}

#ifdef CONFIG_SND_PROC_FS
/*
 * proc interface
 */
static char *
capmode_str(int val)
{
	val &= PERM_READ|PERM_WRITE;
	if (val == (PERM_READ|PERM_WRITE))
		return "read/write";
	else if (val == PERM_READ)
		return "read";
	else if (val == PERM_WRITE)
		return "write";
	else
		return "none";
}

void
snd_seq_oss_midi_info_read(struct snd_info_buffer *buf)
{
	int i;
	struct seq_oss_midi *mdev;

	snd_iprintf(buf, "\nNumber of MIDI devices: %d\n", max_midi_devs);
	for (i = 0; i < max_midi_devs; i++) {
		snd_iprintf(buf, "\nmidi %d: ", i);
		mdev = get_mdev(i);
		if (mdev == NULL) {
			snd_iprintf(buf, "*empty*\n");
			continue;
		}
		snd_iprintf(buf, "[%s] ALSA port %d:%d\n", mdev->name,
			    mdev->client, mdev->port);
		snd_iprintf(buf, "  capability %s / opened %s\n",
			    capmode_str(mdev->flags),
			    capmode_str(mdev->opened));
		snd_use_lock_free(&mdev->use_lock);
	}
}
#endif /* CONFIG_SND_PROC_FS */

{'repo_name': 'google/ktsan', 'stars': '551', 'repo_language': 'C', 'file_name': 'irqsrcs_thm_9_0.h', 'mime_type': 'text/x-c', 'hash': 9197593909108476294, 'source_dataset': 'data'}


package io.ebeaninternal.server.core;

import io.ebean.ScriptRunner;
import io.ebean.migration.ddl.DdlRunner;
import io.ebean.migration.runner.ScriptTransform;
import io.ebeaninternal.api.SpiEbeanServer;
import io.ebeaninternal.util.UrlHelper;

import javax.persistence.PersistenceException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

class DScriptRunner implements ScriptRunner {

  private static final String NEWLINE = "\n";

  private final SpiEbeanServer server;
  private final String platformName;

  DScriptRunner(SpiEbeanServer server) {
    this.server = server;
    this.platformName = this.server.getDatabasePlatform().getPlatform().base().name();
  }

  @Override
  public void run(String path) {
    run(path, null);
  }

  @Override
  public void run(String path, Map<String, String> placeholderMap) {
    run(this.getClass().getResource(path), path, placeholderMap);
  }

  @Override
  public void run(URL resource) {
    run(resource, null, null);
  }

  @Override
  public void run(URL resource, Map<String, String> placeholderMap) {
    run(resource, null, placeholderMap);
  }

  private void run(URL resource, String scriptName, Map<String, String> placeholderMap) {
    if (resource == null) {
      throw new IllegalArgumentException("resource is null?");
    }
    if (scriptName == null) {
      scriptName = resource.getFile();
    }

    String content = content(resource);
    runScript(content, scriptName, placeholderMap, false);
  }

  private String content(URL resource) {
    if (resource == null) {
      throw new IllegalArgumentException("resource is null?");
    }

    try (InputStream inputStream = UrlHelper.openNoCache(resource)) {
      return readContent(new InputStreamReader(inputStream));

    } catch (IOException e) {
      throw new PersistenceException("Failed to read script content", e);
    }
  }

  @Override
  public void runScript(String name, String content, boolean useAutoCommit) {
    runScript(content, name, null, useAutoCommit);
  }

  /**
   * Execute all the DDL statements in the script.
   */
  private void runScript(String content, String scriptName, Map<String, String> placeholderMap, boolean useAutoCommit) {
    try {
      if (placeholderMap != null) {
        content = ScriptTransform.build(null, placeholderMap).transform(content);
      }

      try (Connection connection = obtainConnection()) {
        DdlRunner runner = new DdlRunner(useAutoCommit, scriptName, platformName);
        runner.runAll(content, connection);
        connection.commit();
        runner.runNonTransactional(connection);
      }

    } catch (SQLException e) {
      throw new PersistenceException("Failed to run script", e);
    }
  }

  private Connection obtainConnection() {
    try {
      return server.getPluginApi().getDataSource().getConnection();
    } catch (SQLException e) {
      throw new PersistenceException("Failed to obtain connection to run script", e);
    }
  }

  private String readContent(Reader reader) throws IOException {

    StringBuilder buf = new StringBuilder();
    try (LineNumberReader lineReader = new LineNumberReader(reader)) {
      String line;
      while ((line = lineReader.readLine()) != null) {
        buf.append(line).append(NEWLINE);
      }
      return buf.toString();
    }
  }

}

{'repo_name': 'ebean-orm/ebean', 'stars': '1076', 'repo_language': 'Java', 'file_name': 'setup_database', 'mime_type': 'text/x-shellscript', 'hash': -1606257817582087894, 'source_dataset': 'data'}


// EnergyPlus, Copyright (c) 1996-2020, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
//     conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
//     conditions and the following disclaimer in the documentation and/or other materials
//     provided with the distribution.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory,
//     the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
//     used to endorse or promote products derived from this software without specific prior
//     written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
//     without changes from the version obtained under this License, or (ii) Licensee makes a
//     reference solely to the software portion of its product, Licensee must refer to the
//     software as "EnergyPlus version X" software, where "X" is the version number Licensee
//     obtained under this License and may not use a different name for the software. Except as
//     specifically required in this Section (4), Licensee shall not use in a company name, a
//     product name, in advertising, publicity, or other promotional activities any name, trade
//     name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
//     similar designation, without the U.S. Department of Energy's prior written consent.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef OutputReportTabular_hh_INCLUDED
#define OutputReportTabular_hh_INCLUDED

// C++ Headers
#include <fstream>
#include <string>

// ObjexxFCL Headers
#include <ObjexxFCL/Array1D.hh>
#include <ObjexxFCL/Array1S.hh>
#include <ObjexxFCL/Array2D.hh>
#include <ObjexxFCL/Array2S.hh>
#include <ObjexxFCL/Array3D.hh>
#include <ObjexxFCL/Optional.hh>

// EnergyPlus Headers
#include <EnergyPlus/DataGlobals.hh>
#include <EnergyPlus/EnergyPlus.hh>
#include <EnergyPlus/OutputProcessor.hh>

namespace EnergyPlus {

    // Forward declarations
    struct CostEstimateManagerData;
    struct EnergyPlusData;
    struct ZoneTempPredictorCorrectorData;

namespace OutputReportTabular {

    // Using/Aliasing

    // Data
    // MODULE PARAMETER DEFINITIONS:

    extern int const MaxHeaderLength;
    extern int const MaxNoteLength;

    extern int const aggTypeSumOrAvg;
    extern int const aggTypeMaximum;
    extern int const aggTypeMinimum;
    extern int const aggTypeValueWhenMaxMin;
    extern int const aggTypeHoursZero;
    extern int const aggTypeHoursNonZero;
    extern int const aggTypeHoursPositive;
    extern int const aggTypeHoursNonPositive;
    extern int const aggTypeHoursNegative;
    extern int const aggTypeHoursNonNegative;
    extern int const aggTypeSumOrAverageHoursShown;
    extern int const aggTypeMaximumDuringHoursShown;
    extern int const aggTypeMinimumDuringHoursShown;

    extern int const tableStyleComma;
    extern int const tableStyleTab;
    extern int const tableStyleFixed;
    extern int const tableStyleHTML;
    extern int const tableStyleXML;

    extern int const unitsStyleNone; // no change to any units
    extern int const unitsStyleJtoKWH;
    extern int const unitsStyleJtoMJ;
    extern int const unitsStyleJtoGJ;
    extern int const unitsStyleInchPound;
    extern int const unitsStyleNotFound;

    extern int const stepTypeZone;
    extern int const stepTypeHVAC;

    extern int const cSensInst;
    extern int const cSensDelay;
    extern int const cSensRA;
    extern int const cLatent;
    extern int const cTotal;
    extern int const cPerc;
    extern int const cArea;
    extern int const cPerArea;

    extern int const rPeople;
    extern int const rLights;
    extern int const rEquip;
    extern int const rRefrig;
    extern int const rWaterUse;
    extern int const rHvacLoss;
    extern int const rPowerGen;
    extern int const rDOAS;
    extern int const rInfil;
    extern int const rZoneVent;
    extern int const rIntZonMix;
    extern int const rRoof;
    extern int const rIntZonCeil;
    extern int const rOtherRoof;
    extern int const rExtWall;
    extern int const rIntZonWall;
    extern int const rGrdWall;
    extern int const rOtherWall;
    extern int const rExtFlr;
    extern int const rIntZonFlr;
    extern int const rGrdFlr;
    extern int const rOtherFlr;
    extern int const rFeneCond;
    extern int const rFeneSolr;
    extern int const rOpqDoor;
    extern int const rGrdTot;

    // BEPS Report Related Variables
    // From Report:Table:Predefined - BEPS
    extern int const numResourceTypes;
    extern int const numSourceTypes;

    // MODULE VARIABLE DECLARATIONS:

    // The Binned table type is different and only references one variable and its structure is very
    // different from the others so it is has its own type.

    // arrays for time binned results

    extern int OutputTableBinnedCount;
    extern int BinResultsTableCount;
    extern int BinResultsIntervalCount;

    extern int const numNamedMonthly;
    // These reports are detailed/named in routine InitializePredefinedMonthlyTitles

    extern int MonthlyInputCount;
    extern int sizeMonthlyInput;
    extern int MonthlyFieldSetInputCount;
    extern int sizeMonthlyFieldSetInput;
    extern int MonthlyTablesCount;
    extern int MonthlyColumnsCount;
    extern Array1D_bool IsMonthGathered; // shown as true for any month used

    extern int TOCEntriesCount;
    extern int TOCEntriesSize;

    extern int UnitConvSize;

    extern bool WriteTabularFiles;

    // Allow up to five output files to be created
    extern int const maxNumStyles;

    // From Report:Table:Style
    extern int unitsStyle; // see list of parameters
    extern int numStyles;
    extern std::ofstream csv_stream;                   // CSV table stream
    extern std::ofstream tab_stream;                   // Tab table stream
    extern std::ofstream fix_stream;                   // Fixed table stream
    extern std::ofstream htm_stream;                   // HTML table stream
    extern std::ofstream xml_stream;                   // XML table stream
    extern Array1D<std::ofstream *> TabularOutputFile; // Table stream array
    extern Array1D_string del;                         // the delimiter to use
    extern Array1D_int TableStyle;                     // see list of parameters

    extern Real64 timeInYear;

    // Flags for predefined tabular reports
    extern bool displayTabularBEPS;
    extern bool displayLEEDSummary;
    extern bool displayTabularCompCosts; // added BTG 5/6/04 for component cost summary
    extern bool displayTabularVeriSum;   // added JG 2006-06-28 for input verification and summary report
    extern bool displayComponentSizing;
    extern bool displaySurfaceShadowing;
    extern bool displayDemandEndUse;
    extern bool displayAdaptiveComfort;
    extern bool displaySourceEnergyEndUseSummary;
    extern bool displayZoneComponentLoadSummary;
    extern bool displayAirLoopComponentLoadSummary;
    extern bool displayFacilityComponentLoadSummary;
    extern bool displayLifeCycleCostReport;
    extern bool displayTariffReport;
    extern bool displayEconomicResultSummary;
    extern bool displayHeatEmissionsSummary;
    extern bool displayEioSummary;
    extern bool displayThermalResilienceSummary;
    extern bool displayCO2ResilienceSummary;
    extern bool displayVisualResilienceSummary;
    extern bool displayThermalResilienceSummaryExplicitly;
    extern bool displayCO2ResilienceSummaryExplicitly;
    extern bool displayVisualResilienceSummaryExplicitly;
    // BEPS Report Related Variables
    // From Report:Table:Predefined - BEPS
    // arrays that hold the meter numbers that are initialized at get input
    extern Array1D_int meterNumTotalsBEPS;
    extern Array1D_int meterNumTotalsSource;
    extern Array1D_bool fuelfactorsused;
    extern Array1D_bool ffUsed;
    extern Array1D<Real64> SourceFactors;
    extern Array1D_bool ffSchedUsed;
    extern Array1D_int ffSchedIndex;
    extern Array2D_int meterNumEndUseBEPS;
    extern Array3D_int meterNumEndUseSubBEPS;
    // arrays that hold the names of the resource and end uses
    extern Array1D_string resourceTypeNames;
    extern Array1D_string sourceTypeNames;
    extern Array1D_string endUseNames;
    // arrays that hold the actual values for the year
    extern Array1D<Real64> gatherTotalsBEPS;
    extern Array1D<Real64> gatherTotalsBySourceBEPS;
    extern Array1D<Real64> gatherTotalsSource;
    extern Array1D<Real64> gatherTotalsBySource;
    extern Array2D<Real64> gatherEndUseBEPS;
    extern Array2D<Real64> gatherEndUseBySourceBEPS;
    extern Array3D<Real64> gatherEndUseSubBEPS;
    // arrays the hold the demand values
    extern Array1D<Real64> gatherDemandTotal;
    extern Array2D<Real64> gatherDemandEndUse;
    extern Array2D<Real64> gatherDemandIndEndUse;
    extern Array3D<Real64> gatherDemandEndUseSub;
    extern Array3D<Real64> gatherDemandIndEndUseSub;
    extern Array1D_int gatherDemandTimeStamp;
    // to keep track of hours for the BEPS report gathering
    extern Real64 gatherElapsedTimeBEPS;
    // for normalization of results
    extern Real64 buildingGrossFloorArea;
    extern Real64 buildingConditionedFloorArea;
    // keep track if schedules are used in fuel factors
    extern bool fuelFactorSchedulesUsed;
    // for electic load components on BEPS report
    extern int meterNumPowerFuelFireGen;
    extern Real64 gatherPowerFuelFireGen;
    extern int meterNumPowerPV;
    extern Real64 gatherPowerPV;
    extern int meterNumPowerWind;
    extern Real64 gatherPowerWind;
    extern Real64 OverallNetEnergyFromStorage;
    extern int meterNumPowerHTGeothermal;
    extern Real64 gatherPowerHTGeothermal;
    extern int meterNumElecProduced;
    extern Real64 gatherElecProduced;
    extern int meterNumElecPurchased;
    extern Real64 gatherElecPurchased;
    extern int meterNumElecSurplusSold;
    extern Real64 gatherElecSurplusSold;
    extern int meterNumElecStorage;
    extern Real64 gatherElecStorage;
    extern int meterNumPowerConversion;
    extern Real64 gatherPowerConversion;
    // for on site thermal source components on BEPS report
    extern int meterNumWaterHeatRecovery;
    extern Real64 gatherWaterHeatRecovery;
    extern int meterNumAirHeatRecoveryCool;
    extern Real64 gatherAirHeatRecoveryCool;
    extern int meterNumAirHeatRecoveryHeat;
    extern Real64 gatherAirHeatRecoveryHeat;
    extern int meterNumHeatHTGeothermal;
    extern Real64 gatherHeatHTGeothermal;
    extern int meterNumHeatSolarWater;
    extern Real64 gatherHeatSolarWater;
    extern int meterNumHeatSolarAir;
    extern Real64 gatherHeatSolarAir;
    // for on site water components on BEPS report
    extern int meterNumRainWater;
    extern Real64 gatherRainWater;
    extern int meterNumCondensate;
    extern Real64 gatherCondensate;
    extern int meterNumGroundwater;
    extern Real64 gatherWellwater;
    extern int meterNumMains;
    extern Real64 gatherMains;
    extern int meterNumWaterEndUseTotal;
    extern Real64 gatherWaterEndUseTotal;
    // for source energy conversion factors on BEPS report
    extern Real64 sourceFactorElectric;
    extern Real64 sourceFactorNaturalGas;
    extern Real64 efficiencyDistrictCooling;
    extern Real64 efficiencyDistrictHeating;
    extern Real64 sourceFactorSteam;
    extern Real64 sourceFactorGasoline;
    extern Real64 sourceFactorDiesel;
    extern Real64 sourceFactorCoal;
    extern Real64 sourceFactorFuelOil1;
    extern Real64 sourceFactorFuelOil2;
    extern Real64 sourceFactorPropane;
    extern Real64 sourceFactorOtherFuel1;
    extern Real64 sourceFactorOtherFuel2;

    extern Array1D_int td;
    //(1)   Current year
    //(2)   Current month
    //(3)   Current day
    //(4)   Time difference with respect to UTC in minutes (0-59)
    //(5)   Hour of the day (0-23)
    //(6)   Minutes (0-59)
    //(7)   Seconds (0-59)
    //(8)   Milliseconds (0-999)

    // Design day name storage
    extern Array1D_string DesignDayName;
    extern int DesignDayCount;

    // arrays related to pulse and load component reporting
    extern Array2D_int radiantPulseTimestep;
    extern Array2D<Real64> radiantPulseReceived;
    extern Array3D<Real64> loadConvectedNormal;
    extern Array3D<Real64> loadConvectedWithPulse;
    extern Array3D<Real64> netSurfRadSeq;
    extern Array2D<Real64> decayCurveCool;
    extern Array2D<Real64> decayCurveHeat;
    extern Array3D<Real64> ITABSFseq; // used for determining the radiant fraction on each surface
    extern Array3D<Real64> TMULTseq;  // used for determining the radiant fraction on each surface

    extern Array3D<Real64> peopleInstantSeq;
    extern Array3D<Real64> peopleLatentSeq;
    extern Array3D<Real64> peopleRadSeq;
    extern Array3D<Real64> peopleDelaySeq;

    extern Array3D<Real64> lightInstantSeq;
    extern Array3D<Real64> lightRetAirSeq;
    extern Array3D<Real64> lightLWRadSeq; // long wave thermal radiation
    extern Array3D<Real64> lightSWRadSeq; // short wave visible radiation
    extern Array3D<Real64> lightDelaySeq;

    extern Array3D<Real64> equipInstantSeq;
    extern Array3D<Real64> equipLatentSeq;
    extern Array3D<Real64> equipRadSeq;
    extern Array3D<Real64> equipDelaySeq;

    extern Array3D<Real64> refrigInstantSeq;
    extern Array3D<Real64> refrigRetAirSeq;
    extern Array3D<Real64> refrigLatentSeq;

    extern Array3D<Real64> waterUseInstantSeq;
    extern Array3D<Real64> waterUseLatentSeq;

    extern Array3D<Real64> hvacLossInstantSeq;
    extern Array3D<Real64> hvacLossRadSeq;
    extern Array3D<Real64> hvacLossDelaySeq;

    extern Array3D<Real64> powerGenInstantSeq;
    extern Array3D<Real64> powerGenRadSeq;
    extern Array3D<Real64> powerGenDelaySeq;

    extern Array3D<Real64> infilInstantSeq;
    extern Array3D<Real64> infilLatentSeq;

    extern Array3D<Real64> zoneVentInstantSeq;
    extern Array3D<Real64> zoneVentLatentSeq;

    extern Array3D<Real64> interZoneMixInstantSeq;
    extern Array3D<Real64> interZoneMixLatentSeq;

    extern Array3D<Real64> feneCondInstantSeq;
    // REAL(r64), DIMENSION(:,:,:),ALLOCATABLE,PUBLIC  :: feneSolarInstantSeq
    extern Array3D<Real64> feneSolarRadSeq;
    extern Array3D<Real64> feneSolarDelaySeq;

    extern Array3D<Real64> surfDelaySeq;

    extern int maxUniqueKeyCount;

    // for the XML report must keep track fo the active sub-table name and report set by other routines
    extern std::string activeSubTableName;
    extern std::string activeReportNameNoSpace;
    extern std::string activeReportName;
    extern std::string activeForName;
    extern std::string prevReportName;

    // LineTypes for reading the stat file
    enum class StatLineType {
        Initialized, // used as a dummy placeholder
        StatisticsLine,
        LocationLine,
        LatLongLine,
        ElevationLine,
        StdPressureLine,
        DataSourceLine,
        WMOStationLine,
        DesignConditionsLine,
        heatingConditionsLine,
        coolingConditionsLine,
        stdHDDLine,
        stdCDDLine,
        maxDryBulbLine,
        minDryBulbLine,
        maxDewPointLine,
        minDewPointLine,
        wthHDDLine,
        wthCDDLine,
        KoppenLine,
        KoppenDes1Line,
        KoppenDes2Line,
        AshStdLine,
        AshStdDes1Line,
        AshStdDes2Line,
        AshStdDes3Line,
    };

    // Types

    struct OutputTableBinnedType
    {
        // Members
        std::string keyValue;   // the key value (usually an asterisk to indicate all variables
        std::string varOrMeter; // the name of the variable or meter
        Real64 intervalStart;   // The lowest value for the intervals being binned into.
        Real64 intervalSize;    // The size of the bins starting with Interval start.
        int intervalCount;      // The number of bins used. The number of hours below the start of
        // the lowest bin and above the value of the last bin are also shown.
        int resIndex; // result index - pointer to BinResults array
        int numTables;
        int typeOfVar;                     // 0=not found, 1=integer, 2=real, 3=meter
        OutputProcessor::StoreType avgSum; // Variable  is Averaged=1 or Summed=2
        OutputProcessor::TimeStepType stepType;                      // Variable time step is Zone=1 or HVAC=2
        OutputProcessor::Unit units;       // the units enumeration
        std::string ScheduleName;          // the name of the schedule
        int scheduleIndex;                 // index to the schedule specified - if no schedule use zero

        // Default Constructor
        OutputTableBinnedType()
            : intervalStart(0.0), intervalSize(0.0), intervalCount(0), resIndex(0), numTables(0), typeOfVar(0),
              avgSum(OutputProcessor::StoreType::Averaged), stepType(OutputProcessor::TimeStepType::TimeStepZone), scheduleIndex(0)
        {
        }
    };

    struct BinResultsType
    {
        // Members
        Array1D<Real64> mnth; // monthly bins
        Array1D<Real64> hrly; // hourly bins

        // Default Constructor
        BinResultsType() : mnth(12, 0.0), hrly(24, 0.0)
        {
        }
    };

    struct BinObjVarIDType
    {
        // Members
        std::string namesOfObj; // name of the object
        int varMeterNum;        // variable or meter number

        // Default Constructor
        BinObjVarIDType() : varMeterNum(0)
        {
        }
    };

    struct BinStatisticsType
    {
        // Members
        Real64 sum;     // sum of the variable
        Real64 sum2;    // sum of the variable squared
        int n;          // number of items in sum
        Real64 minimum; // minimum value
        Real64 maximum; // maximum value

        // Default Constructor
        BinStatisticsType() : sum(0.0), sum2(0.0), n(0), minimum(0.0), maximum(0.0)
        {
        }
    };

    struct NamedMonthlyType
    {
        // Members
        std::string title; // report title
        bool show;         // if report should be shown

        // Default Constructor
        NamedMonthlyType() : show(false)
        {
        }
    };

    struct MonthlyInputType
    {
        // Members
        std::string name;  // identifier
        int numFieldSet;   // number of monthly field sets
        int firstFieldSet; // pointer to the first field set
        int numTables;     // number of tables
        int firstTable;    // pointer to the first table
        int showDigits;    // the number of digits to be shown

        // Default Constructor
        MonthlyInputType() : numFieldSet(0), firstFieldSet(0), numTables(0), firstTable(0), showDigits(0)
        {
        }
    };

    struct MonthlyFieldSetInputType
    {
        // Members
        std::string variMeter;                // the name of the variable or meter
        std::string colHead;                  // the column header to use instead of the variable name (only for predefined)
        int aggregate;                        // the type of aggregation for the variable (see aggType parameters)
        OutputProcessor::Unit varUnits;       // Units enumeration
        std::string variMeterUpper;           // the name of the variable or meter uppercased
        int typeOfVar;                        // 0=not found, 1=integer, 2=real, 3=meter
        int keyCount;                         // noel
        OutputProcessor::StoreType varAvgSum; // Variable  is Averaged=1 or Summed=2
        OutputProcessor::TimeStepType varStepType;                      // Variable time step is Zone=1 or HVAC=2
        Array1D_string NamesOfKeys;           // keyNames !noel
        Array1D_int IndexesForKeyVar;         // keyVarIndexes !noel

        // Default Constructor
        MonthlyFieldSetInputType()
            : aggregate(0), varUnits(OutputProcessor::Unit::None), typeOfVar(0), keyCount(0), varAvgSum(OutputProcessor::StoreType::Averaged),
              varStepType(OutputProcessor::TimeStepType::TimeStepZone)
        {
        }
    };

    struct MonthlyTablesType
    {
        // Members
        std::string keyValue; // the key value - the object names that result in the variable
        int firstColumn;      // pointer to the monthly column array for the first item
        int numColumns;       // number of columns for the table

        // Default Constructor
        MonthlyTablesType() : firstColumn(0), numColumns(0)
        {
        }
    };

    struct MonthlyColumnsType
    {
        // Members
        std::string varName;               // name of variable
        std::string colHead;               // column header (not used for user defined monthly)
        int varNum;                        // variable or meter number
        int typeOfVar;                     // 0=not found, 1=integer, 2=real, 3=meter
        OutputProcessor::StoreType avgSum; // Variable  is Averaged=1 or Summed=2
        OutputProcessor::TimeStepType stepType;                      // Variable time step is Zone=1 or HVAC=2
        OutputProcessor::Unit units;       // the units string, may be blank
        int aggType;                       // index to the type of aggregation (see list of parameters)
        Array1D<Real64> reslt;             // monthly results
        Array1D<Real64> duration;          // the time during which results are summed for use in averages
        Array1D_int timeStamp;             // encoded timestamp of max or min
        Real64 aggForStep;                 // holds the aggregation for the HVAC time steps when smaller than
        // the zone timestep

        // Default Constructor
        MonthlyColumnsType()
            : varNum(0), typeOfVar(0), avgSum(OutputProcessor::StoreType::Averaged), stepType(OutputProcessor::TimeStepType::TimeStepZone), units(OutputProcessor::Unit::None), aggType(0),
              reslt(12, 0.0), duration(12, 0.0), timeStamp(12, 0), aggForStep(0.0)
        {
        }
    };

    struct TOCEntriesType
    {
        // Members
        std::string reportName;  // the name of the individual report
        std::string sectionName; // the name of the section containing individual reports
        bool isWritten;          // flag if the entry has been written to TOC

        // Default Constructor
        TOCEntriesType() : isWritten(false)
        {
        }
    };

    struct UnitConvType
    {
        // Members
        std::string siName; // the name abbreviation or symbol of the SI units
        std::string ipName; // the name abbreviation or symbol of the IP units
        Real64 mult;        // the multiplier used to convert from SI to IP in IP = (SI * mult) + offset
        Real64 offset;      // the offset used to convert from SI to IP in IP = (SI * mult) + offset
        std::string hint;   // the string used when multiple SI units match
        bool several;       // several different options for the SI unit to be converted into IP
        bool is_default;    // if part of a set of "several" this should be used as default

        // Default Constructor
        UnitConvType() : mult(1.0), offset(0.0), several(false), is_default(false)
        {
        }
    };

    struct CompLoadTablesType
    {
        // members
        int desDayNum;             // design day number
        int timeStepMax;           // times step of the day that the maximum occurs
        Array2D<Real64> cells;     // main component table results (column, row)
        Array2D_bool cellUsed;     // flag if the cell is used for the table of results (column, row)
        std::string peakDateHrMin; // string containing peak timestamp
        Real64 outsideDryBulb;     // outside dry bulb temperature at peak
        Real64 outsideWetBulb;     // outside wet bulb temperature at peak
        Real64 outsideHumRatio;    // outside humidity ratio at peak
        Real64 zoneDryBulb;        // zone dry bulb temperature at peak
        Real64 zoneRelHum;         // zone relative humidity at peak
        Real64 zoneHumRatio;       // zone humidity ratio at peak

        Real64 supAirTemp;     // supply air temperature
        Real64 mixAirTemp;     // mixed air temperature
        Real64 mainFanAirFlow; // main fan air flow
        Real64 outsideAirFlow; // outside air flow
        Real64 designPeakLoad; // design peak load
        Real64 diffDesignPeak; // difference between Design and Peak Load

        Real64 peakDesSensLoad;    // peak design sensible load
        Real64 estInstDelSensLoad; // estimated instant plus delayed sensible load
        Real64 diffPeakEst;        // difference between the peak design sensible load and the estimated instant plus delayed sensible load
        Array1D_int zoneIndices;   // the zone numbers covered by the report

        Real64 outsideAirRatio;   // outside Air
        Real64 floorArea;         // floor area
        Real64 airflowPerFlrArea; // airflow per floor area
        Real64 airflowPerTotCap;  // airflow per total capacity
        Real64 areaPerTotCap;     // area per total capacity
        Real64 totCapPerArea;     // total capacity per area
        Real64 chlPumpPerFlow;    // chiller pump power per flow
        Real64 cndPumpPerFlow;    // condenser pump power per flow
        Real64 numPeople;         // number of people

        // default constructor
        CompLoadTablesType()
            : desDayNum(0), timeStepMax(0), outsideDryBulb(0.), outsideWetBulb(0.), outsideHumRatio(0.), zoneDryBulb(0.), zoneRelHum(0.),
              supAirTemp(0.), mixAirTemp(0.), mainFanAirFlow(0.), outsideAirFlow(0.), designPeakLoad(0.), diffDesignPeak(0.), peakDesSensLoad(0.),
              estInstDelSensLoad(0.), diffPeakEst(0.), outsideAirRatio(0.), floorArea(0.), airflowPerFlrArea(0.), airflowPerTotCap(0.),
              areaPerTotCap(0.), totCapPerArea(0.), chlPumpPerFlow(0.), cndPumpPerFlow(0.), numPeople(0.)

        {
        }
    };

    struct ZompComponentAreasType
    {
        // members
        Real64 floor;
        Real64 roof;
        Real64 ceiling;
        Real64 extWall;
        Real64 intZoneWall;
        Real64 grndCntWall;
        Real64 extFloor;
        Real64 intZoneFloor;
        Real64 grndCntFloor;
        Real64 fenestration;
        Real64 door;

        // default constructor
        ZompComponentAreasType()
            : floor(0.), roof(0.), ceiling(0.), extWall(0.), intZoneWall(0.), grndCntWall(0.), extFloor(0.), intZoneFloor(0.), grndCntFloor(0.),
              fenestration(0.), door(0.)
        {
        }
    };

    // Object Data
    extern Array1D<OutputTableBinnedType> OutputTableBinned;
    extern Array2D<BinResultsType> BinResults;      // table number, number of intervals
    extern Array1D<BinResultsType> BinResultsBelow; // time below the lowest defined bin
    extern Array1D<BinResultsType> BinResultsAbove; // time above the highest defined bin
    extern Array1D<BinObjVarIDType> BinObjVarID;
    extern Array1D<BinStatisticsType> BinStatistics;
    extern Array1D<NamedMonthlyType> namedMonthly; // for predefined monthly report titles
    extern Array1D<MonthlyFieldSetInputType> MonthlyFieldSetInput;
    extern Array1D<MonthlyInputType> MonthlyInput;
    extern Array1D<MonthlyTablesType> MonthlyTables;
    extern Array1D<MonthlyColumnsType> MonthlyColumns;
    extern Array1D<TOCEntriesType> TOCEntries;
    extern Array1D<UnitConvType> UnitConv;

    // Functions
    void clear_state();

    std::ofstream & open_tbl_stream(int const iStyle, std::string const & filename, bool output_to_file = true);

    void UpdateTabularReports(EnergyPlusData &state, OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

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

    //    GET INPUT ROUTINES

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

    void GetInputTabularMonthly(IOFiles & ioFiles);

    int AddMonthlyReport(std::string const &inReportName, int const inNumDigitsShown);

    void AddMonthlyFieldSetInput(int const inMonthReport, std::string const &inVariMeter, std::string const &inColHead, int const inAggregate);

    void InitializeTabularMonthly();

    bool isInvalidAggregationOrder();

    void GetInputTabularTimeBins(IOFiles & ioFiles);

    bool warningAboutKeyNotFound(int foundIndex, int inObjIndex, std::string const &moduleName);

    void GetInputTabularStyle(IOFiles &ioFiles);

    int SetUnitsStyleFromString(std::string const &unitStringIn);

    void GetInputOutputTableSummaryReports(IOFiles & ioFiles);

    bool isCompLoadRepReq();

    bool hasSizingPeriodsDays();

    void InitializePredefinedMonthlyTitles();

    void CreatePredefinedMonthlyReports();

    void GetInputFuelAndPollutionFactors();

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

    //    OTHER INITIALIZATION ROUTINES

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

    void OpenOutputTabularFile(IOFiles & ioFiles);

    void CloseOutputTabularFile();

    void WriteTableOfContents(EnergyPlusData &state);

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

    //    GATHER DATA EACH TIME STEP ROUTINES

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

    void GatherBinResultsForTimestep(OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

    void GatherMonthlyResultsForTimestep(OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

    void GatherBEPSResultsForTimestep(OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

    void GatherSourceEnergyEndUseResultsForTimestep(OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

    void GatherPeakDemandForTimestep(OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

    void GatherHeatGainReport(OutputProcessor::TimeStepType t_timeStepType); // What kind of data to update (Zone, HVAC)

    void GatherHeatEmissionReport(EnergyPlusData &state, OutputProcessor::TimeStepType t_timeStepType);

    void CalcHeatEmissionReport(EnergyPlusData &state);

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

    //    WRITE OUTPUT FILE ROUTINES

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

    void WriteTabularReports(EnergyPlusData &state);

    void parseStatLine(const std::string & lineIn, StatLineType &lineType, bool & desConditionlinepassed, bool & heatingDesignlinepassed, bool & coolingDesignlinepassed, bool & isKoppen);

    void FillWeatherPredefinedEntries(IOFiles &ioFiles);

    std::string GetColumnUsingTabs(std::string const &inString, // Input String
                                   int const colNum             // Column number
    );

    void FillRemainingPredefinedEntries(EnergyPlusData &state);

    void WriteMonthlyTables(CostEstimateManagerData &dataCostEstimateManager);

    void WriteTimeBinTables(CostEstimateManagerData &dataCostEstimateManager);

    void WriteBEPSTable(CostEstimateManagerData &dataCostEstimateManager,
                        ZoneTempPredictorCorrectorData &dataZoneTempPredictorCorrector,
                        IOFiles &ioFiles);

    std::string ResourceWarningMessage(std::string resource);

    Real64 WaterConversionFunct(Real64 WaterTotal, Real64 ConversionFactor);

    void WriteSourceEnergyEndUseSummary(CostEstimateManagerData &dataCostEstimateManager);

    void WriteDemandEndUseSummary(CostEstimateManagerData &dataCostEstimateManager);

    void WriteCompCostTable(CostEstimateManagerData &dataCostEstimateManager);

    void WriteVeriSumTable(CostEstimateManagerData &dataCostEstimateManager, IOFiles &ioFiles);

    void WriteAdaptiveComfortTable(CostEstimateManagerData &dataCostEstimateManager);

    void WriteThermalResilienceTables();

    void WriteCO2ResilienceTables();

    void WriteVisualResilienceTables();

    void WriteResilienceBinsTable(int const columnNum,
                                  std::vector<int> const &columnHead,
                                  Array1D<std::vector<Real64>> const &ZoneBins);

    void WriteSETHoursTable(int const columnNum,
                            std::vector<std::string> const &columnHead,
                            Array1D<std::vector<Real64>> const &ZoneBins);

    void WriteHeatEmissionTable(CostEstimateManagerData &dataCostEstimateManager);

    void WritePredefinedTables(CostEstimateManagerData &dataCostEstimateManager);

    void WriteComponentSizing(CostEstimateManagerData &dataCostEstimateManager);

    void WriteSurfaceShadowing(CostEstimateManagerData &dataCostEstimateManager);

    void WriteEioTables(CostEstimateManagerData &dataCostEstimateManager, IOFiles &ioFiles);

    int unitsFromHeading(std::string &heading);

    std::vector<std::string> splitCommaString(std::string const &inputString);

    void AddTOCLoadComponentTableSummaries();

    void AllocateLoadComponentArrays();

    void DeallocateLoadComponentArrays();

    void ComputeLoadComponentDecayCurve(IOFiles &ioFiles);

    void GatherComponentLoadsSurface();

    void GatherComponentLoadsHVAC();

    void WriteLoadComponentSummaryTables(EnergyPlusData &state, CostEstimateManagerData &dataCostEstimateManager);

    void GetDelaySequences(int const &desDaySelected,
                           bool const &isCooling,
                           int const &zoneIndex,
                           Array1D<Real64> &peopleDelaySeq,
                           Array1D<Real64> &equipDelaySeq,
                           Array1D<Real64> &hvacLossDelaySeq,
                           Array1D<Real64> &powerGenDelaySeq,
                           Array1D<Real64> &lightDelaySeq,
                           Array1D<Real64> &feneSolarDelaySeq,
                           Array3D<Real64> &feneCondInstantSeq,
                           Array2D<Real64> &surfDelaySeq);

    Real64 MovingAvgAtMaxTime(Array1S<Real64> const &dataSeq, int const &numTimeSteps, int const &maxTimeStep);

    void ComputeTableBodyUsingMovingAvg(Array2D<Real64> &resultCells,
                                        Array2D_bool &resultCellsUsed,
                                        int const &desDaySelected,
                                        int const &timeOfMax,
                                        int const &zoneIndex,
                                        Array1D<Real64> const &peopleDelaySeq,
                                        Array1D<Real64> const &equipDelaySeq,
                                        Array1D<Real64> const &hvacLossDelaySeq,
                                        Array1D<Real64> const &powerGenDelaySeq,
                                        Array1D<Real64> const &lightDelaySeq,
                                        Array1D<Real64> const &feneSolarDelaySeq,
                                        Array3D<Real64> const &feneCondInstantSeqLoc,
                                        Array2D<Real64> const &surfDelaySeq);

    void CollectPeakZoneConditions(
        CompLoadTablesType &compLoad, int const &desDaySelected, int const &timeOfMax, int const &zoneIndex, bool const &isCooling);

    void ComputeEngineeringChecks(CompLoadTablesType &compLoad);

    void GetZoneComponentAreas(Array1D<ZompComponentAreasType> &areas);

    void AddAreaColumnForZone(int const &zoneNum, Array1D<ZompComponentAreasType> const &compAreas, CompLoadTablesType &compLoadTotal);

    void CombineLoadCompResults(CompLoadTablesType &compLoadTotal, CompLoadTablesType const &compLoadPartial, Real64 const &multiplier);

    void AddTotalRowsForLoadSummary(CompLoadTablesType &compLoadTotal);

    void ComputePeakDifference(CompLoadTablesType &compLoad);

    void LoadSummaryUnitConversion(CompLoadTablesType &compLoadTotal);

    void CreateListOfZonesForAirLoop(CompLoadTablesType &compLoad, Array1D_int const &zoneToAirLoop, int const &curAirLoop);

    void OutputCompLoadSummary(CostEstimateManagerData &dataCostEstimateManager,
                               int const &kind, // zone=1, airloop=2, facility=3
                               CompLoadTablesType const &compLoadCool,
                               CompLoadTablesType const &compLoadHeat,
                               int const &zoneOrAirLoopIndex);

    void WriteReportHeaders(std::string const &reportName, std::string const &objectName, OutputProcessor::StoreType const averageOrSum);

    void WriteSubtitle(std::string const &subtitle);

    void WriteTextLine(std::string const &lineOfText, Optional_bool_const isBold = _);

    void WriteTable(CostEstimateManagerData &dataCostEstimateManager,
                    Array2S_string const body, // row,column
                    const Array1D_string &rowLabels,
                    const Array1D_string &columnLabels,
                    Array1D_int &widthColumn,
                    Optional_bool_const transposeXML = _,
                    Optional_string_const footnoteText = _);

    std::string MakeAnchorName(std::string const &reportString, std::string const &objectString);

    std::string InsertCurrencySymbol(CostEstimateManagerData &dataCostEstimateManager,
                                     std::string const &inString, // Input String
                                     bool const isHTML            // True if an HTML string
    );

    std::string ConvertToElementTag(std::string const &inString); // Input String

    std::string ConvertUnicodeToUTF8(unsigned long const codepoint);

    std::string ConvertToEscaped(std::string const &inString); // Input String

    void DetermineBuildingFloorArea();

    /* Tables with Subcategories in particular have a blank for rowHead for display in the HTML output.
     * This routine will fill up the blanks for output to Sql in particular */
    void FillRowHead(Array1D_string & rowHead);

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

    //    ROUTINES TO RESET GATHERED VALUES TO ZERO

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

    void ResetTabularReports();

    void ResetMonthlyGathering();

    void ResetBinGathering();

    void ResetBEPSGathering();

    void ResetSourceEnergyEndUseGathering();

    void ResetPeakDemandGathering();

    void ResetHeatGainGathering();

    void ResetRemainingPredefinedEntries();

    void ResetAdaptiveComfort();

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

    //    ROUTINES RELATED TO IF VALUE IS IN A RANGE

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

    bool isInTriangle(
        Real64 const qx, Real64 const qy, Real64 const x1, Real64 const y1, Real64 const x2, Real64 const y2, Real64 const x3, Real64 const y3);

    bool isInQuadrilateral(Real64 const qx,
                           Real64 const qy,
                           Real64 const ax,
                           Real64 const ay,
                           Real64 const bx,
                           Real64 const by,
                           Real64 const cx,
                           Real64 const cy,
                           Real64 const dx,
                           Real64 const dy);

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

    //    SUPPORT ROUTINES

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

    std::string RealToStr(Real64 const RealIn, int const numDigits);

    Real64 StrToReal(std::string const &stringIn);

    std::string DateToString(int const codedDate); // word containing encoded month, day, hour, minute

    bool isNumber(std::string const &s);

    int digitsAferDecimal(std::string s);

    void AddTOCEntry(std::string const &nameSection, std::string const &nameReport);

    void SetupUnitConversions();

    std::string GetUnitSubString(std::string const &inString); // Input String

    void LookupSItoIP(std::string const &stringInWithSI, int &unitConvIndex, std::string &stringOutWithIP);

    void LookupJtokWH(std::string const &stringInWithJ, int &unitConvIndex, std::string &stringOutWithKWH);

    Real64 ConvertIP(int const unitConvIndex, Real64 const SIvalue);

    Real64 ConvertIPdelta(int const unitConvIndex, Real64 const SIvalue);

    void GetUnitConversion(int const unitConvIndex, Real64 &multiplier, Real64 &offset, std::string &IPunit);

    Real64 getSpecificUnitMultiplier(std::string const &SIunit, std::string const &IPunit);

    Real64 getSpecificUnitDivider(std::string const &SIunit, std::string const &IPunit);

    Real64 getSpecificUnitIndex(std::string const &SIunit, std::string const &IPunit);

} // namespace OutputReportTabular

} // namespace EnergyPlus

#endif

{'repo_name': 'NREL/EnergyPlus', 'stars': '511', 'repo_language': 'C++', 'file_name': 'slabexample.gtp', 'mime_type': 'text/plain', 'hash': -8563953482085819138, 'source_dataset': 'data'}


/*
 * Copyright (C) 2017-2019 Dremio Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dremio.service.namespace.file;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.dremio.service.namespace.file.proto.AvroFileConfig;
import com.dremio.service.namespace.file.proto.ExcelFileConfig;
import com.dremio.service.namespace.file.proto.JsonFileConfig;
import com.dremio.service.namespace.file.proto.ParquetFileConfig;
import com.dremio.service.namespace.file.proto.TextFileConfig;
import com.dremio.service.namespace.file.proto.XlsFileConfig;

/**
 * FileFormat tests
 */
public class TestFileFormat {

  private static void assertContains(String expectedContains, String string) {
    assertTrue(string + " should contain " + expectedContains, string.contains(expectedContains));
  }

  @Test
  public void testDefaultTextFileFormatOptions() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'text'", tableOptions);
    assertContains("fieldDelimiter => ','", tableOptions);
    assertContains("comment => '#'", tableOptions);
    assertContains("\"escape\" => '\"'", tableOptions);
    assertContains("quote => '\"'", tableOptions);
    assertContains("lineDelimiter => '\r\n'", tableOptions);
    assertContains("extractHeader => false", tableOptions);
    assertContains("skipFirstLine => false", tableOptions);
    assertContains("autoGenerateColumnNames => true", tableOptions);
  }

  @Test
  public void testLineDelimiterTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setLineDelimiter("\t");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("lineDelimiter => '\t'", tableOptions);
  }

  @Test
  public void testLineDelimiterTextFileWithSingleQuote() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setLineDelimiter("'a");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("lineDelimiter => '''a'", tableOptions);
  }

  @Test
  public void testCommentTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setComment("$");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("comment => '$'", tableOptions);
  }

  @Test
  public void testEscapeTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setEscape("\\");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("\"escape\" => '\\", tableOptions);
  }

  @Test
  public void testQuoteTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setQuote("\"");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("quote => '\"'", tableOptions);
  }

  @Test
  public void testSingleQuoteTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setQuote("'");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("quote => ''''", tableOptions);
  }

  @Test
  public void testFieldDelimiterTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setFieldDelimiter("@");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("fieldDelimiter => '@'", tableOptions);
  }

  @Test
  public void testExtractHeaderTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setExtractHeader(true);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("extractHeader => true", tableOptions);
  }

  @Test
  public void testsetSkipFirstLineTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setSkipFirstLine(true);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("skipFirstLine => true", tableOptions);
  }

  @Test
  public void testAutoGenerateColumnNamesTextFile() throws Exception {
    TextFileConfig fileFormat = new TextFileConfig();
    fileFormat.setAutoGenerateColumnNames(false);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("autoGenerateColumnNames => false", tableOptions);
  }

  @Test
  public void testDefaultJsonFileFormatOptions() throws Exception {
    JsonFileConfig fileFormat = new JsonFileConfig();
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'json'", tableOptions);
  }

  @Test
  public void testDefaultParquetFileFormatOptions() throws Exception {
    ParquetFileConfig fileFormat = new ParquetFileConfig();
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'parquet'", tableOptions);
  }

  @Test
  public void testDefaultAvroFileFormatOptions() throws Exception {
    AvroFileConfig fileFormat = new AvroFileConfig();
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'avro'", tableOptions);
  }

  @Test
  public void testDefaultExcelFileFormatOptions() throws Exception {
    ExcelFileConfig fileFormat = new ExcelFileConfig();
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("extractHeader => false", tableOptions);
    assertContains("hasMergedCells => false", tableOptions);
    assertContains("xls => false", tableOptions);
  }

  @Test
  public void testDefaultXlsFileFormatOptions() throws Exception {
    XlsFileConfig fileFormat = new XlsFileConfig();
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("extractHeader => false", tableOptions);
    assertContains("hasMergedCells => false", tableOptions);
    assertContains("xls => true", tableOptions);
  }

  @Test
  public void testSheetExcelFile() throws Exception {
    ExcelFileConfig fileFormat = new ExcelFileConfig();
    fileFormat.setSheetName("foo");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => false", tableOptions);
    assertContains("sheet => 'foo'", tableOptions);
  }

  @Test
  public void testSheetExcelFileWithSingleQuote() throws Exception {
    ExcelFileConfig fileFormat = new ExcelFileConfig();
    fileFormat.setSheetName("fo'o");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => false", tableOptions);
    assertContains("sheet => 'fo''o'", tableOptions);
  }

  @Test
  public void testSheetXlsFile() throws Exception {
    XlsFileConfig fileFormat = new XlsFileConfig();
    fileFormat.setSheetName("foo");
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => true", tableOptions);
    assertContains("sheet => 'foo'", tableOptions);
  }

  @Test
  public void testExtractHeaderExcelFile() throws Exception {
    ExcelFileConfig fileFormat = new ExcelFileConfig();
    fileFormat.setExtractHeader(true);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => false", tableOptions);
    assertContains("extractHeader => true", tableOptions);
  }

  @Test
  public void testHasMergedCellsExcelFile() throws Exception {
    ExcelFileConfig fileFormat = new ExcelFileConfig();
    fileFormat.setHasMergedCells(true);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => false", tableOptions);
    assertContains("hasMergedCells => true", tableOptions);
  }

  @Test
  public void testExtractHeaderXlsFile() throws Exception {
    XlsFileConfig fileFormat = new XlsFileConfig();
    fileFormat.setExtractHeader(true);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => true", tableOptions);
    assertContains("extractHeader => true", tableOptions);
  }

  @Test
  public void testHasMergedCellsXlsFile() throws Exception {
    XlsFileConfig fileFormat = new XlsFileConfig();
    fileFormat.setHasMergedCells(true);
    String tableOptions = fileFormat.toTableOptions();
    assertContains("type => 'excel'", tableOptions);
    assertContains("xls => true", tableOptions);
    assertContains("hasMergedCells => true", tableOptions);
  }
}

{'repo_name': 'dremio/dremio-oss', 'stars': '738', 'repo_language': 'Java', 'file_name': 'Hive3PluginOptions.java', 'mime_type': 'text/x-java', 'hash': 7369835101271611980, 'source_dataset': 'data'}


#
# OpenSSL/crypto/ripemd/Makefile
#

DIR=    ripemd
TOP=    ../..
CC=     cc
CPP=    $(CC) -E
INCLUDES=
CFLAG=-g
MAKEFILE=       Makefile
AR=             ar r

RIP_ASM_OBJ=

CFLAGS= $(INCLUDES) $(CFLAG)
ASFLAGS= $(INCLUDES) $(ASFLAG)
AFLAGS= $(ASFLAGS)

GENERAL=Makefile
TEST=rmdtest.c
APPS=

LIB=$(TOP)/libcrypto.a
LIBSRC=rmd_dgst.c rmd_one.c
LIBOBJ=rmd_dgst.o rmd_one.o $(RMD160_ASM_OBJ)

SRC= $(LIBSRC)

EXHEADER= ripemd.h
HEADER= rmd_locl.h rmdconst.h $(EXHEADER)

ALL=    $(GENERAL) $(SRC) $(HEADER)

top:
	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)

all:    lib

lib:    $(LIBOBJ)
	$(AR) $(LIB) $(LIBOBJ)
	$(RANLIB) $(LIB) || echo Never mind.
	@touch lib

rmd-586.s:	asm/rmd-586.pl ../perlasm/x86asm.pl
	$(PERL) asm/rmd-586.pl $(PERLASM_SCHEME) $(CFLAGS) > $@

files:
	$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO

links:
	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)

install:
	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
	do  \
	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
	done;

tags:
	ctags $(SRC)

tests:

lint:
	lint -DLINT $(INCLUDES) $(SRC)>fluff

update: depend

depend:
	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)

dclean:
	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
	mv -f Makefile.new $(MAKEFILE)

clean:
	rm -f *.s *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff

# DO NOT DELETE THIS LINE -- make depend depends on it.

rmd_dgst.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
rmd_dgst.o: ../../include/openssl/opensslconf.h
rmd_dgst.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
rmd_dgst.o: ../../include/openssl/ripemd.h ../../include/openssl/safestack.h
rmd_dgst.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
rmd_dgst.o: ../md32_common.h rmd_dgst.c rmd_locl.h rmdconst.h
rmd_one.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
rmd_one.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
rmd_one.o: ../../include/openssl/ossl_typ.h ../../include/openssl/ripemd.h
rmd_one.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
rmd_one.o: ../../include/openssl/symhacks.h rmd_one.c

{'repo_name': 'microsoft/msix-packaging', 'stars': '656', 'repo_language': 'C++', 'file_name': 'macos.cmake', 'mime_type': 'text/plain', 'hash': -1768926856143725857, 'source_dataset': 'data'}


/*
 **********************************************************************
 *   Copyright (C) 1999-2011, International Business Machines
 *   Corporation and others.  All Rights Reserved.
 **********************************************************************
 *   Date        Name        Description
 *   11/17/99    aliu        Creation.
 **********************************************************************
 */

#include "unicode/utypes.h"

#if !UCONFIG_NO_TRANSLITERATION

#include "unicode/rep.h"
#include "unicode/unifilt.h"
#include "unicode/uniset.h"
#include "unicode/utf16.h"
#include "rbt_rule.h"
#include "rbt_data.h"
#include "cmemory.h"
#include "strmatch.h"
#include "strrepl.h"
#include "util.h"
#include "putilimp.h"

static const UChar FORWARD_OP[] = {32,62,32,0}; // " > "

U_NAMESPACE_BEGIN

/**
 * Construct a new rule with the given input, output text, and other
 * attributes.  A cursor position may be specified for the output text.
 * @param input input string, including key and optional ante and
 * post context
 * @param anteContextPos offset into input to end of ante context, or -1 if
 * none.  Must be <= input.length() if not -1.
 * @param postContextPos offset into input to start of post context, or -1
 * if none.  Must be <= input.length() if not -1, and must be >=
 * anteContextPos.
 * @param output output string
 * @param cursorPosition offset into output at which cursor is located, or -1 if
 * none.  If less than zero, then the cursor is placed after the
 * output; that is, -1 is equivalent to
 * output.length().  If greater than
 * output.length() then an exception is thrown.
 * @param segs array of UnicodeFunctors corresponding to input pattern
 * segments, or null if there are none.  The array itself is adopted,
 * but the pointers within it are not.
 * @param segsCount number of elements in segs[]
 * @param anchorStart TRUE if the the rule is anchored on the left to
 * the context start
 * @param anchorEnd TRUE if the rule is anchored on the right to the
 * context limit
 */
TransliterationRule::TransliterationRule(const UnicodeString& input,
                                         int32_t anteContextPos, int32_t postContextPos,
                                         const UnicodeString& outputStr,
                                         int32_t cursorPosition, int32_t cursorOffset,
                                         UnicodeFunctor** segs,
                                         int32_t segsCount,
                                         UBool anchorStart, UBool anchorEnd,
                                         const TransliterationRuleData* theData,
                                         UErrorCode& status) :
    UMemory(),
    segments(0),
    data(theData) {

    if (U_FAILURE(status)) {
        return;
    }
    // Do range checks only when warranted to save time
    if (anteContextPos < 0) {
        anteContextLength = 0;
    } else {
        if (anteContextPos > input.length()) {
            // throw new IllegalArgumentException("Invalid ante context");
            status = U_ILLEGAL_ARGUMENT_ERROR;
            return;
        }
        anteContextLength = anteContextPos;
    }
    if (postContextPos < 0) {
        keyLength = input.length() - anteContextLength;
    } else {
        if (postContextPos < anteContextLength ||
            postContextPos > input.length()) {
            // throw new IllegalArgumentException("Invalid post context");
            status = U_ILLEGAL_ARGUMENT_ERROR;
            return;
        }
        keyLength = postContextPos - anteContextLength;
    }
    if (cursorPosition < 0) {
        cursorPosition = outputStr.length();
    } else if (cursorPosition > outputStr.length()) {
        // throw new IllegalArgumentException("Invalid cursor position");
        status = U_ILLEGAL_ARGUMENT_ERROR;
        return;
    }
    // We don't validate the segments array.  The caller must
    // guarantee that the segments are well-formed (that is, that
    // all $n references in the output refer to indices of this
    // array, and that no array elements are null).
    this->segments = segs;
    this->segmentsCount = segsCount;

    pattern = input;
    flags = 0;
    if (anchorStart) {
        flags |= ANCHOR_START;
    }
    if (anchorEnd) {
        flags |= ANCHOR_END;
    }

    anteContext = NULL;
    if (anteContextLength > 0) {
        anteContext = new StringMatcher(pattern, 0, anteContextLength,
                                        FALSE, *data);
        /* test for NULL */
        if (anteContext == 0) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return;
        }
    }

    key = NULL;
    if (keyLength > 0) {
        key = new StringMatcher(pattern, anteContextLength, anteContextLength + keyLength,
                                FALSE, *data);
        /* test for NULL */
        if (key == 0) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return;
        }
    }

    int32_t postContextLength = pattern.length() - keyLength - anteContextLength;
    postContext = NULL;
    if (postContextLength > 0) {
        postContext = new StringMatcher(pattern, anteContextLength + keyLength, pattern.length(),
                                        FALSE, *data);
        /* test for NULL */
        if (postContext == 0) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return;
        }
    }

    this->output = new StringReplacer(outputStr, cursorPosition + cursorOffset, data);
    /* test for NULL */
    if (this->output == 0) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return;
    }
}

/**
 * Copy constructor.
 */
TransliterationRule::TransliterationRule(TransliterationRule& other) :
    UMemory(other),
    anteContext(NULL),
    key(NULL),
    postContext(NULL),
    pattern(other.pattern),
    anteContextLength(other.anteContextLength),
    keyLength(other.keyLength),
    flags(other.flags),
    data(other.data) {

    segments = NULL;
    segmentsCount = 0;
    if (other.segmentsCount > 0) {
        segments = (UnicodeFunctor **)uprv_malloc(other.segmentsCount * sizeof(UnicodeFunctor *));
        uprv_memcpy(segments, other.segments, other.segmentsCount*sizeof(segments[0]));
    }

    if (other.anteContext != NULL) {
        anteContext = (StringMatcher*) other.anteContext->clone();
    }
    if (other.key != NULL) {
        key = (StringMatcher*) other.key->clone();
    }
    if (other.postContext != NULL) {
        postContext = (StringMatcher*) other.postContext->clone();
    }
    output = other.output->clone();
}

TransliterationRule::~TransliterationRule() {
    uprv_free(segments);
    delete anteContext;
    delete key;
    delete postContext;
    delete output;
}

/**
 * Return the preceding context length.  This method is needed to
 * support the Transliterator method
 * getMaximumContextLength().  Internally, this is
 * implemented as the anteContextLength, optionally plus one if
 * there is a start anchor.  The one character anchor gap is
 * needed to make repeated incremental transliteration with
 * anchors work.
 */
int32_t TransliterationRule::getContextLength(void) const {
    return anteContextLength + ((flags & ANCHOR_START) ? 1 : 0);
}

/**
 * Internal method.  Returns 8-bit index value for this rule.
 * This is the low byte of the first character of the key,
 * unless the first character of the key is a set.  If it's a
 * set, or otherwise can match multiple keys, the index value is -1.
 */
int16_t TransliterationRule::getIndexValue() const {
    if (anteContextLength == pattern.length()) {
        // A pattern with just ante context {such as foo)>bar} can
        // match any key.
        return -1;
    }
    UChar32 c = pattern.char32At(anteContextLength);
    return (int16_t)(data->lookupMatcher(c) == NULL ? (c & 0xFF) : -1);
}

/**
 * Internal method.  Returns true if this rule matches the given
 * index value.  The index value is an 8-bit integer, 0..255,
 * representing the low byte of the first character of the key.
 * It matches this rule if it matches the first character of the
 * key, or if the first character of the key is a set, and the set
 * contains any character with a low byte equal to the index
 * value.  If the rule contains only ante context, as in foo)>bar,
 * then it will match any key.
 */
UBool TransliterationRule::matchesIndexValue(uint8_t v) const {
    // Delegate to the key, or if there is none, to the postContext.
    // If there is neither then we match any key; return true.
    UnicodeMatcher *m = (key != NULL) ? key : postContext;
    return (m != NULL) ? m->matchesIndexValue(v) : TRUE;
}

/**
 * Return true if this rule masks another rule.  If r1 masks r2 then
 * r1 matches any input string that r2 matches.  If r1 masks r2 and r2 masks
 * r1 then r1 == r2.  Examples: "a>x" masks "ab>y".  "a>x" masks "a[b]>y".
 * "[c]a>x" masks "[dc]a>y".
 */
UBool TransliterationRule::masks(const TransliterationRule& r2) const {
    /* Rule r1 masks rule r2 if the string formed of the
     * antecontext, key, and postcontext overlaps in the following
     * way:
     *
     * r1:      aakkkpppp
     * r2:     aaakkkkkpppp
     *            ^
     *
     * The strings must be aligned at the first character of the
     * key.  The length of r1 to the left of the alignment point
     * must be <= the length of r2 to the left; ditto for the
     * right.  The characters of r1 must equal (or be a superset
     * of) the corresponding characters of r2.  The superset
     * operation should be performed to check for UnicodeSet
     * masking.
     *
     * Anchors:  Two patterns that differ only in anchors only
     * mask one another if they are exactly equal, and r2 has
     * all the anchors r1 has (optionally, plus some).  Here Y
     * means the row masks the column, N means it doesn't.
     *
     *         ab   ^ab    ab$  ^ab$
     *   ab    Y     Y     Y     Y
     *  ^ab    N     Y     N     Y
     *   ab$   N     N     Y     Y
     *  ^ab$   N     N     N     Y
     *
     * Post context: {a}b masks ab, but not vice versa, since {a}b
     * matches everything ab matches, and {a}b matches {|a|}b but ab
     * does not.  Pre context is different (a{b} does not align with
     * ab).
     */

    /* LIMITATION of the current mask algorithm: Some rule
     * maskings are currently not detected.  For example,
     * "{Lu}]a>x" masks "A]a>y".  This can be added later. TODO
     */

    int32_t len = pattern.length();
    int32_t left = anteContextLength;
    int32_t left2 = r2.anteContextLength;
    int32_t right = len - left;
    int32_t right2 = r2.pattern.length() - left2;
    int32_t cachedCompare = r2.pattern.compare(left2 - left, len, pattern);

    // TODO Clean this up -- some logic might be combinable with the
    // next statement.

    // Test for anchor masking
    if (left == left2 && right == right2 &&
        keyLength <= r2.keyLength &&
        0 == cachedCompare) {
        // The following boolean logic implements the table above
        return (flags == r2.flags) ||
            (!(flags & ANCHOR_START) && !(flags & ANCHOR_END)) ||
            ((r2.flags & ANCHOR_START) && (r2.flags & ANCHOR_END));
    }

    return left <= left2 &&
        (right < right2 ||
         (right == right2 && keyLength <= r2.keyLength)) &&
         (0 == cachedCompare);
}

static inline int32_t posBefore(const Replaceable& str, int32_t pos) {
    return (pos > 0) ?
        pos - U16_LENGTH(str.char32At(pos-1)) :
        pos - 1;
}

static inline int32_t posAfter(const Replaceable& str, int32_t pos) {
    return (pos >= 0 && pos < str.length()) ?
        pos + U16_LENGTH(str.char32At(pos)) :
        pos + 1;
}

/**
 * Attempt a match and replacement at the given position.  Return
 * the degree of match between this rule and the given text.  The
 * degree of match may be mismatch, a partial match, or a full
 * match.  A mismatch means at least one character of the text
 * does not match the context or key.  A partial match means some
 * context and key characters match, but the text is not long
 * enough to match all of them.  A full match means all context
 * and key characters match.
 *
 * If a full match is obtained, perform a replacement, update pos,
 * and return U_MATCH.  Otherwise both text and pos are unchanged.
 *
 * @param text the text
 * @param pos the position indices
 * @param incremental if TRUE, test for partial matches that may
 * be completed by additional text inserted at pos.limit.
 * @return one of U_MISMATCH,
 * U_PARTIAL_MATCH, or U_MATCH.  If
 * incremental is FALSE then U_PARTIAL_MATCH will not be returned.
 */
UMatchDegree TransliterationRule::matchAndReplace(Replaceable& text,
                                                  UTransPosition& pos,
                                                  UBool incremental) const {
    // Matching and replacing are done in one method because the
    // replacement operation needs information obtained during the
    // match.  Another way to do this is to have the match method
    // create a match result struct with relevant offsets, and to pass
    // this into the replace method.

    // ============================ MATCH ===========================

    // Reset segment match data
    if (segments != NULL) {
        for (int32_t i=0; i<segmentsCount; ++i) {
            ((StringMatcher*) segments[i])->resetMatch();
        }
    }

//    int32_t lenDelta, keyLimit;
    int32_t keyLimit;

    // ------------------------ Ante Context ------------------------

    // A mismatch in the ante context, or with the start anchor,
    // is an outright U_MISMATCH regardless of whether we are
    // incremental or not.
    int32_t oText; // offset into 'text'
//    int32_t newStart = 0;
    int32_t minOText;

    // Note (1): We process text in 16-bit code units, rather than
    // 32-bit code points.  This works because stand-ins are
    // always in the BMP and because we are doing a literal match
    // operation, which can be done 16-bits at a time.

    int32_t anteLimit = posBefore(text, pos.contextStart);

    UMatchDegree match;

    // Start reverse match at char before pos.start
    oText = posBefore(text, pos.start);

    if (anteContext != NULL) {
        match = anteContext->matches(text, oText, anteLimit, FALSE);
        if (match != U_MATCH) {
            return U_MISMATCH;
        }
    }

    minOText = posAfter(text, oText);

    // ------------------------ Start Anchor ------------------------

    if (((flags & ANCHOR_START) != 0) && oText != anteLimit) {
        return U_MISMATCH;
    }

    // -------------------- Key and Post Context --------------------

    oText = pos.start;

    if (key != NULL) {
        match = key->matches(text, oText, pos.limit, incremental);
        if (match != U_MATCH) {
            return match;
        }
    }

    keyLimit = oText;

    if (postContext != NULL) {
        if (incremental && keyLimit == pos.limit) {
            // The key matches just before pos.limit, and there is
            // a postContext.  Since we are in incremental mode,
            // we must assume more characters may be inserted at
            // pos.limit -- this is a partial match.
            return U_PARTIAL_MATCH;
        }

        match = postContext->matches(text, oText, pos.contextLimit, incremental);
        if (match != U_MATCH) {
            return match;
        }
    }

    // ------------------------- Stop Anchor ------------------------

    if (((flags & ANCHOR_END)) != 0) {
        if (oText != pos.contextLimit) {
            return U_MISMATCH;
        }
        if (incremental) {
            return U_PARTIAL_MATCH;
        }
    }

    // =========================== REPLACE ==========================

    // We have a full match.  The key is between pos.start and
    // keyLimit.

    int32_t newStart;
    int32_t newLength = output->toReplacer()->replace(text, pos.start, keyLimit, newStart);
    int32_t lenDelta = newLength - (keyLimit - pos.start);

    oText += lenDelta;
    pos.limit += lenDelta;
    pos.contextLimit += lenDelta;
    // Restrict new value of start to [minOText, min(oText, pos.limit)].
    pos.start = uprv_max(minOText, uprv_min(uprv_min(oText, pos.limit), newStart));
    return U_MATCH;
}

/**
 * Create a source string that represents this rule.  Append it to the
 * given string.
 */
UnicodeString& TransliterationRule::toRule(UnicodeString& rule,
                                           UBool escapeUnprintable) const {

    // Accumulate special characters (and non-specials following them)
    // into quoteBuf.  Append quoteBuf, within single quotes, when
    // a non-quoted element must be inserted.
    UnicodeString str, quoteBuf;

    // Do not emit the braces '{' '}' around the pattern if there
    // is neither anteContext nor postContext.
    UBool emitBraces =
        (anteContext != NULL) || (postContext != NULL);

    // Emit start anchor
    if ((flags & ANCHOR_START) != 0) {
        rule.append((UChar)94/*^*/);
    }

    // Emit the input pattern
    ICU_Utility::appendToRule(rule, anteContext, escapeUnprintable, quoteBuf);

    if (emitBraces) {
        ICU_Utility::appendToRule(rule, (UChar) 0x007B /*{*/, TRUE, escapeUnprintable, quoteBuf);
    }

    ICU_Utility::appendToRule(rule, key, escapeUnprintable, quoteBuf);

    if (emitBraces) {
        ICU_Utility::appendToRule(rule, (UChar) 0x007D /*}*/, TRUE, escapeUnprintable, quoteBuf);
    }

    ICU_Utility::appendToRule(rule, postContext, escapeUnprintable, quoteBuf);

    // Emit end anchor
    if ((flags & ANCHOR_END) != 0) {
        rule.append((UChar)36/*$*/);
    }

    ICU_Utility::appendToRule(rule, UnicodeString(TRUE, FORWARD_OP, 3), TRUE, escapeUnprintable, quoteBuf);

    // Emit the output pattern

    ICU_Utility::appendToRule(rule, output->toReplacer()->toReplacerPattern(str, escapeUnprintable),
                              TRUE, escapeUnprintable, quoteBuf);

    ICU_Utility::appendToRule(rule, (UChar) 0x003B /*;*/, TRUE, escapeUnprintable, quoteBuf);

    return rule;
}

void TransliterationRule::setData(const TransliterationRuleData* d) {
    data = d;
    if (anteContext != NULL) anteContext->setData(d);
    if (postContext != NULL) postContext->setData(d);
    if (key != NULL) key->setData(d);
    // assert(output != NULL);
    output->setData(d);
    // Don't have to do segments since they are in the context or key
}

/**
 * Union the set of all characters that may be modified by this rule
 * into the given set.
 */
void TransliterationRule::addSourceSetTo(UnicodeSet& toUnionTo) const {
    int32_t limit = anteContextLength + keyLength;
    for (int32_t i=anteContextLength; i<limit; ) {
        UChar32 ch = pattern.char32At(i);
        i += U16_LENGTH(ch);
        const UnicodeMatcher* matcher = data->lookupMatcher(ch);
        if (matcher == NULL) {
            toUnionTo.add(ch);
        } else {
            matcher->addMatchSetTo(toUnionTo);
        }
    }
}

/**
 * Union the set of all characters that may be emitted by this rule
 * into the given set.
 */
void TransliterationRule::addTargetSetTo(UnicodeSet& toUnionTo) const {
    output->toReplacer()->addReplacementSetTo(toUnionTo);
}

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_TRANSLITERATION */

//eof

{'repo_name': 'mbbill/JSC.js', 'stars': '279', 'repo_language': 'C++', 'file_name': 'updateGN.md', 'mime_type': 'text/plain', 'hash': 3796974906773176699, 'source_dataset': 'data'}


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

// Preprocessed version of "boost/mpl/or.hpp" header
// -- DO NOT modify by hand!

namespace boost { namespace mpl {

namespace aux {
template< bool C_ > struct or_impl
{
    template<
          typename T1, typename T2, typename T3, typename T4
        >
    struct result_
        : true_
    {
    };
};

template<> struct or_impl<false>
{
    template<
          typename T1, typename T2, typename T3, typename T4
        >
    struct result_
        : or_impl<
              BOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
            >::template result_< T2,T3,T4,false_ >
    {
    };
};

template<>
struct or_impl<false>
    ::result_< false_,false_,false_,false_ >
        : false_
{
};

} // namespace aux

template<
      typename BOOST_MPL_AUX_NA_PARAM(T1)
    , typename BOOST_MPL_AUX_NA_PARAM(T2)
    , typename T3 = false_, typename T4 = false_, typename T5 = false_
    >
struct or_

    : aux::or_impl<
          BOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
        >::template result_< T2,T3,T4,T5 >

{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(
          5
        , or_
        , ( T1, T2, T3, T4, T5)
        )
};

BOOST_MPL_AUX_NA_SPEC2(
      2
    , 5
    , or_
    )

}}

{'repo_name': 'libMesh/libmesh', 'stars': '398', 'repo_language': 'C', 'file_name': 'libmesh_citations.py', 'mime_type': 'text/x-python', 'hash': 5019736450836645650, 'source_dataset': 'data'}