text:
import path from 'path';
import expect from 'expect.js';
import { fromRoot } from '../../../utils';
import { resolve } from 'path';
import { parseMilliseconds, parse, getPlatform } from '../settings';

describe('kibana cli', function () {

  describe('plugin installer', function () {

    describe('command line option parsing', function () {

      describe('parseMilliseconds function', function () {

        it('should return 0 for an empty string', function () {
          const value = '';
          const result = parseMilliseconds(value);

          expect(result).to.be(0);
        });

        it('should return 0 for a number with an invalid unit of measure', function () {
          const result = parseMilliseconds('1gigablasts');
          expect(result).to.be(0);
        });

        it('should assume a number with no unit of measure is specified as milliseconds', function () {
          const result = parseMilliseconds(1);
          expect(result).to.be(1);

          const result2 = parseMilliseconds('1');
          expect(result2).to.be(1);
        });

        it('should interpret a number with "s" as the unit of measure as seconds', function () {
          const result = parseMilliseconds('5s');
          expect(result).to.be(5 * 1000);
        });

        it('should interpret a number with "second" as the unit of measure as seconds', function () {
          const result = parseMilliseconds('5second');
          expect(result).to.be(5 * 1000);
        });

        it('should interpret a number with "seconds" as the unit of measure as seconds', function () {
          const result = parseMilliseconds('5seconds');
          expect(result).to.be(5 * 1000);
        });

        it('should interpret a number with "m" as the unit of measure as minutes', function () {
          const result = parseMilliseconds('9m');
          expect(result).to.be(9 * 1000 * 60);
        });

        it('should interpret a number with "minute" as the unit of measure as minutes', function () {
          const result = parseMilliseconds('9minute');
          expect(result).to.be(9 * 1000 * 60);
        });

        it('should interpret a number with "minutes" as the unit of measure as minutes', function () {
          const result = parseMilliseconds('9minutes');
          expect(result).to.be(9 * 1000 * 60);
        });

      });

      describe('parse function', function () {

        const command = 'plugin name';
        let options = {};
        const kbnPackage = { version: 1234 };
        beforeEach(function () {
          options = { pluginDir: fromRoot('plugins') };
        });

        describe('timeout option', function () {

          it('should default to 0 (milliseconds)', function () {
            const settings = parse(command, options, kbnPackage);

            expect(settings.timeout).to.be(0);
          });

          it('should set settings.timeout property', function () {
            options.timeout = 1234;
            const settings = parse(command, options, kbnPackage);

            expect(settings.timeout).to.be(1234);
          });

        });

        describe('quiet option', function () {

          it('should default to false', function () {
            const settings = parse(command, options, kbnPackage);

            expect(settings.quiet).to.be(false);
          });

          it('should set settings.quiet property to true', function () {
            options.quiet = true;
            const settings = parse(command, options, kbnPackage);

            expect(settings.quiet).to.be(true);
          });

        });

        describe('silent option', function () {

          it('should default to false', function () {
            const settings = parse(command, options, kbnPackage);

            expect(settings.silent).to.be(false);
          });

          it('should set settings.silent property to true', function () {
            options.silent = true;
            const settings = parse(command, options, kbnPackage);

            expect(settings.silent).to.be(true);
          });

        });

        describe('config option', function () {

          it('should default to ZLS', function () {
            const settings = parse(command, options, kbnPackage);

            expect(settings.config).to.be('');
          });

          it('should set settings.config property', function () {
            options.config = 'foo bar baz';
            const settings = parse(command, options, kbnPackage);

            expect(settings.config).to.be('foo bar baz');
          });

        });

        describe('pluginDir option', function () {

          it('should default to plugins', function () {
            const settings = parse(command, options, kbnPackage);

            expect(settings.pluginDir).to.be(fromRoot('plugins'));
          });

          it('should set settings.config property', function () {
            options.pluginDir = 'foo bar baz';
            const settings = parse(command, options, kbnPackage);

            expect(settings.pluginDir).to.be('foo bar baz');
          });

        });

        describe('command value', function () {

          it('should set settings.plugin property', function () {
            const settings = parse(command, options, kbnPackage);

            expect(settings.plugin).to.be(command);
          });

        });

        describe('urls collection', function () {

          it('should populate the settings.urls property', function () {
            const settings = parse(command, options, kbnPackage);

            const expected = [
              command,
              `https://artifacts.elastic.co/downloads/kibana-plugins/${command}/${command}-1234.zip`
            ];

            expect(settings.urls).to.eql(expected);
          });

        });

        describe('workingPath value', function () {

          it('should set settings.workingPath property', function () {
            options.pluginDir = 'foo/bar/baz';
            const settings = parse(command, options, kbnPackage);
            const expected = resolve('foo/bar/baz', '.plugin.installing');

            expect(settings.workingPath).to.be(expected);
          });

        });

        describe('tempArchiveFile value', function () {

          it('should set settings.tempArchiveFile property', function () {
            options.pluginDir = 'foo/bar/baz';
            const settings = parse(command, options, kbnPackage);
            const expected = resolve('foo/bar/baz', '.plugin.installing', 'archive.part');

            expect(settings.tempArchiveFile).to.be(expected);
          });

        });

        describe('tempPackageFile value', function () {

          it('should set settings.tempPackageFile property', function () {
            options.pluginDir = 'foo/bar/baz';
            const settings = parse(command, options, kbnPackage);
            const expected = resolve('foo/bar/baz', '.plugin.installing', 'package.json');

            expect(settings.tempPackageFile).to.be(expected);
          });

        });

      });

    });

  });

});


text:
package com.twitter.finagle.offload

import com.twitter.concurrent.NamedPoolThreadFactory
import com.twitter.finagle.offload.DefaultThreadPoolExecutor.RunsOnNettyThread
import com.twitter.finagle.stats.Counter
import com.twitter.finagle.stats.StatsReceiver
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.RejectedExecutionHandler
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

private[twitter] class DefaultThreadPoolExecutor(poolSize: Int, stats: StatsReceiver)
    extends ThreadPoolExecutor(
      poolSize /*corePoolSize*/,
      poolSize /*maximumPoolSize*/,
      0L /*keepAliveTime*/,
      TimeUnit.MILLISECONDS,
      new LinkedBlockingQueue[Runnable]() /*workQueue*/,
      new NamedPoolThreadFactory("finagle/offload", makeDaemons = true) /*threadFactory*/,
      new RunsOnNettyThread(stats.counter("not_offloaded_tasks")))

private object DefaultThreadPoolExecutor {

  // This handler is run when the submitted work is rejected from the ThreadPool, usually because
  // its work queue has reached the proposed limit. When that happens, we simply run the work on
  // the current thread (a thread that was trying to offload), which is most commonly a Netty IO
  // worker.
  private final class RunsOnNettyThread(rejections: Counter) extends RejectedExecutionHandler {
    def rejectedExecution(r: Runnable, e: ThreadPoolExecutor): Unit = {
      if (!e.isShutdown) {
        rejections.incr()
        r.run()
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
import django_filters as filters
import django_tables2 as tables
from django.utils.safestring import mark_safe
from django_tables2.utils import AttributeDict

class CustomCheckBoxColumn(tables.CheckBoxColumn):

    @property
    def header(self):
        default = {"type": "checkbox",
                   "class": "toggle-all",
                   }
        general = self.attrs.get('input')
        specific = self.attrs.get('th__input')
        attrs = AttributeDict(default, **(specific or general or {}))
        return mark_safe('<input %s /> ' % attrs.as_html())

    def render(self, value, bound_column):  # pylint: disable=W0221
        default = {
            'type': 'checkbox',
            'name': bound_column.name,
            'class': 'id-check',
            'value': value
        }
        general = self.attrs.get('input')
        specific = self.attrs.get('td__input')
        attrs = AttributeDict(default, **(specific or general or {}))
        return mark_safe('<input %s/>' % attrs.as_html())

class Table(tables.Table):
    """Generic class with common properties for all tables."""
    ids = CustomCheckBoxColumn(accessor='pk',
                               orderable=False)

    class Meta:
        attrs = {"class": "paleblue"}
        sequence = ("ids", "...",)

class FilterSet(filters.FilterSet):
    """Generic class that allows filter for all the model fields."""
    class Meta:
        model = None


text:
/* globals document */
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';

const rootEl = document.getElementById('app');
ReactDOM.render(<App />, rootEl);


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>Suara Viajes</title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/normalize.css" type="text/css" rel="stylesheet">
  <link href="css/font-awesome.min.css" rel="stylesheet" >
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/main.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/social-media.css" type="text/css" rel="stylesheet"/>

  <link rel="icon" sizes="192x192" href="images/suara_logo.png"/>
  <meta name="theme-color" content="#009cde">

Nosotros

Destinos

Luna de Miel

Formas de Pago

Nosotros

Destinos

Luna de Miel

Formas de Pago

      menu

Footer Content

You can use rows and columns here to organize your footer content.

Links

Link 1

Link 2

Link 3

Link 4

        © 2018 Suara Viajes


text:
/**
 * @file
 * Persistence functions - reading information from and saving data to disk
 */

#include "Persistence.h"
#include "Log.h"
#include "Broker.h"
#include "Socket.h"
#include "SubsEngine.h"
#include "Bridge.h"
#include "MQTTProtocol.h"
#include "Topics.h"
#include "Messages.h"
#include "Clients.h"
#include "Users.h"
#include "StackTrace.h"

#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <memory.h>
#include <stdlib.h>
#include <sys/stat.h>

#include "Heap.h"

#if defined(WIN32)
#define snprintf _snprintf
#endif

int (*functions[])(char*);

enum {
	PROPERTY_INT, PROPERTY_STRING, PROPERTY_BOOLEAN, PROPERTY_STRING_LIST, PROPERTY_FUNCTION
} PROPERTY_TYPE;

/**
 * Property values to be read from the configuration file
 */
typedef struct
{
	char* name;		/**< name of the property string */
	int type;		/**< 0 = int, 1 = string, 2 = boolean, 3 = list of strings, 4 = function */
	int location;	/**< pointer to the position in the structure where this value is stored */
} property;

/**
 * Broker properties
 */
property brokerProps[] =
{
	{ "log_level", PROPERTY_INT, offsetof(trace_settings_type, log_level) },
	{ "max_log_entries", 0, offsetof(trace_settings_type, max_log_entries) },
	{ "trace_level", 0, offsetof(trace_settings_type, trace_level) },
	{ "trace_output", 4, 1 },
	{ "max_trace_entries", 0, offsetof(trace_settings_type, max_trace_entries) },
	{ "connection_messages", 2, offsetof(BrokerStates, connection_messages) },
	{ "max_inflight_messages", 0, offsetof(BrokerStates, max_inflight_messages) },
	{ "max_queued_messages", 0, offsetof(BrokerStates, max_queued_messages) },
	{ "retry_interval", 0, offsetof(BrokerStates, retry_interval) } ,
	{ "ffdc_output", 1, offsetof(BrokerStates, ffdc_location) },
	{ "persistence_location", 1, offsetof(BrokerStates, persistence_location) },
	{ "retained_persistence", 2, offsetof(BrokerStates, persistence) },
	{ "persistence", 2, offsetof(BrokerStates, persistence) }, /* synonym for retained_persistence */
	{ "autosave_on_changes", 2, offsetof(BrokerStates, autosave_on_changes) },
	{ "autosave_interval", PROPERTY_INT, offsetof(BrokerStates, autosave_interval) },
	{ "clientid_prefixes", 3, offsetof(BrokerStates, clientid_prefixes) },
#if !defined(NO_BRIDGE)
	{ "connection", 1, offsetof(BridgeConnections, name) },
#endif
#if defined(SINGLE_LISTENER)
	{ "port", 0, offsetof(BrokerStates, port) },
	{ "bind_address", 1, offsetof(BrokerStates, bind_address) },
	{ "max_connections", 0, offsetof(BrokerStates, max_connections) },
#else
	{ "listener", 1, 0 },
	{ "port", 0, 0 },
	{ "bind_address", 1, 0 },
	{ "max_connections", 0, 0 },
	{ "ipv6", 2, 0 },
#endif
	{ "password_file", 1, offsetof(BrokerStates, password_file) },
	{ "acl_file", 1, offsetof(BrokerStates, acl_file) },
	{ "allow_anonymous", 2, offsetof(BrokerStates, allow_anonymous) },
#if defined(MQTTS)
	{ "max_mqtts_packet_size", PROPERTY_INT, offsetof(BrokerStates, max_mqtts_packet_size) },
	{ "predefined_topics_file", PROPERTY_STRING, offsetof(BrokerStates, predefined_topics_file) },
#endif
};

#if !defined(ARRAY_SIZE)
/**
 * Macro to calculate the number of entries in an array
 */
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#endif

/**
 * size of the broker property array
 */
#define broker_props_count ARRAY_SIZE(brokerProps)

#if !defined(NO_BRIDGE)
/**
 * Bridge connection properties
 */
property bridgeProps[] =
{
	{ "notifications", 2, offsetof(BridgeConnections, notifications) },
	{ "round_robin", 2, offsetof(BridgeConnections, round_robin) },
	{ "try_private", 2, offsetof(BridgeConnections, try_private) },
	{ "address", 3, offsetof(BridgeConnections, addresses) }, /* synonym for addresses */
	{ "addresses", 3, offsetof(BridgeConnections, addresses) },
	{ "topic", 1, offsetof(BridgeConnections, topics) },
	{ "connection", 1, offsetof(BridgeConnections, name) },
	{ "notification_topic", 1, offsetof(BridgeConnections, notification_topic) },
	{ "keepalive_interval", 0, offsetof(BridgeConnections, keepalive_interval) },
	{ "start_type", 0, offsetof(BridgeConnections, start_type) },
	{ "idle_timeout", 0, offsetof(BridgeConnections, idle_timeout) },
	{ "threshold", 0, offsetof(BridgeConnections, threshold) },
	{ "cleansession", 2, offsetof(BridgeConnections, cleansession) },
#if defined(MQTTS)
	{ "protocol", 1, offsetof(BridgeConnections, protocol) },
	{ "loopback", PROPERTY_INT, offsetof(BridgeConnections, loopback) },
#endif
#if !defined(SINGLE_LISTENER)
	{ "listener", 1, 0 },
#endif
	{ "username", 1, offsetof(BridgeConnections, username) },
	{ "password", 1, offsetof(BridgeConnections, password) },
	{ "clientid", 1, offsetof(BridgeConnections, clientid) },
};
/**
 * size of the bridge properties array
 */
#define bridge_props_count ARRAY_SIZE(bridgeProps)
#endif

#if !defined(SINGLE_LISTENER)
/**
 * Listener properties
 */
property listenerProps[] =
{
	{ "listener", 1, 0 },
	{ "max_connections", 0, offsetof(Listener, max_connections) },
	{ "mount_point", 1, offsetof(Listener, mount_point) },
	{ "ipv6", 2, offsetof(Listener, ipv6) },
#if defined(MQTTS)
	{ "multicast_groups", 3, offsetof(Listener, multicast_groups) },
	{ "advertise", 1, offsetof(Listener, advertise) },
	{ "loopback", PROPERTY_INT, offsetof(Listener, loopback) },
#endif
	{ "connection", 1, offsetof(BridgeConnections, name) },
};
/**
 * size of the listener properties array
 */
#define listener_props_count ARRAY_SIZE(listenerProps)
#endif

#if defined(WIN32)
/**
 * strtok_r mapping for Windows
 */
#define strtok_r strtok_s
#else
/**
 * _unlink mapping for linux
 */
#define _unlink unlink
#endif

char* delims = " \t\r\n";	/**< token delimiters string for strtok */
char* pwordDelims = ":\r\n";

static BrokerStates* bstate;	/**< pointer to broker state structure */

int Persistence_process_acl_file(FILE* afile, BrokerStates* bs)
{
	User* currentUser = NULL;
	char curline[120], *curpos, *topic;
	int rc = 0;
	int line = 0;

	FUNC_ENTRY;
	while (fgets(curline, sizeof(curline),afile))
	{
		char* command = strtok_r(curline,delims, &curpos);
		if (command && command[0] != '\0' && command[0] != '#')
		{
			if (strcmp(command, "user") == 0)
			{
				char* user = strtok_r(NULL, delims, &curpos);
				if ((currentUser = Users_get_user(user)) == NULL)
				{
					rc = -98;
					Log(LOG_WARNING, 40, NULL, user, line);
					break;
				}
			}
			else if (strcmp(command, "topic") == 0)
			{
				// scan to the first non-whitespace char
				while(curpos[0] != '\0' && (curpos[0]==' ' || curpos[0]=='\t' || curpos[0]=='\n'|| curpos[0]=='\r'))
					curpos++;
				if (strlen(curpos) > 0)
				{
					// there is meaningful content on this line
					int permission = ACL_FULL;

					// check for the two permissions (read/write) followed by whitespace
					if (strncmp(curpos,"read",4)==0 && strlen(curpos)>4 && (curpos[4]==' ' || curpos[4]=='\t'))
					{
						permission = ACL_READ;
						curpos += 4;
					}
					else if (strncmp(curpos,"write",5)==0 && strlen(curpos)>5 && (curpos[5]==' ' || curpos[5]=='\t'))
					{
						permission = ACL_WRITE;
						curpos += 5;
					}
					// if a permission token was read, ignore the next block of whitespace
					// to reach the start of the topic
					if (permission != ACL_FULL)
						while(curpos[0] != '\0' && (curpos[0]==' ' || curpos[0]=='\t'))
							curpos++;

					// strip off any end-of-line chars
					topic = strtok(curpos, "\r\n");

					if (permission == ACL_FULL || permission == ACL_READ)
					{
						if ( (strchr(topic, '+') != NULL) || (strcspn(topic,"#") < strlen(topic) - 1))
						{
							rc = -98;
							Log(LOG_WARNING, 151, NULL, topic);
							break;
						}
					}

					if (currentUser == NULL)
						Users_add_default_rule(topic,permission);
					else
						Users_add_rule(currentUser,topic,permission);
				}
				else
				{
					rc = -98;
					Log(LOG_WARNING, 41, NULL, line);
					break;
				}
			}
			else
			{
				rc = -98;
				Log(LOG_WARNING, 41, NULL, line);
				break;
			}
		}
		line++;
	}
	FUNC_EXIT_RC(rc);
	return rc;
}

int Persistence_process_user_file(FILE* ufile, BrokerStates* bs)
{
	char curline[120], *curpos;
	int rc = 0;
	int line = 1;

	FUNC_ENTRY;
	while (fgets(curline, sizeof(curline),ufile))
	{
		char* user = strtok_r(curline, pwordDelims, &curpos);
		if (user && user[0] != '\0' && user[0] != '#')
		{
			char* password = strtok_r(NULL, pwordDelims, &curpos);
			if (password)
				Users_add_user(user, password);
			else
			{
				Log(LOG_WARNING, 39, NULL, line);
				rc = -98;
				break;
			}
		}
		line++;
	}
	FUNC_EXIT_RC(rc);
	return rc;
}

#if defined(MQTTS)
int Persistence_process_predefined_topics_file(FILE* ifile, BrokerStates* bs)
{
	char curline[120], *curpos, *topic ;
	int rc = 0;
	int line = 0;

	FUNC_ENTRY;
	Tree *predefined_topics = bs->default_predefined_topics ;
	unsigned long int topicId = 0 ;

	while (fgets(curline, sizeof(curline),ifile)){
		char* command = strtok_r(curline,delims, &curpos);
		if (command && command[0] != '\0' && command[0] != '#') {
			// Client specific mapping
			if (strcmp(command, "clientId") == 0) {
				char* clientId = strtok_r(NULL, delims, &curpos);
				Node *node = NULL;
				node = TreeFind(bs->client_predefined_topics, clientId) ;
				if ( node != NULL) {
					predefined_topics = ((Client_Predefined_Topics*)node->content)->topics ;
				} else {
					predefined_topics = TreeInitialize( topicIdCompare ) ;
					Client_Predefined_Topics *client_predefined = malloc( sizeof(Client_Predefined_Topics) );
					client_predefined->topics = predefined_topics;
					client_predefined->clientId = malloc((strlen(clientId)+1) * sizeof(char));
					strcpy(client_predefined->clientId, clientId);
					TreeAdd( bs->client_predefined_topics , client_predefined , sizeof(Client_Predefined_Topics) ) ;
				}
			} else {
				topicId = strtoul (command, NULL, 10) ;
				if (0 < topicId && topicId <= 65535 ) {
					// Scan to the first non-whitespace char
					while(curpos[0] != '\0' && (curpos[0]==' ' || curpos[0]=='\t' )) {
						curpos++;
					}
					if (strlen(curpos) > 0) {
						// Strip off any end-of-line chars
						topic = strtok(curpos, "\r\n");

						// Strip trailing white space characters
						char *white = topic + strlen(topic) -1 ;
						while ( isspace((int)*white) && topic < white ) {
							*white = '\0';
							--white ;
						}

						// Pre-defined topic must not contain wild characters
						if ( (strchr(topic, '+') != NULL) || (strchr(topic, '#') != NULL) ) {
							rc = -98;
							Log(LOG_WARNING, 401, NULL, topic);
							break;
						}

						Node *node = NULL;
						// If topicId already exists terminate
						if ( (node = TreeFind(predefined_topics, &topicId)) != NULL) {
							rc = -98;
							Log(LOG_WARNING, 402, NULL , topicId , topic , ((Predefined_Topic*)(node->content))->topicName );
							break;
						}

						// Add "ID -> topic" mapping to tree
						Predefined_Topic *map = malloc( sizeof(Predefined_Topic) ) ;
						map->id = topicId ;
						map->topicName = malloc( (strlen(topic)+1) * sizeof(char));
						strcpy(map->topicName, topic);
						TreeAdd(predefined_topics, map, sizeof(Predefined_Topic) + strlen(map->topicName)+1) ;
						// Increase topic id offset if it is smaller than current topicId
						bs->topic_id_offset = bs->topic_id_offset < topicId ? topicId : bs->topic_id_offset ;
					}
				} else {
					rc = -98;
					Log(LOG_WARNING, 400, NULL, line);
					break;
				}
			}
		}
		line++;
	} // while each line in
	FUNC_EXIT_RC(rc);
	return rc;
}
#endif

/**
 * Return a string token, allowing the inclusion of spaces by enclosing with ", and the inclusion of "
 * by doubling "
 * @param str char string as per strtok_r
 * @param delimiter string as per strtok_r
 * @param curpos char pointer as per strtok_r
 * @return pointer to the token string
 */
char* getstring(char* str, char* delims, char** curpos)
{
	char* rc = NULL;
	static char buf[128];

	buf[0] = '\0';
	while (**curpos == ' ') /* skip leading whitespace */
		(*curpos)++;
	if (**curpos == '\"') /* if the first character of the token is ", it must finish with " or the end of the line */
	{
		if (*((*curpos)+1) == '\"') /* if the next character is also ", then we have a 0 length string */
			(*curpos) += 2; /* skip the two "" */
		else
		{
			strcat(buf, strtok_r(str, "\"", curpos));
			while (**curpos == '\"')
			{
				strcat(buf, "\"");
				strcat(buf, strtok_r(str, "\"", curpos));
			}
		}
		rc = buf;
	}
	else
		rc = strtok_r(str, delims, curpos);
	return rc;
}

/**
 * Process a configuration file
 * @param cfile configuration file handle
 * @param bs pointer to the broker state structure
 * @param propsTable property table to use
 * @param props_count size of the property table
 * @return pointer to the default listener, if any
 */
#if !defined(SINGLE_LISTENER)
	Listener*
#else
	void
#endif
Persistence_process_file(FILE* cfile, BrokerStates* bs, property* propsTable, int props_count)
{
	void* s = bs;
	char curline[120], *curpos;
	int line_no = 0;
#if !defined(SINGLE_LISTENER)
	Listener* defaultListener = NULL;
#endif

	FUNC_ENTRY;
	while (fgets(curline, sizeof(curline), cfile))
	{
		char *pword = strtok_r(curline, delims, &curpos);

		line_no++;
		if (pword && pword[0] != '\0' && pword[0] != '#')
		{
			int i = 0;
			int found = 0;
			for (i = 0; i < props_count; ++i)
			{
				if (strcmp(pword, propsTable[i].name) == 0)
				{
					char* val = getstring(NULL, delims, &curpos);
					found = 1;
					if (!val && !(propsTable[i].type == 4 && strcmp(pword, "stop") == 0))
						Log(LOG_WARNING, 1, NULL, pword, line_no);
					else
					{
						if (strcmp(pword, "log_level") == 0)
						{
							if (strcmp(val, "config") == 0)
								trace_settings.log_level = LOG_CONFIG;
							else if (strcmp(val, "detail") == 0)
								trace_settings.log_level = LOG_DETAIL;
							else if (strcmp(val, "info") == 0)
								trace_settings.log_level = LOG_INFO;
							else if (strcmp(val, "audit") == 0)
								trace_settings.log_level = LOG_AUDIT;
							else if (strcmp(val, "warning") == 0)
								trace_settings.log_level = LOG_WARNING;
							else if (strcmp(val, "error") == 0)
								trace_settings.log_level = LOG_ERROR;
							else
								Log(LOG_WARNING, 152, NULL, val, line_no);
						}
						else if (strcmp(pword, "trace_level") == 0)
						{
							if (strcmp(val, "minimum") == 0)
								trace_settings.trace_level = TRACE_MINIMUM;
							else if (strcmp(val, "medium") == 0)
								trace_settings.trace_level = TRACE_MEDIUM;
							else if (strcmp(val, "maximum") == 0)
								trace_settings.trace_level = TRACE_MAXIMUM;
							else
								Log(LOG_WARNING, 152, NULL, val, line_no);
						}
						else if (strcmp(pword, "max_log_entries") == 0)
							trace_settings.max_log_entries = atoi(val);
						else if (strcmp(pword, "max_trace_entries") == 0)
							trace_settings.max_trace_entries = atoi(val);
						else
#if !defined(SINGLE_LISTENER)
						if (propsTable != listenerProps && strcmp(pword, "bind_address") == 0)
						{
							if (defaultListener == NULL)
								defaultListener = Socket_new_listener();
							defaultListener->address = malloc(strlen(val)+1);
							strcpy(defaultListener->address, val);
						}
						else if (propsTable != listenerProps && strcmp(pword, "port") == 0)
						{
							if (defaultListener == NULL)
								defaultListener = Socket_new_listener();
							defaultListener->port = atoi(val);
						}
						else if (propsTable != listenerProps && strcmp(pword, "max_connections") == 0)
						{
							if (defaultListener == NULL)
								defaultListener = Socket_new_listener();
							defaultListener->max_connections = atoi(val);
						}
						else if (propsTable != listenerProps && strcmp(pword, "ipv6") == 0)
						{
							if (defaultListener == NULL)
								defaultListener = Socket_new_listener();
							defaultListener->ipv6 = (strcmp(val, "true") == 0);
						}
						else if (strcmp(pword, "listener") == 0)
						{
							/* listener port [address] [mqtt|mqtts] */
							propsTable = listenerProps;
							props_count = listener_props_count;
							s = Socket_new_listener();
							((Listener*)s)->port = atoi(val);
							if ((val = strtok_r(NULL, delims, &curpos)))
							{
								((Listener*)s)->address = malloc(strlen(val)+1);
								strcpy(((Listener*)s)->address, val);
								if ((val = strtok_r(NULL, delims, &curpos)))
								{
									if (strcmp(val, "mqtt") == 0)
										((Listener*)s)->protocol = PROTOCOL_MQTT;
#if defined(MQTTS)
									else if (strcmp(val, "mqtts") == 0)
										((Listener*)s)->protocol = PROTOCOL_MQTTS;
#endif
									else
										Log(LOG_WARNING, 152, NULL, val, line_no);
								}
							}
							ListAppend(bs->listeners, s, 0);
						}
						else
#endif
#if !defined(NO_BRIDGE)
						if (strcmp(pword, "connection") == 0)
						{
							propsTable = bridgeProps;
							props_count = bridge_props_count;
							s = Bridge_new_connection(&(bs->bridge), val);
							if (s == NULL)
								goto exit;
							if (bs->bridge.connections == NULL)
								bs->bridge.connections = ListInitialize();
							ListAppend(bs->bridge.connections, s, 0);
							Log(LOG_CONFIG, 6, NULL, val, "connections");
						}
						else if (strcmp(pword, "start_type") == 0)
						{
							if (strcmp(val, "automatic") == 0)
								((BridgeConnections*)s)->start_type = START_AUTOMATIC;
							else if (strcmp(val, "manual") == 0)
								((BridgeConnections*)s)->start_type = START_MANUAL;
							else if (strcmp(val, "lazy") == 0)
								((BridgeConnections*)s)->start_type = START_LAZY;
							else if (strcmp(val, "once") == 0)
								((BridgeConnections*)s)->start_type = START_ONCE;
							else
								Log(LOG_WARNING, 152, NULL, val, line_no);
						}
						else if (strcmp(pword, "topic") == 0)
						{
							/* List of topic structures: pattern, direction, localPrefix, remotePrefix, priority */
							int ok = 0;
							BridgeTopics* t = malloc(sizeof(BridgeTopics));
#if defined(MQTTS)
							t->subscribed = 0;
#endif
							t->localPrefix = t->remotePrefix = NULL;
							t->pattern = malloc(strlen(val)+1);
							strcpy(t->pattern, val);
							ok = 1;
							t->direction = 2; /* default - out */
							t->priority = PRIORITY_NORMAL;
							if ((val = getstring(NULL, delims, &curpos)))
							{
								if (strcmp(val, "both") == 0)
									t->direction = 0;
								else if (strcmp(val, "in") == 0)
									t->direction = 1;
								else if (strcmp(val, "out") == 0)
									t->direction = 2;
								else
									Log(LOG_WARNING, 2, NULL, val);
								if ((val = getstring(NULL, delims, &curpos)))
								{
									if (val[0] != '\0')
									{
										t->localPrefix = malloc(strlen(val)+1);
										strcpy(t->localPrefix, val);
									}
									if ((val = getstring(NULL, delims, &curpos)))
									{
										if (val[0] != '\0')
										{
											t->remotePrefix = malloc(strlen(val)+1);
											strcpy(t->remotePrefix, val);
										}
										if ((val = getstring(NULL, delims, &curpos)))
										{
											if (val[0] != '\0')
											{
												if (strcmp(val, "high") == 0)
													t->priority = PRIORITY_HIGH;
												else if (strcmp(val, "low") == 0)
													t->priority = PRIORITY_LOW;
											}
										}
									}
								}
							}
							if (ok)
								ListAppend(((BridgeConnections*)s)->topics, t, sizeof(BridgeTopics));
						}
						else
#if defined(MQTTS)
						if (strcmp(pword, "protocol") == 0)
						{
							if (strcmp(val, "mqtt") == 0)
								((BridgeConnections*)s)->protocol = PROTOCOL_MQTT;
							else if (strcmp(val, "mqtts") == 0)
								((BridgeConnections*)s)->protocol = PROTOCOL_MQTTS;
							else if (strcmp(val, "mqtts_multicast") == 0)
								((BridgeConnections*)s)->protocol = PROTOCOL_MQTTS_MULTICAST;
						}
						else if (strcmp(pword, "advertise") == 0)
						{
							/* advertise address interval gateway_id */
							advertise_parms* adv = malloc(sizeof(advertise_parms));
							memset(adv, '\0', sizeof(advertise_parms));
							adv->address = malloc(strlen(val) + 1);
							strcpy(adv->address, val);
							if ((val = strtok_r(NULL, delims, &curpos)))
							{
								adv->interval = atoi(val);
								if ((val = strtok_r(NULL, delims, &curpos)))
								  adv->gateway_id = atoi(val);
							}
							((Listener*)s)->advertise = adv;
						}
						else
#endif
#endif
						if (propsTable[i].type == PROPERTY_STRING)
						{
							char** loc = (char**)&((char*)s)[propsTable[i].location];
							*loc = malloc(strlen(val)+1);
							strcpy(*loc, val);
							Log(LOG_CONFIG, 5, NULL, pword, val);
						}
						else if (propsTable[i].type == PROPERTY_BOOLEAN)
						{ /* boolean */
							int ival = -1;
							if (strcmp(val, "true") == 0)
								ival = 1;
							else if (strcmp(val, "false") == 0)
								ival = 0;
							else
								Log(LOG_WARNING, 4,  NULL, val, line_no);
							if (ival != -1)
							{
								Log(LOG_CONFIG, 5, NULL, pword, val);
								memcpy(&(((char*)s)[propsTable[i].location]), &ival, sizeof(int));
							}
						}
						else if (propsTable[i].type == PROPERTY_STRING_LIST)
						{
							List** list = (List**)&((char*)s)[propsTable[i].location];
							/* list of strings */
							while (val)
							{
								int len = strlen(val)+1;
								char *loc = malloc(len);
								strcpy(loc, val);
								ListAppend(*list, loc, len);
								Log(LOG_CONFIG, 6, NULL, val, pword);
								//val = strtok_r(NULL, delims, &curpos);
								val = getstring(NULL, delims, &curpos);
							}
						}
#if !defined(NO_ADMIN_COMMANDS)
						else if (propsTable[i].type == PROPERTY_FUNCTION)
						{
							/* call the function pointed to in the table */
							(*functions[propsTable[i].location])(val);
						}
#endif
						else
						{
							int ival = atoi(val);
							Log(LOG_CONFIG, 7, NULL, pword, ival);
							memcpy(&(((char*)s)[propsTable[i].location]), &ival, sizeof(int));
						}
					}
					break;
				} /* if */
			} /* for */
			if (!found)
				Log(LOG_WARNING, 8, NULL, pword, line_no);
		} /* if */
	} /* while */

#if !defined(NO_BRIDGE)
	exit:;
#endif
	FUNC_EXIT;
#if !defined(SINGLE_LISTENER)
	return defaultListener;
#endif
}

/**
 * Read the broker configuration file
 * @param filename name of the configuration file
 * @param bs pointer to the broker state structure
 * @param config_set has a config file been named at startup?
 * @return success indicator - success == 1
 */
int Persistence_read_config(char* filename, BrokerStates* bs, int config_set)
{
	int rc = 0;
	FILE* cfile = NULL;
#if !defined(SINGLE_LISTENER)
	Listener* defaultListener = NULL;
#endif
#if !defined(NO_BRIDGE)
	ListElement* bridgeConnectionElem = NULL;
#endif

	FUNC_ENTRY;
	bs->clientid_prefixes = ListInitialize();
	bstate = bs;
	if ((cfile = fopen(filename, "r")) == NULL)
	{
		if (config_set)
		{
			Log(LOG_WARNING, 0, NULL, filename);
			rc = -98;
		}
	}
	else
	{
#if !defined(SINGLE_LISTENER)
		defaultListener =
#endif
		Persistence_process_file(cfile, bs, brokerProps, broker_props_count);
		fclose(cfile);
#if !defined(SINGLE_LISTENER)
		if (defaultListener != NULL)
			ListAppend(bs->listeners, defaultListener, 0);
#endif
	}
#if !defined(SINGLE_LISTENER)
	if (bs->listeners->count == 0)
	{
		defaultListener = Socket_new_listener();
		ListAppend(bs->listeners, defaultListener, 0);
	}
#endif

	bs->users = ListInitialize();

#if !defined(NO_BRIDGE)
	if (bs->bridge.connections != NULL)
	{
		while (ListNextElement(bs->bridge.connections, &bridgeConnectionElem))
			if (((BridgeConnections*)(bridgeConnectionElem->content))->addresses->count == 0)
			{
				rc = -97;
				Log(LOG_WARNING, 142, NULL, ((BridgeConnections*)(bridgeConnectionElem->content))->name);
				goto exit;
			}
	}
#endif

	if (bs->password_file)
	{
		FILE* ufile = NULL;
		if ((ufile = fopen(bs->password_file,"r")) == NULL)
		{
			Log(LOG_WARNING, 0, NULL, bs->password_file);
			rc = -98;
		}
		else
		{
			rc = Persistence_process_user_file(ufile,bs);
			fclose(ufile);
		}

		if ((rc==0) && bs->acl_file)
		{
			FILE* afile = NULL;
			if ((afile = fopen(bs->acl_file,"r")) == NULL)
			{
				Log(LOG_WARNING, 0, NULL, bs->acl_file);
				rc = -98;
			}
			else
			{
				rc = Persistence_process_acl_file(afile,bs);
				fclose(afile);
			}
		}

	}
	else if (bs->acl_file)
	{
		Log(LOG_WARNING, 25, NULL);
		rc = -98;
	}

#if defined(MQTTS)
	/* Read pre-defined topics file if predefined_topics_file set*/
	if (bs->predefined_topics_file)
	{
		FILE* ifile = NULL;
		if ((ifile = fopen(bs->predefined_topics_file,"r")) == NULL)
		{
			Log(LOG_WARNING, 0, NULL, bs->predefined_topics_file);
			rc = -98;
		}
		else
		{
			rc = Persistence_process_predefined_topics_file(ifile,bs);
			fclose(ifile);
		}
	}
#endif

#if !defined(NO_BRIDGE)
	exit:
#endif
	FUNC_EXIT_RC(rc);
	return rc;
}

/**
 * Free configuration storage
 * @param bs pointer to a broker state structure
 */
void Persistence_free_config(BrokerStates* bs)
{
#if !defined(SINGLE_LISTENER)
	ListElement* current = NULL;
#endif

	FUNC_ENTRY;
	if (bs->persistence_location)
		free(bs->persistence_location);
	if (bs->ffdc_location)
		free(bs->ffdc_location);
	ListFree(bs->clientid_prefixes);

    if (bs->password_file)
    	free(bs->password_file);
    if (bs->acl_file)
    	free(bs->acl_file);

    Users_free_list();

#if !defined(SINGLE_LISTENER)
	while (ListNextElement(bs->listeners, &current))
	{
		Listener* list = (Listener*)(current->content);
		ListFree(list->connections);
		if (list->address)
			free(list->address);
		if (list->mount_point)
			free(list->mount_point);
#if defined(MQTTS)
		ListFree(list->multicast_groups);
		if (list->advertise)
		{
			free(list->advertise->address);
			free(list->advertise);
		}
#endif
	}
	ListFree(bs->listeners);
#else
	if (bs->bind_address)
		free(bs->bind_address);
#endif

#if defined(MQTTS)
	Node* curnode = NULL ;

	// Free broker wide pre-defined topics
	while ( (curnode = TreeNextElement(bs->default_predefined_topics, curnode)) ){
		free ( ((Predefined_Topic*)(curnode->content))->topicName ) ;
	}
	TreeFree(bs->default_predefined_topics);

	curnode = NULL ;
	// Free client specific pre-defined topics
	while ( (curnode = TreeNextElement(bs->client_predefined_topics, curnode)) ){
		Client_Predefined_Topics *client_predefined = (Client_Predefined_Topics*)curnode->content ;

		Node* curnode2 = NULL ;
		while ( (curnode2 = TreeNextElement(client_predefined->topics, curnode2)) ){
			free ( ((Predefined_Topic*)(curnode2->content))->topicName ) ;
		}
		TreeFree(client_predefined->topics);
		free( client_predefined->clientId ) ;
	}
	TreeFree(bs->client_predefined_topics);

	// Free pre-defined topics configuration file name
	if (bs->predefined_topics_file)
		free(bs->predefined_topics_file);
#endif
	FUNC_EXIT;
}

static FILE* rfile = NULL;	/**< Current persistence file handle */
static char *cur_fn, *cur_backup_fn, *cur_backup_fn1;

/**
 * Add the persistence location prefix to a filename
 * @param fn the name of the file to which to add the prefix
 * @return the prefix+filename
 */
char* add_prefix(char* fn)
{
	char* rc = fn;

	FUNC_ENTRY;
	if (bstate->persistence_location)
	{
		rc = malloc(strlen(fn) + strlen(bstate->persistence_location)+1);
		strcpy(rc, bstate->persistence_location);
		strcat(rc, fn);
	}
	FUNC_EXIT;
	return rc;
}

/**
 * Free prefix storage, if it was set
 * @param rc pointer to the (maybe) changed string
 * @param fn pointer to the original filename string
 */
void free_prefix(char* rc, char* fn)
{
	FUNC_ENTRY;
	if (rc != fn)
		free(rc);
	FUNC_EXIT;
}

/**
 * Open a persisted data file
 * @param mode file mode to use
 * @param fn file name
 * @param backup_fn backup file name
 * @param backup_fn1 secondary backup file name
 * @return pointer to the file handle
 */
FILE* Persistence_open_common(char mode, char* fn, char* backup_fn, char* backup_fn1)
{
	char *type = (fn[7] == 'r') ? Messages_get(139, LOG_INFO) : Messages_get(140, LOG_INFO);

	FUNC_ENTRY;
	cur_fn = fn;
	cur_backup_fn = backup_fn;
	cur_backup_fn1 = backup_fn1;
	if (!bstate->persistence)
		rfile = NULL;
	else if (mode == 'w')
	{
		char* loc = add_prefix(fn);
		char* bak = add_prefix(backup_fn);
		char* bak1 = add_prefix(backup_fn1);

		_unlink(bak1);         /* make room for second backup */
		rename(bak, bak1);     /* move backup to second backup */
		rename(loc, bak);      /* move current state file to backup */

		/* open new file */
		if ((rfile = fopen(loc, "wb")) == NULL)
			Log(LOG_WARNING, 9, NULL, type, loc, type);
		free_prefix(loc, fn);
		free_prefix(bak, backup_fn);
		free_prefix(bak1, backup_fn1);
	}
	else if (mode == 'r')
	{
		char* loc = add_prefix(fn);
		if ((rfile = fopen(loc, "rb")) == NULL)
			Log(LOG_WARNING, 10, NULL, type, loc, type);
		else
			Log(LOG_INFO, 11, NULL, type, loc);
		free_prefix(loc, fn);
	}
	FUNC_EXIT;
	return rfile;
}

/**
 * Open the retained message persistence file
 * @param mode file mode to use
 * @return the opened file handle
 */
FILE* Persistence_open_retained(char mode)
{
	return Persistence_open_common(mode, "broker.rms", "broker.1ms", "broker.2ms");
}

/**
 * Open the subscription persistence file
 * @param mode file mode to use
 * @return the opened file handle
 */
FILE* Persistence_open_subscriptions(char mode)
{
	return Persistence_open_common(mode, "broker.sub", "broker.1ub", "broker.2ub");
}

/**
 * Write a retained message to the current persistence file
 * @param payload the message contents
 * @param payloadlen the length of the payload
 * @param qos quality of service
 * @param topicName the name of the topic
 * @return success indicator - success = 0, -1 otherwise
 */
int Persistence_write_retained(char* payload, int payloadlen, int qos, char* topicName)
{
	int rc = 0;

	FUNC_ENTRY;
	if (rfile)
	{
		int topiclen = strlen(topicName);
		if (fwrite(&payloadlen, sizeof(int), 1, rfile) != 1)
			rc = -1;
		if (fwrite(payload, payloadlen, 1, rfile) != 1)
			rc = -1;
		if (fwrite(&qos, sizeof(int), 1, rfile) != 1)
			rc = -1;
		if (fwrite(&topiclen, sizeof(int), 1, rfile) != 1)
			rc = -1;
		if (fwrite(topicName, topiclen, 1, rfile) != 1)
			rc = -1;
	}
	else
		rc = -1;
	FUNC_EXIT_RC(rc);
	return rc;
}

/**
 * Read a retained publication from the current persistence file
 * @return the retained publication read from the file
 */
RetainedPublications* Persistence_read_retained()
{
	RetainedPublications* r = NULL;

	FUNC_ENTRY;
	if (rfile != NULL)
	{
		int topiclen;
		int success = 0;
		r = malloc(sizeof(RetainedPublications));

		if (fread(&(r->payloadlen), sizeof(int), 1, rfile) == 1)
		{
			r->payload = malloc(r->payloadlen);
			if (fread(r->payload, r->payloadlen, 1, rfile) == 1 &&
				fread(&(r->qos), sizeof(int), 1, rfile) == 1 &&
				fread(&topiclen, sizeof(int), 1, rfile) == 1)
			{
				r->topicName = malloc(topiclen + 1);
				if (fread(r->topicName, topiclen, 1, rfile) == 1)
				{
					r->topicName[topiclen] = '\0';
					success = 1;
				}
				else
				{
					free(r->topicName);
					free(r->payload);
				}
			}
			else
				free(r->payload);
		}
		if (!success)
		{
			free(r);
			r = NULL;
		}
	}
	FUNC_EXIT;
	return r;
}

/**
 * Write a subscription to the current persistence file
 * @param s pointer to the subcription information
 * @return success indicator - success = 0, -1 otherwise
 */
int Persistence_write_subscription(Subscriptions* s)
{
	int rc = 0;

	FUNC_ENTRY;
	if (rfile)
	{
		int len = strlen(s->clientName);

		if (fwrite(&len, sizeof(int), 1, rfile) != 1)
			rc = -1;
		if (fwrite(s->clientName, len, 1, rfile) != 1)
			rc = -1;
		if (fwrite(&(s->noLocal), sizeof(int), 1, rfile) != 1)
			rc = -1;
		if (fwrite(&(s->qos), sizeof(int), 1, rfile) != 1)
			rc = -1;
		len = strlen(s->topicName);
		if (fwrite(&len, sizeof(int), 1, rfile) != 1)
			rc = -1;
		if (fwrite(s->topicName, len, 1, rfile) != 1)
			rc = -1;
	}
	else
		rc = -1;
	FUNC_EXIT_RC(rc);
	return rc;
}

/**
 * Create a default client structure with suitably allocated storage
 * @param clientID the client id string to use
 * @return pointer to the allocated client structure
 */
Clients* Persistence_createDefaultClient(char* clientID)
{
	Clients* newc = malloc(sizeof(Clients));
	int i;

	FUNC_ENTRY;
	memset(newc, '\0', sizeof(Clients));
	newc->clientID = clientID;
	newc->outboundMsgs = ListInitialize();
	newc->inboundMsgs = ListInitialize();
	for (i = 0; i < PRIORITY_MAX; ++i)
		newc->queuedMsgs[i] = ListInitialize();
	FUNC_EXIT;
	return newc;
}

/**
 * Read a subscription entry from the current persistence file
 * @return pointer to the subscription structure read, or NULL if there was an error
 */
Subscriptions* Persistence_read_subscription()
{
	Subscriptions* s = NULL;

	FUNC_ENTRY;
	if (rfile != NULL)
	{
		int len;
		int success = 0;
		s = malloc(sizeof(Subscriptions));
		memset(s, '\0', sizeof(Subscriptions));

		if (fread(&(len), sizeof(int), 1, rfile) == 1)
		{
			/* s->was_persisted = 1; */
			s->clientName = malloc(len+1);
			s->clientName[len] = '\0';

			if (fread(s->clientName, len, 1, rfile) == 1 &&
				fread(&(s->noLocal), sizeof(int), 1, rfile) == 1 &&
				fread(&(s->qos), sizeof(int), 1, rfile) == 1 &&
				fread(&len, sizeof(int), 1, rfile) == 1)
			{
				s->topicName = malloc(len + 1);
				if (fread(s->topicName, len, 1, rfile) == 1)
				{
					Node* elem = NULL;
					s->topicName[len] = '\0';
					s->durable = 1;
					s->wildcards = Topics_hasWildcards(s->topicName);
					s->priority = PRIORITY_NORMAL;
					success = 1;

					if ((elem = TreeFind(bstate->disconnected_clients, s->clientName)) == NULL)
					{
						/*printf("adding sub for client %s\n", s->clientName);*/
						TreeAdd(bstate->disconnected_clients, Persistence_createDefaultClient(s->clientName),
							sizeof(Clients) + strlen(s->clientName)+1 + 3*sizeof(List));
					}
					else
					{
						free(s->clientName);
						s->clientName = ((Clients*)(elem->content))->clientID;
					}
				}
				else
				{
					free(s->topicName);
					free(s->clientName);
				}
			}
			else
				free(s->clientName);
		}
		if (!success)
		{
			free(s);
			s = NULL;
		}
	}
	FUNC_EXIT;
	return s;
}

/**
 * Close the current persistence file.
 */
void Persistence_close_file(int write_error)
{
	if (rfile)
	{
		char* bak1 = add_prefix(cur_backup_fn1);

		int rc = fclose(rfile);

		if (write_error != 0 || rc != 0)
		{
			char* loc = add_prefix(cur_fn);
			char* bak = add_prefix(cur_backup_fn);

			_unlink(loc); /* remove the erroneously written persistence file */
			rename(bak, loc); /* restore the backup */
			rename(bak1, bak); /* restore the 2nd backup to backup */

			free_prefix(loc, cur_fn);
			free_prefix(bak, cur_backup_fn);
		}
		else
			_unlink(bak1);         /* remove the second backup */

		free_prefix(bak1, cur_backup_fn1);
	}
}

#if !defined(NO_ADMIN_COMMANDS)
int xxx_create_segfault(char* dest)
{
	int* ptr = (int*)0xFFFFFFFF;
	*ptr = 2;
	return 0;
}

int clear_retained(char* dest)
{
	SubscriptionEngines_clearRetained(bstate->se, dest);
	return 0;
}

int take_FFDC(char* symptoms)
{
	#define SYMPTOM_BUFFER_SIZE 256
	char symptom_buffer[SYMPTOM_BUFFER_SIZE];
	snprintf(symptom_buffer, SYMPTOM_BUFFER_SIZE, "Requested by command. %s", symptoms);
	symptom_buffer[SYMPTOM_BUFFER_SIZE - 1] = '\0';
	Broker_recordFFDC(symptom_buffer);
	return 0;
}

/**
 * function table of command implementations
 */
int (*functions[])(char*) =
{
	Broker_stop,
	Log_traceOutput,
	Log_dumpTrace,
	Broker_dumpHeap,
	take_FFDC,
	xxx_create_segfault,
	clear_retained,
#if !defined(NO_BRIDGE)
	Bridge_startConnection,
	Bridge_stopConnection,
	Bridge_deleteConnection,
#endif
};

/**
 * Property table for admin commands
 */
property commandProps[] =
{
	{ "stop", 4, 0 },
	{ "log_level", 0, offsetof(trace_settings_type, log_level) },
	{ "trace_level", 0, offsetof(trace_settings_type, trace_level) },
	{ "trace_output", 4, 1 },
	{ "trace_dump", 4, 2 },
	{ "heap_dump", 4, 3 },
	{ "take_ffdc", 4, 4 },
	{ "xxx_create_segfault", 4, 5 },
	{ "max_log_entries", 0, offsetof(trace_settings_type, max_log_entries) },
	{ "max_trace_entries", 0, offsetof(trace_settings_type, max_trace_entries) },
	{ "clear_retained", 4, 6 },
#if !defined(NO_BRIDGE)
	{ "start_connection", 4, 7 },
	{ "stop_connection", 4, 8 },
	{ "delete_connection", 4, 9 },
	{ "connection", 1, offsetof(BridgeConnections, name) },
#endif

};
/**
 * size of the admin commands property array
 */
#define command_props_count ARRAY_SIZE(commandProps)

/**
 * Read a command from the named update file and run it.
 * @param filename - the name of the file to read the admin command from
 * @param bs pointer to the broker state structure
 * @return boolean success indicator, success=1
 */
int Persistence_read_admin(char* filename, BrokerStates* bs)
{
	int success = 0;
	FILE* cfile = NULL;

	FUNC_ENTRY;
	if ((cfile = fopen(filename, "r")) != NULL)
	{
		Persistence_process_file(cfile, bs, commandProps, command_props_count);
		fclose(cfile);
		success = 1;
	}
	FUNC_EXIT_RC(success);
	return success;
}

/**
 * Read a command from the update file and run it.
 * @param bs pointer to the broker state structure
 */
void Persistence_read_command(BrokerStates* bs)
{
	char* fn = "broker.upd";
	char* cmd_file = add_prefix(fn);
	struct stat buf;

	FUNC_ENTRY;
	if (stat(cmd_file, &buf) != -1)
	{
		int saved = trace_settings.log_level;

		Log(LOG_INFO, 68, NULL, cmd_file);
		trace_settings.log_level = LOG_CONFIG;
		if (Persistence_read_admin(cmd_file, bs))
			_unlink(cmd_file);
		trace_settings.log_level = saved;
	}
	free_prefix(cmd_file, fn);
	FUNC_EXIT;
}

#endif


text:
extern crate std;
fn main() {}
//~^^ ERROR the name `std` is defined multiple times [E0259]


text:
<?php

namespace Magento\Shipping\Test\Block\Adminhtml\Form\Items;

/**
 * Item product form on shipment items block.
 */
class Product extends \Magento\Sales\Test\Block\Adminhtml\Order\AbstractForm\Product
{
    //
}


text:
package eu.hyvar.context.contextValidity.resource.hyvalidityformula.analysis;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;

import eu.hyvar.dataValues.HyEnum;
import eu.hyvar.feature.expression.resource.hyexpression.IHyexpressionQuickFix;
import eu.hyvar.feature.expression.resource.hyexpression.IHyexpressionReferenceMapping;

public class HyEnumValueEnumReferenceResolver implements eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaReferenceResolver<eu.hyvar.dataValues.HyEnumValue, eu.hyvar.dataValues.HyEnum> {

	private eu.hyvar.feature.expression.resource.hyexpression.analysis.HyEnumValueEnumReferenceResolver delegate = new eu.hyvar.feature.expression.resource.hyexpression.analysis.HyEnumValueEnumReferenceResolver();

	public void resolve(String identifier, eu.hyvar.dataValues.HyEnumValue container, EReference reference, int position, boolean resolveFuzzy, final eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaReferenceResolveResult<eu.hyvar.dataValues.HyEnum> result) {

		if((identifier!=null)&&(identifier.contains(eu.hyvar.mspl.manifest.util.custom.HyManifestResolverUtil.MANIFEST_SEPARATOR))) {
			HyEnum found = eu.hyvar.mspl.manifest.util.custom.HyManifestResolverUtil.resolveMsplEnum(identifier, container);
			if (found!=null) {
				result.addMapping(identifier, found);
			}
		}
		else {
			delegate.resolve(identifier, container, reference, position, resolveFuzzy, new eu.hyvar.feature.expression.resource.hyexpression.IHyexpressionReferenceResolveResult<eu.hyvar.dataValues.HyEnum>() {

				public boolean wasResolvedUniquely() {
					return result.wasResolvedUniquely();
				}

				public boolean wasResolvedMultiple() {
					return result.wasResolvedMultiple();
				}

				public boolean wasResolved() {
					return result.wasResolved();
				}

				public void setErrorMessage(String message) {
					result.setErrorMessage(message);
				}

				public String getErrorMessage() {
					return result.getErrorMessage();
				}

				public void addMapping(String identifier, URI newIdentifier) {
					result.addMapping(identifier, newIdentifier);
				}

				public void addMapping(String identifier, URI newIdentifier, String warning) {
					result.addMapping(identifier, newIdentifier, warning);
				}

				public void addMapping(String identifier, eu.hyvar.dataValues.HyEnum target) {
					result.addMapping(identifier, target);
				}

				public void addMapping(String identifier, eu.hyvar.dataValues.HyEnum target, String warning) {
					result.addMapping(identifier, target, warning);
				}

				@Override
				public void addQuickFix(final IHyexpressionQuickFix quickFix) {
					result.addQuickFix(new eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaQuickFix() {

						public String getImageKey() {
							return quickFix.getImageKey();
						}

						public String getDisplayString() {
							return quickFix.getDisplayString();
						}

						public Collection<EObject> getContextObjects() {
							return quickFix.getContextObjects();
						}

						public String getContextAsString() {
							return quickFix.getContextAsString();
						}

						public String apply(String currentText) {
							return quickFix.apply(currentText);
						}
					});

				}

				@Override
				public Collection<IHyexpressionQuickFix> getQuickFixes() {
					return Collections.emptySet();
				}

				@Override
				public Collection<IHyexpressionReferenceMapping<HyEnum>> getMappings() {
					throw new UnsupportedOperationException();
				}
			});

		}

	}

	public String deResolve(eu.hyvar.dataValues.HyEnum element, eu.hyvar.dataValues.HyEnumValue container, EReference reference) {
		return delegate.deResolve(element, container, reference);
	}

	public void setOptions(Map<?,?> options) {
		// save options in a field or leave method empty if this resolver does not depend
		// on any option
	}

}


text:
package com.google.cloud.channel.v1.samples;

// [START cloudchannel_v1_generated_CloudChannelService_SuspendEntitlement_sync]
import com.google.cloud.channel.v1.CloudChannelServiceClient;
import com.google.cloud.channel.v1.Entitlement;
import com.google.cloud.channel.v1.SuspendEntitlementRequest;

public class SyncSuspendEntitlement {

  public static void main(String[] args) throws Exception {
    syncSuspendEntitlement();
  }

  public static void syncSuspendEntitlement() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudChannelServiceClient cloudChannelServiceClient = CloudChannelServiceClient.create()) {
      SuspendEntitlementRequest request =
          SuspendEntitlementRequest.newBuilder()
              .setName("name3373707")
              .setRequestId("requestId693933066")
              .build();
      Entitlement response = cloudChannelServiceClient.suspendEntitlementAsync(request).get();
    }
  }
}
// [END cloudchannel_v1_generated_CloudChannelService_SuspendEntitlement_sync]


text:
'use strict';

var i18n = require('i18n');

module.exports = function () {
  arguments[0] = i18n.__(arguments[0]);
  return this.warn.apply(this, arguments);
};


text:
<?php declare(strict_types = 1);

namespace Cryptopals\Set4\Challenge30;

use Cryptopals\Solution;

class Solution30 implements Solution
{
    protected $messageAPI;
    protected $md4;

    function __construct(MessageAPI $messageAPI, MD4 $md4)
    {
        $this->messageAPI = $messageAPI;
        $this->md4 = $md4;
    }

    protected function getGlue(string $message, int $offset = 0): string
    {
        $messageLen = strlen($message) + $offset;
        $padLen = 64 - ($messageLen % 64);

        if ($padLen < 9) {
            $padLen += 64;
        }

        $messageLen <<= 3;

        return "\x80" . str_repeat("\0", $padLen - 9) . pack('C4', $messageLen, $messageLen >> 8, $messageLen >> 16, $messageLen >> 24) . "\0\0\0\0";
    }

    function execute(): bool
    {
        $message = 'comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon';
        $mac = $this->messageAPI->sign($message);

        // attacker has access to message and mac, but not key

        print "Message: $message\n";
        print "Old MAC: " . bin2hex($mac) . "\n\n";

        $ctx = new MD4Context();
        $digest = array_values(unpack('V4', $mac));
        $messageLen = strlen($message);
        $suffix = ';admin=true';

        $keyLen = 0;
        while ($keyLen < 33) {
            $glue = $this->getGlue($message, $keyLen);

            $this->md4->init($ctx);
            list($ctx->a, $ctx->b, $ctx->c, $ctx->d) = $digest;
            $ctx->lo = ($messageLen + $keyLen + strlen($glue));

            $this->md4->update($ctx, $suffix);
            $newMac = $this->md4->result($ctx);
            if ($this->messageAPI->verify($message . $glue . $suffix, $newMac)) {
                print "Key len: $keyLen\n\n";
                print "Message: $message$glue$suffix\n";
                print "New MAC: " . bin2hex($newMac) . "\n\n";
                return true;
            }

            $keyLen ++;
        }

        return false;
    }
}


text:
export default function getValueKey({ normalized, cumulative }) {
  if (normalized && cumulative) return 'cumulativeDensity';
  if (cumulative) return 'cumulative';
  if (normalized) return 'density';

  return 'count';
}


text:
package sdhook

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/facebookgo/stack"
	"github.com/fluent/fluent-logger-golang/fluent"

	errorReporting "google.golang.org/api/clouderrorreporting/v1beta1"
	logging "google.golang.org/api/logging/v2beta1"
)

const (
	// DefaultName is the default name passed to LogName when using service
	// account credentials.
	DefaultName = "default"
)

// StackdriverHook provides a logrus hook to Google Stackdriver logging.
type StackdriverHook struct {
	// levels are the levels that logrus will hook to.
	levels []logrus.Level

	// projectID is the projectID
	projectID string

	// service is the logging service.
	service *logging.EntriesService

	// service is the error reporting service.
	errorService *errorReporting.Service

	// resource is the monitored resource.
	resource *logging.MonitoredResource

	// logName is the name of the log.
	logName string

	// labels are the labels to send with each log entry.
	labels map[string]string

	// partialSuccess allows partial writes of log entries if there is a badly
	// formatted log.
	partialSuccess bool

	// agentClient defines the fluentd logger object that can send data to
	// to the Google logging agent.
	agentClient *fluent.Fluent

	// errorReportingServiceName defines the value of the field <service>,
	// required for a valid error reporting payload. If this value is set,
	// messages where level/severity is higher than or equal to "error" will
	// be sent to Stackdriver error reporting.
	// See more at:
	// https://cloud.google.com/error-reporting/docs/formatting-error-messages
	errorReportingServiceName string

	// errorReportingLogName is the name of the log for error reporting.
	// It must contain the string "error"
	// If not given, the string "<logName>_error" is used.
	errorReportingLogName string
}

// New creates a StackdriverHook using the provided options that is suitible
// for using with logrus for logging to Google Stackdriver.
func New(opts ...Option) (*StackdriverHook, error) {
	var err error

	sh := &StackdriverHook{
		levels: logrus.AllLevels,
	}

	// apply opts
	for _, o := range opts {
		err = o(sh)
		if err != nil {
			return nil, err
		}
	}

	// check service, resource, logName set
	if sh.service == nil && sh.agentClient == nil {
		return nil, errors.New("no stackdriver service was provided")
	}
	if sh.resource == nil && sh.agentClient == nil {
		return nil, errors.New("the monitored resource was not provided")
	}
	if sh.projectID == "" && sh.agentClient == nil {
		return nil, errors.New("the project id was not provided")
	}

	// set default project name
	if sh.logName == "" {
		err = LogName(DefaultName)(sh)
		if err != nil {
			return nil, err
		}
	}

	// If error reporting log name not set, set it to log name
	// plus string suffix
	if sh.errorReportingLogName == "" {
		sh.errorReportingLogName = sh.logName + "_errors"
	}

	return sh, nil
}

func isError(entry *logrus.Entry) bool {
	if entry != nil {
		switch entry.Level {
		case logrus.ErrorLevel:
			return true
		case logrus.FatalLevel:
			return true
		case logrus.PanicLevel:
			return true
		}
	}
	return false
}

// Levels returns the logrus levels that this hook is applied to. This can be
// set using the Levels Option.
func (sh *StackdriverHook) Levels() []logrus.Level {
	return sh.levels
}

// Fire writes the message to the Stackdriver entry service.
func (sh *StackdriverHook) Fire(entry *logrus.Entry) error {
	go func() {
		var httpReq *logging.HttpRequest

		// convert entry data to labels
		labels := make(map[string]string, len(entry.Data))
		for k, v := range entry.Data {
			switch x := v.(type) {
			case string:
				labels[k] = x

			case *http.Request:
				httpReq = &logging.HttpRequest{
					Referer:       x.Referer(),
					RemoteIp:      x.RemoteAddr,
					RequestMethod: x.Method,
					RequestUrl:    x.URL.String(),
					UserAgent:     x.UserAgent(),
				}

			case *logging.HttpRequest:
				httpReq = x

			default:
				labels[k] = fmt.Sprintf("%v", v)
			}
		}

		// write log entry
		if sh.agentClient != nil {
			sh.sendLogMessageViaAgent(entry, labels, httpReq)
		} else {
			sh.sendLogMessageViaAPI(entry, labels, httpReq)
		}
	}()

	return nil
}

func (sh *StackdriverHook) sendLogMessageViaAgent(entry *logrus.Entry, labels map[string]string, httpReq *logging.HttpRequest) {
	// The log entry payload schema is defined by the Google fluentd
	// logging agent. See more at:
	// https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud
	logEntry := map[string]interface{}{
		"severity":         strings.ToUpper(entry.Level.String()),
		"timestampSeconds": strconv.FormatInt(entry.Time.Unix(), 10),
		"timestampNanos":   strconv.FormatInt(entry.Time.UnixNano()-entry.Time.Unix()*1000000000, 10),
		"message":          entry.Message,
	}
	for k, v := range labels {
		logEntry[k] = v
	}
	if httpReq != nil {
		logEntry["httpRequest"] = httpReq
	}
	// The error reporting payload JSON schema is defined in:
	// https://cloud.google.com/error-reporting/docs/formatting-error-messages
	// Which reflects the structure of the ErrorEvent type in:
	// https://godoc.org/google.golang.org/api/clouderrorreporting/v1beta1
	if sh.errorReportingServiceName != "" && isError(entry) {
		errorEvent := sh.buildErrorReportingEvent(entry, labels, httpReq)
		errorStructPayload, err := json.Marshal(errorEvent)
		if err != nil {
			log.Printf("error marshaling error reporting data: %s", err.Error())
		}
		var errorJSONPayload map[string]interface{}
		err = json.Unmarshal(errorStructPayload, &errorJSONPayload)
		if err != nil {
			log.Printf("error parsing error reporting data: %s", err.Error())
		}
		for k, v := range logEntry {
			errorJSONPayload[k] = v
		}
		if err := sh.agentClient.Post(sh.errorReportingLogName, errorJSONPayload); err != nil {
			log.Printf("error posting error reporting entries to logging agent: %s", err.Error())
		}
	} else {
		if err := sh.agentClient.Post(sh.logName, logEntry); err != nil {
			log.Printf("error posting log entries to logging agent: %s", err.Error())
		}
	}
}

func (sh *StackdriverHook) sendLogMessageViaAPI(entry *logrus.Entry, labels map[string]string, httpReq *logging.HttpRequest) {
	if sh.errorReportingServiceName != "" && isError(entry) {
		errorEvent := sh.buildErrorReportingEvent(entry, labels, httpReq)
		sh.errorService.Projects.Events.Report(sh.projectID, &errorEvent)
	} else {
		logName := sh.logName
		if sh.errorReportingLogName != "" && isError(entry) {
			logName = sh.errorReportingLogName
		}
		_, _ = sh.service.Write(&logging.WriteLogEntriesRequest{
			LogName:        logName,
			Resource:       sh.resource,
			Labels:         sh.labels,
			PartialSuccess: sh.partialSuccess,
			Entries: []*logging.LogEntry{
				&logging.LogEntry{
					Severity:    strings.ToUpper(entry.Level.String()),
					Timestamp:   entry.Time.Format(time.RFC3339),
					TextPayload: entry.Message,
					Labels:      labels,
					HttpRequest: httpReq,
				},
			},
		}).Do()
	}
}

func (sh *StackdriverHook) buildErrorReportingEvent(entry *logrus.Entry, labels map[string]string, httpReq *logging.HttpRequest) errorReporting.ReportedErrorEvent {
	errorEvent := errorReporting.ReportedErrorEvent{
		EventTime: entry.Time.Format(time.RFC3339),
		Message:   entry.Message,
		ServiceContext: &errorReporting.ServiceContext{
			Service: sh.errorReportingServiceName,
			Version: labels["version"],
		},
		Context: &errorReporting.ErrorContext{
			User: labels["user"],
		},
	}
	// Assumes that caller stack frame information of type
	// github.com/facebookgo/stack.Frame has been added.
	// Possibly via a library like github.com/Gurpartap/logrus-stack
	if entry.Data["caller"] != nil {
		caller := entry.Data["caller"].(stack.Frame)
		errorEvent.Context.ReportLocation = &errorReporting.SourceLocation{
			FilePath:     caller.File,
			FunctionName: caller.Name,
			LineNumber:   int64(caller.Line),
		}
	}
	if httpReq != nil {
		errRepHttpRequest := &errorReporting.HttpRequestContext{
			Method:    httpReq.RequestMethod,
			Referrer:  httpReq.Referer,
			RemoteIp:  httpReq.RemoteIp,
			Url:       httpReq.RequestUrl,
			UserAgent: httpReq.UserAgent,
		}
		errorEvent.Context.HttpRequest = errRepHttpRequest
	}
	return errorEvent
}


text:
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"

#include "av1/encoder/encoder.h"

#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"

namespace {

using ::testing::make_tuple;
using ::testing::tuple;

/* TESTING PARAMETERS */

#define NUM_TEST_VIDEOS 3

const int kBitrate = 40;

// PSNR thresholds found by experiment
const double kPSNRThresholds[] = { 26.0, 28.0, 20.0 };

typedef struct {
  const char *filename;
  aom_img_fmt fmt;
  aom_bit_depth_t bit_depth;
  unsigned int profile;
  unsigned int limit;
  unsigned int screen_content;
} TestVideoParam;

const TestVideoParam kTestVideoVectors[] = {
  { "park_joy_90p_8_420.y4m", AOM_IMG_FMT_I420, AOM_BITS_8, 0, 5, 0 },
  { "park_joy_90p_10_444.y4m", AOM_IMG_FMT_I44416, AOM_BITS_10, 1, 5, 0 },
  { "screendata.y4m", AOM_IMG_FMT_I420, AOM_BITS_8, 0, 4, 1 },
};

// Superres modes tested
// SUPERRES_QTHRESH is not included, as it has its own test
const SUPERRES_MODE kSuperresModesNotQThresh[] = { SUPERRES_FIXED,
                                                   SUPERRES_RANDOM };

// Superres denominators and superres kf denominators to be tested
typedef tuple<int, int> SuperresDenominatorPair;
const SuperresDenominatorPair kSuperresDenominators[] = {
  make_tuple(16, 9),  make_tuple(13, 11), make_tuple(9, 9),
  make_tuple(13, 13), make_tuple(11, 16), make_tuple(8, 16),
  make_tuple(16, 8),  make_tuple(8, 8),   make_tuple(9, 14),
};

// Superres q thresholds and superres kf q thresholds to be tested
typedef tuple<int, int> SuperresQThresholdPair;
const SuperresQThresholdPair kSuperresQThresholds[] = {
  make_tuple(63, 63), make_tuple(63, 41), make_tuple(17, 63),
  make_tuple(41, 11), make_tuple(1, 37),  make_tuple(11, 11),
  make_tuple(1, 1),   make_tuple(17, 29), make_tuple(29, 11),
};

/* END (TESTING PARAMETERS) */

// Test parameter list:
//  <[needed for EncoderTest], test_video_idx_, superres_mode_,
//  tuple(superres_denom_, superres_kf_denom_)>
typedef tuple<const libaom_test::CodecFactory *, int, SUPERRES_MODE,
              SuperresDenominatorPair>
    HorzSuperresTestParam;

class HorzSuperresEndToEndTest
    : public ::testing::TestWithParam<HorzSuperresTestParam>,
      public ::libaom_test::EncoderTest {
 protected:
  HorzSuperresEndToEndTest()
      : EncoderTest(GET_PARAM(0)), test_video_idx_(GET_PARAM(1)),
        superres_mode_(GET_PARAM(2)), psnr_(0.0), frame_count_(0) {
    test_video_param_ = kTestVideoVectors[test_video_idx_];

    SuperresDenominatorPair denoms = GET_PARAM(3);
    superres_denom_ = ::testing::get<0>(denoms);
    superres_kf_denom_ = ::testing::get<1>(denoms);
  }

  virtual ~HorzSuperresEndToEndTest() {}

  virtual void SetUp() {
    InitializeConfig();
    SetMode(::libaom_test::kTwoPassGood);
    cfg_.g_lag_in_frames = 5;
    cfg_.rc_end_usage = AOM_VBR;
    cfg_.rc_target_bitrate = kBitrate;
    cfg_.g_error_resilient = 0;
    cfg_.g_profile = test_video_param_.profile;
    cfg_.g_input_bit_depth = (unsigned int)test_video_param_.bit_depth;
    cfg_.g_bit_depth = test_video_param_.bit_depth;
    init_flags_ = AOM_CODEC_USE_PSNR;
    if (cfg_.g_bit_depth > 8) init_flags_ |= AOM_CODEC_USE_HIGHBITDEPTH;

    // Set superres parameters
    cfg_.rc_superres_mode = superres_mode_;
    cfg_.rc_superres_denominator = superres_denom_;
    cfg_.rc_superres_kf_denominator = superres_kf_denom_;
  }

  virtual void BeginPassHook(unsigned int) {
    psnr_ = 0.0;
    frame_count_ = 0;
  }

  virtual void PSNRPktHook(const aom_codec_cx_pkt_t *pkt) {
    psnr_ += pkt->data.psnr.psnr[0];
    frame_count_++;
  }

  virtual void PreEncodeFrameHook(::libaom_test::VideoSource *video,
                                  ::libaom_test::Encoder *encoder) {
    if (video->frame() == 1) {
      encoder->Control(AV1E_SET_FRAME_PARALLEL_DECODING, 1);
      encoder->Control(AV1E_SET_TILE_COLUMNS, 4);

      // Set cpu-used = 8 for speed
      encoder->Control(AOME_SET_CPUUSED, 8);

      // Test screen coding tools
      if (test_video_param_.screen_content)
        encoder->Control(AV1E_SET_TUNE_CONTENT, AOM_CONTENT_SCREEN);
      else
        encoder->Control(AV1E_SET_TUNE_CONTENT, AOM_CONTENT_DEFAULT);

      encoder->Control(AOME_SET_ENABLEAUTOALTREF, 1);
      encoder->Control(AOME_SET_ARNR_MAXFRAMES, 7);
      encoder->Control(AOME_SET_ARNR_STRENGTH, 5);
    }
  }

  double GetAveragePsnr() const {
    if (frame_count_) return psnr_ / frame_count_;
    return 0.0;
  }

  double GetPsnrThreshold() { return kPSNRThresholds[test_video_idx_]; }

  void DoTest() {
    testing::internal::scoped_ptr<libaom_test::VideoSource> video;
    video.reset(new libaom_test::Y4mVideoSource(test_video_param_.filename, 0,
                                                test_video_param_.limit));
    ASSERT_TRUE(video.get() != NULL);

    ASSERT_NO_FATAL_FAILURE(RunLoop(video.get()));
    const double psnr = GetAveragePsnr();
    EXPECT_GT(psnr, GetPsnrThreshold())
        << "superres_mode_ = " << superres_mode_
        << ", superres_denom_ = " << superres_denom_
        << ", superres_kf_denom_ = " << superres_kf_denom_;

    EXPECT_EQ(test_video_param_.limit, frame_count_)
        << "superres_mode_ = " << superres_mode_
        << ", superres_denom_ = " << superres_denom_
        << ", superres_kf_denom_ = " << superres_kf_denom_;
  }

  int test_video_idx_;
  TestVideoParam test_video_param_;
  SUPERRES_MODE superres_mode_;
  int superres_denom_;
  int superres_kf_denom_;

 private:
  double psnr_;
  unsigned int frame_count_;
};

TEST_P(HorzSuperresEndToEndTest, HorzSuperresEndToEndPSNRTest) { DoTest(); }

AV1_INSTANTIATE_TEST_CASE(HorzSuperresEndToEndTest,
                          ::testing::Range(0, NUM_TEST_VIDEOS),
                          ::testing::ValuesIn(kSuperresModesNotQThresh),
                          ::testing::ValuesIn(kSuperresDenominators));

// Test parameter list:
//  <[needed for EncoderTest], test_video_idx_, tuple(superres_denom_,
//  superres_kf_denom_), tuple(superres_qthresh_,superres_kf_qthresh_)>
typedef tuple<const libaom_test::CodecFactory *, int, SuperresDenominatorPair,
              SuperresQThresholdPair>
    HorzSuperresQThreshTestParam;

class HorzSuperresQThreshEndToEndTest
    : public ::testing::TestWithParam<HorzSuperresQThreshTestParam>,
      public ::libaom_test::EncoderTest {
 protected:
  HorzSuperresQThreshEndToEndTest()
      : EncoderTest(GET_PARAM(0)), test_video_idx_(GET_PARAM(1)),
        superres_mode_(SUPERRES_QTHRESH), psnr_(0.0), frame_count_(0) {
    test_video_param_ = kTestVideoVectors[test_video_idx_];

    SuperresDenominatorPair denoms = GET_PARAM(2);
    superres_denom_ = ::testing::get<0>(denoms);
    superres_kf_denom_ = ::testing::get<1>(denoms);

    SuperresQThresholdPair qthresholds = GET_PARAM(3);
    superres_qthresh_ = ::testing::get<0>(qthresholds);
    superres_kf_qthresh_ = ::testing::get<1>(qthresholds);
  }

  virtual ~HorzSuperresQThreshEndToEndTest() {}

  virtual void SetUp() {
    InitializeConfig();
    SetMode(::libaom_test::kTwoPassGood);
    cfg_.g_lag_in_frames = 5;
    cfg_.rc_end_usage = AOM_VBR;
    cfg_.rc_target_bitrate = kBitrate;
    cfg_.g_error_resilient = 0;
    cfg_.g_profile = test_video_param_.profile;
    cfg_.g_input_bit_depth = (unsigned int)test_video_param_.bit_depth;
    cfg_.g_bit_depth = test_video_param_.bit_depth;
    init_flags_ = AOM_CODEC_USE_PSNR;
    if (cfg_.g_bit_depth > 8) init_flags_ |= AOM_CODEC_USE_HIGHBITDEPTH;

    // Set superres parameters
    cfg_.rc_superres_mode = superres_mode_;
    cfg_.rc_superres_denominator = superres_denom_;
    cfg_.rc_superres_kf_denominator = superres_kf_denom_;
    cfg_.rc_superres_qthresh = superres_qthresh_;
    cfg_.rc_superres_kf_qthresh = superres_kf_qthresh_;
  }

  virtual void BeginPassHook(unsigned int) {
    psnr_ = 0.0;
    frame_count_ = 0;
  }

  virtual void PSNRPktHook(const aom_codec_cx_pkt_t *pkt) {
    psnr_ += pkt->data.psnr.psnr[0];
    frame_count_++;
  }

  virtual void PreEncodeFrameHook(::libaom_test::VideoSource *video,
                                  ::libaom_test::Encoder *encoder) {
    if (video->frame() == 1) {
      encoder->Control(AV1E_SET_FRAME_PARALLEL_DECODING, 1);
      encoder->Control(AV1E_SET_TILE_COLUMNS, 0);

      // Set cpu-used = 8 for speed
      encoder->Control(AOME_SET_CPUUSED, 8);

      // Test screen coding tools
      if (test_video_param_.screen_content)
        encoder->Control(AV1E_SET_TUNE_CONTENT, AOM_CONTENT_SCREEN);
      else
        encoder->Control(AV1E_SET_TUNE_CONTENT, AOM_CONTENT_DEFAULT);

      encoder->Control(AOME_SET_ENABLEAUTOALTREF, 1);
      encoder->Control(AOME_SET_ARNR_MAXFRAMES, 7);
      encoder->Control(AOME_SET_ARNR_STRENGTH, 5);
    }
  }

  double GetAveragePsnr() const {
    if (frame_count_) return psnr_ / frame_count_;
    return 0.0;
  }

  double GetPsnrThreshold() { return kPSNRThresholds[test_video_idx_]; }

  void DoTest() {
    testing::internal::scoped_ptr<libaom_test::VideoSource> video;
    video.reset(new libaom_test::Y4mVideoSource(test_video_param_.filename, 0,
                                                test_video_param_.limit));
    ASSERT_TRUE(video.get() != NULL);

    ASSERT_NO_FATAL_FAILURE(RunLoop(video.get()));
    const double psnr = GetAveragePsnr();
    EXPECT_GT(psnr, GetPsnrThreshold())
        << "superres_mode_ = " << superres_mode_
        << ", superres_denom_ = " << superres_denom_
        << ", superres_kf_denom_ = " << superres_kf_denom_
        << ", superres_qthresh_ = " << superres_qthresh_
        << ", superres_kf_qthresh_ = " << superres_kf_qthresh_;

    EXPECT_EQ(test_video_param_.limit, frame_count_)
        << "superres_mode_ = " << superres_mode_
        << ", superres_denom_ = " << superres_denom_
        << ", superres_kf_denom_ = " << superres_kf_denom_
        << ", superres_qthresh_ = " << superres_qthresh_
        << ", superres_kf_qthresh_ = " << superres_kf_qthresh_;
  }

  int test_video_idx_;
  TestVideoParam test_video_param_;
  SUPERRES_MODE superres_mode_;
  int superres_denom_;
  int superres_kf_denom_;
  int superres_qthresh_;
  int superres_kf_qthresh_;

 private:
  double psnr_;
  unsigned int frame_count_;
};

TEST_P(HorzSuperresQThreshEndToEndTest, HorzSuperresQThreshEndToEndPSNRTest) {
  DoTest();
}

AV1_INSTANTIATE_TEST_CASE(HorzSuperresQThreshEndToEndTest,
                          ::testing::Range(0, NUM_TEST_VIDEOS),
                          ::testing::ValuesIn(kSuperresDenominators),
                          ::testing::ValuesIn(kSuperresQThresholds));

}  // namespace


text:
namespace tests
{
    using System.Collections.Generic;

    [global::Bond.Schema]
    [System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
    public partial class Foo<T>
    {
        [global::Bond.Id(0), global::Bond.Type(typeof(List<List<global::Bond.Tag.classT>>))]
        public IList<IList<T>> aa { get; set; }

        public Foo()
            : this("tests.Foo", "Foo")
        {}

        protected Foo(string fullName, string name)
        {
            aa = new List<IList<T>>();
        }
    }

    [System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
    public enum EnumToWrap
    {
        anEnumValue,
    }

    [global::Bond.Schema]
    [System.CodeDom.Compiler.GeneratedCode("gbc", "0.11.0.0")]
    public partial class WrappingAnEnum
    {
        [global::Bond.Id(0)]
        public EnumToWrap aWrappedEnum { get; set; }

        public WrappingAnEnum()
            : this("tests.WrappingAnEnum", "WrappingAnEnum")
        {}

        protected WrappingAnEnum(string fullName, string name)
        {
            aWrappedEnum = EnumToWrap.anEnumValue;
        }
    }
} // tests


text:
package debop4s.rediscala.serializer

import org.xerial.snappy.Snappy

object SnappyRedisSerializer {

  def apply[T](inner: RedisSerializer[T] = new BinaryRedisSerializer[T]()): SnappyRedisSerializer[T] =
    new SnappyRedisSerializer[T](inner)
}

/**
 * Snappy 압축 알고리즘을 이용하여 serialized 된 데이터를 압축합니다.
 * @author Sunghyouk Bae
 */
class SnappyRedisSerializer[@miniboxed T](val inner: RedisSerializer[T] = new BinaryRedisSerializer[T])
  extends RedisSerializer[T] {

  /**
   * Snappy 압축 알고리즘을 이용하여 serialized 된 데이터를 압축합니다.
   * @param graph serialized 될 객체
   * @return serialized 된 정보를 압축한 데이터
   */
  override def serialize(graph: T): Array[Byte] = {
    if (graph == null)
      return EMPTY_BYTES

    Snappy.compress(inner.serialize(graph))
  }

  /**
   * Snappy 압축 알고리즘을 이용하여 serialized 된 데이터를 복원하고, deserialize 시킵니다.
   * @param bytes 압축된 serialized 된 정보
   * @return 원본 객체
   */
  override def deserialize(bytes: Array[Byte]): T = {
    if (bytes == null || bytes.length == 0)
      return null.asInstanceOf[T]

    inner.deserialize(Snappy.uncompress(bytes)).asInstanceOf[T]
  }
}


text:
import React, {
  PropTypes,
  Platform,
  Animated,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Actions from './Actions';
import _drawerImage from './menu_burger.png';
import _backButtonImage from './back_chevron.png';

const styles = StyleSheet.create({
  title: {
    textAlign: 'center',
    marginTop: 10,
    fontSize: 18,
    fontWeight: '500',
    color: '#0A0A0A',
    position: 'absolute',
    top: Platform.OS === 'ios' || Platform.Version > 19 ? 20 : 0,
    left: 0,
    right: 0,
  },
  header: {
    backgroundColor: '#EFEFF2',
    paddingTop: 0,
    top: 0,
    height: Platform.OS === 'ios' || Platform.Version > 19 ? 64 : 44,
    right: 0,
    left: 0,
    borderBottomWidth: 0.5,
    borderBottomColor: '#828287',
    position: 'absolute',
  },
  backButton: {
    width: 130,
    height: 37,
    position: 'absolute',
    bottom: 4,
    left: 2,
    padding: 8,
    flexDirection: 'row',
  },
  rightButton: {
    width: 100,
    height: 37,
    position: 'absolute',
    bottom: 4,
    right: 2,
    padding: 8,
  },
  leftButton: {
    width: 100,
    height: 37,
    position: 'absolute',
    bottom: 4,
    left: 2,
    padding: 8,
  },
  barRightButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'right',
    fontSize: 17,
  },
  barBackButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'left',
    fontSize: 17,
    paddingLeft: 6,
  },
  barLeftButtonText: {
    color: 'rgb(0, 122, 255)',
    textAlign: 'left',
    fontSize: 17,
  },
  backButtonImage: {
    width: 13,
    height: 21,
  },
  rightButtonIconStyle: {

  },
});

const propTypes = {
  navigationState: PropTypes.object,
  backButtonImage: PropTypes.number,
  backButtonTextStyle: PropTypes.string,
  leftButtonStyle: PropTypes.string,
  leftButtonIconStyle: PropTypes.string,
  getTitle: PropTypes.func,
  titleStyle: PropTypes.object,
  position: PropTypes.object,
  navigationBarStyle: PropTypes.object,
};

const contextTypes = {
  drawer: PropTypes.object,
};

const defaultProps = {
  drawerImage: _drawerImage,
  backButtonImage: _backButtonImage,
};

class NavBar extends React.Component {

  constructor(props) {
    super(props);

    this.renderRightButton = this.renderRightButton.bind(this);
    this.renderBackButton = this.renderBackButton.bind(this);
    this.renderLeftButton = this.renderLeftButton.bind(this);
    this.renderTitle = this.renderTitle.bind(this);
  }

  renderBackButton() {
    const state = this.props.navigationState;
    const childState = state.children[state.index];
    let buttonImage = childState.backButtonImage ||
      state.backButtonImage || this.props.backButtonImage;
    let onPress = Actions.pop;

    if (state.index === 0) {
      return null;
    }

    let text = childState.backTitle ?
      <Text
        style={[
          styles.barBackButtonText,
          this.props.backButtonTextStyle,
          state.backButtonTextStyle,
          childState.backButtonTextStyle,
        ]}
      >
        {childState.backTitle}
      </Text>
      : null;

    return (
      <TouchableOpacity
        testID="backNavButton"
        style={[
          styles.backButton,
          this.props.leftButtonStyle,
          state.leftButtonStyle,
          childState.leftButtonStyle,
        ]}
        onPress={onPress}
      >
        {buttonImage &&
          <Image
            source={buttonImage}
            style={[
              styles.backButtonImage,
              this.props.leftButtonIconStyle,
              state.barButtonIconStyle,
              state.leftButtonIconStyle,
              childState.leftButtonIconStyle,
            ]}
          />
        }
        {text}
      </TouchableOpacity>
    );
  }

  renderRightButton() {
    const self = this;
    function tryRender(state) {
      if (state.rightButton) {
        const Button = state.rightButton;
        return (
          <Button
            {...self.props}
            {...state}
            key={'rightNavBarBtn'}
            testID="rightNavButton"
            style={[styles.rightButton, state.rightButtonStyle]}
          />
        );
      }
      if (state.onRight && (state.rightTitle || state.rightButtonImage)) {
        const onPress = state.onRight.bind(null, state);
        return (
          <TouchableOpacity
            key={'rightNavBarBtn'}
            testID="rightNavButton"
            style={[styles.rightButton, state.rightButtonStyle]}
            onPress={onPress}
          >
            {state.rightTitle &&
              <Text
                style={[
                  styles.barRightButtonText,
                  state.rightButtonTextStyle]}
              >
                {state.rightTitle}
              </Text>
            }
            {state.rightButtonImage &&
              <View
                style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-end' }}
              >
                <Image
                  source={state.rightButtonImage}
                  style={state.rightButtonIconStyle}
                />
              </View>}
          </TouchableOpacity>
        );
      }
      if ((!!state.onRight ^ !!(state.rightTitle || state.rightButtonImage))) {
        console.warn(
          `Both onRight and rightTitle/rightButtonImage
            must be specified for the scene: ${state.name}`
        );
      }
      return null;
    }
    return tryRender(this.props);
  }

  renderLeftButton() {
    const self = this;
    const drawer = this.context.drawer;
    function tryRender(state) {
      let onPress = state.onLeft;
      let buttonImage = state.leftButtonImage;

      if (state.leftButton) {
        const Button = state.leftButton;
        return (
          <Button
            {...self.props}
            {...state}
            key={'leftNavBarBtn'}
            testID="leftNavButton"
            style={[styles.leftButton, state.leftButtonStyle]}
          />
        );
      }

      if (!!drawer && typeof drawer.toggle === 'function') {
        buttonImage = state.drawerImage;
        if (buttonImage) {
          onPress = drawer.toggle;
        }
      }

      if (onPress && (state.leftTitle || buttonImage)) {
        onPress = onPress.bind(null, state);
        return (
          <TouchableOpacity
            key={'leftNavBarBtn'}
            testID="leftNavButton"
            style={[styles.leftButton, state.leftButtonStyle]}
            onPress={onPress}
          >
            {state.leftTitle &&
              <Text
                style={[
                  styles.barLeftButtonText,
                  state.leftButtonTextStyle,
                ]}
              >
                {state.leftTitle}
              </Text>
            }
            {buttonImage &&
              <View
                style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-start' }}
              >
                <Image
                  source={buttonImage}
                  style={state.leftButtonIconStyle}
                />
              </View>}
          </TouchableOpacity>
        );
      }
      if ((!!state.onLeft ^ !!(state.leftTitle || buttonImage))) {
        console.warn(
          `Both onLeft and leftTitle/leftButtonImage
            must be specified for the scene: ${state.name}`
        );
      }
      return null;
    }
    return tryRender(this.props);
  }

  renderTitle(childState, index:number) {
    const title = this.props.getTitle ? this.props.getTitle(childState) : childState.title;
    return (
      <Animated.Text
        key={childState.key}
        style={[
          styles.title,
          this.props.titleStyle,
          this.props.navigationState.titleStyle,
          childState.titleStyle,
          {
            opacity: this.props.position.interpolate({
              inputRange: [index - 1, index, index + 1],
              outputRange: [0, 1, 0],
            }),
            left: this.props.position.interpolate({
              inputRange: [index - 1, index + 1],
              outputRange: [200, -200],
            }),
            right: this.props.position.interpolate({
              inputRange: [index - 1, index + 1],
              outputRange: [-200, 200],
            }),
          },
        ]}
      >
        {title}
      </Animated.Text>
    );
  }

  render() {
    let state = this.props.navigationState;
    let selected = state.children[state.index];
    while (selected.hasOwnProperty('children')) {
      state = selected;
      selected = selected.children[selected.index];
    }

    const renderLeftButton = selected.renderLeftButton ||
      selected.component.renderLeftButton ||
      this.renderLeftButton;
    const renderRightButton = selected.renderRightButton ||
      selected.component.renderRightButton ||
      this.renderRightButton;
    const renderBackButton = selected.renderBackButton ||
      selected.component.renderBackButton ||
      this.renderBackButton;
    const renderTitle = selected.renderTitle ||
      selected.component.renderTitle;
    return (
      <Animated.View
        style={[
          styles.header,
          this.props.navigationBarStyle,
          state.navigationBarStyle,
          selected.navigationBarStyle,
        ]}
      >
        {renderTitle ? renderTitle(selected) : state.children.map(this.renderTitle, this)}
        {renderBackButton() || renderLeftButton()}
        {renderRightButton()}
      </Animated.View>
    );
  }
}

NavBar.propTypes = propTypes;
NavBar.contextTypes = contextTypes;
NavBar.defaultProps = defaultProps;

export default NavBar;


text:
package io.datalayer.data.spl7;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Perm2 {
    public static void main(String... args) {
        int minGroupSize = Integer.parseInt(args[1]);

        // Read words from file and put into simulated multimap
        Map m = new HashMap();
        try {
            BufferedReader in =
                   new BufferedReader(new FileReader(args[0]));
            String word;
            while((word = in.readLine()) != null) {
                String alpha = alphabetize(word);
                List l = (List) m.get(alpha);
                if (l==null)
                    m.put(alpha, l=new ArrayList());
                l.add(word);
            }
        } catch(IOException e) {
            System.err.println(e);
            System.exit(1);
        }

        // Make a List of all permutation groups above size threshold
        List winners = new ArrayList();
        for (Iterator i = m.values().iterator(); i.hasNext(); ) {
            List l = (List) i.next();
            if (l.size() >= minGroupSize)
                winners.add(l);
    }

        // Sort permutation groups according to size
        Collections.sort(winners, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((List)o2).size() - ((List)o1).size();
            }
        });

        // Print permutation groups
        for (Iterator i=winners.iterator(); i.hasNext(); ) {
            List l = (List) i.next();
            System.out.println(l.size() + ": " + l);
        }
    }

    private static String alphabetize(String s) {
        int count[] = new int[256];
        int len = s.length();
        for (int i=0; i<len; i++)
            count[s.charAt(i)]++;
        StringBuffer result = new StringBuffer(len);
        for (char c='a'; c<='z'; c++)
            for (int i=0; i<count[c]; i++)
                result.append(c);
        return result.toString();
    }
}


text:
package com.amazonaws.services.wafv2.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Specifies that WAF should do nothing. This is used for the OverrideAction setting on a Rule when
 * the rule uses a rule group reference statement.
 *

 *

 * This is used in the context of other settings, for example to specify values for RuleAction and web ACL
 * DefaultAction.
 *

 *

 * JSON specification: "None": {}
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class NoneAction implements Serializable, Cloneable, StructuredPojo {

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof NoneAction == false)
            return false;
        NoneAction other = (NoneAction) obj;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        return hashCode;
    }

    @Override
    public NoneAction clone() {
        try {
            return (NoneAction) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.wafv2.model.transform.NoneActionMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}