text:
/* application settings */

#include "config.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <assert.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <ctype.h>

#include <piano.h>

#include "settings.h"
#include "config.h"
#include "ui.h"
#include "ui_dispatch.h"

#define streq(a, b) (strcmp (a, b) == 0)

/*	Get current user's home directory
 */
static char *BarSettingsGetHome () {
	char *home;

	/* try environment variable */
	if ((home = getenv ("HOME")) != NULL && strlen (home) > 0) {
		return strdup (home);
	}

	/* try passwd mechanism */
	struct passwd * const pw = getpwuid (getuid ());
	if (pw != NULL && pw->pw_dir != NULL && strlen (pw->pw_dir) > 0) {
		return strdup (pw->pw_dir);
	}

	return NULL;
}

/*	Get XDG config directory, which is set by BarSettingsRead (if not set)
 */
static char *BarGetXdgConfigDir (const char * const filename) {
	assert (filename != NULL);

	char *xdgConfigDir;

	if ((xdgConfigDir = getenv ("XDG_CONFIG_HOME")) != NULL &&
			strlen (xdgConfigDir) > 0) {
		const size_t len = (strlen (xdgConfigDir) + 1 +
				strlen (filename) + 1);
		char * const concat = malloc (len * sizeof (*concat));
		snprintf (concat, len, "%s/%s", xdgConfigDir, filename);
		return concat;
	}

	return NULL;
}

/*	Expand ~/ to user's home directory
 */
char *BarSettingsExpandTilde (const char * const path, const char * const home) {
	assert (path != NULL);
	assert (home != NULL);

	if (strncmp (path, "~/", 2) == 0) {
		char * const expanded = malloc ((strlen (home) + 1 + strlen (path)-2 + 1) *
				sizeof (*expanded));
		sprintf (expanded, "%s/%s", home, &path[2]);
		return expanded;
	}

	return strdup (path);
}

/*	initialize settings structure
 *	@param settings struct
 */
void BarSettingsInit (BarSettings_t *settings) {
	memset (settings, 0, sizeof (*settings));
}

/*	free settings structure, zero it afterwards
 *	@oaram pointer to struct
 */
void BarSettingsDestroy (BarSettings_t *settings) {
	free (settings->controlProxy);
	free (settings->proxy);
	free (settings->bindTo);
	free (settings->username);
	free (settings->password);
	free (settings->passwordCmd);
	free (settings->autostartStation);
	free (settings->eventCmd);
	free (settings->loveIcon);
	free (settings->banIcon);
	free (settings->tiredIcon);
	free (settings->atIcon);
	free (settings->npSongFormat);
	free (settings->npStationFormat);
	free (settings->listSongFormat);
	free (settings->timeFormat);
	free (settings->fifo);
	free (settings->audioPipe);
	free (settings->rpcHost);
	free (settings->rpcTlsPort);
	free (settings->partnerUser);
	free (settings->partnerPassword);
	free (settings->device);
	free (settings->inkey);
	free (settings->outkey);
	for (size_t i = 0; i < MSG_COUNT; i++) {
		free (settings->msgFormat[i].prefix);
		free (settings->msgFormat[i].postfix);
	}
	memset (settings, 0, sizeof (*settings));
}

/*	read app settings from file; format is: key = value\n
 *	@param where to save these settings
 *	@return nothing yet
 */
void BarSettingsRead (BarSettings_t *settings) {
	char * const configfiles[] = {PACKAGE "/state", PACKAGE "/config"};
	char * const userhome = BarSettingsGetHome ();
	assert (userhome != NULL);
	/* set xdg config path (if not set) */
	char * const defaultxdg = malloc (strlen (userhome) + strlen ("/.config") + 1);
	sprintf (defaultxdg, "%s/.config", userhome);
	setenv ("XDG_CONFIG_HOME", defaultxdg, 0);
	free (defaultxdg);

	assert (sizeof (settings->keys) / sizeof (*settings->keys) ==
			sizeof (dispatchActions) / sizeof (*dispatchActions));

	/* apply defaults */
	settings->audioQuality = PIANO_AQ_HIGH;
	settings->autoselect = true;
	settings->history = 5;
	settings->volume = 0;
	settings->timeout = 30; /* seconds */
	settings->gainMul = 1.0;
	/* should be > 4, otherwise expired audio urls (403) can stop playback */
	settings->maxRetry = 5;
	settings->bufferSecs = 5;
	settings->sortOrder = BAR_SORT_NAME_AZ;
	settings->loveIcon = strdup (" <3");
	settings->banIcon = strdup (" </3");
	settings->tiredIcon = strdup (" zZ");
	settings->atIcon = strdup (" @ ");
	settings->npSongFormat = strdup ("\"%t\" by \"%a\" on \"%l\"%r%@%s");
	settings->npStationFormat = strdup ("Station \"%n\" (%i)");
	settings->listSongFormat = strdup ("%i) %a - %t%r");
	settings->timeFormat = strdup ("%s%r/%t");
	settings->rpcHost = strdup (PIANO_RPC_HOST);
	settings->rpcTlsPort = strdup ("443");
	settings->partnerUser = strdup ("android");
	settings->partnerPassword = strdup ("AC7IBG09A3DTSYM4R41UJWL07VLN8JI7");
	settings->device = strdup ("android-generic");
	settings->inkey = strdup ("R=U!LH$O2B#");
	settings->outkey = strdup ("6#26FRL$ZWD");
	settings->fifo = BarGetXdgConfigDir (PACKAGE "/ctl");
	settings->audioPipe = NULL;
	assert (settings->fifo != NULL);
	settings->sampleRate = 0; /* default to stream sample rate */

	settings->msgFormat[MSG_NONE].prefix = NULL;
	settings->msgFormat[MSG_NONE].postfix = NULL;
	settings->msgFormat[MSG_INFO].prefix = strdup ("(i) ");
	settings->msgFormat[MSG_INFO].postfix = NULL;
	settings->msgFormat[MSG_PLAYING].prefix = strdup ("|>  ");
	settings->msgFormat[MSG_PLAYING].postfix = NULL;
	settings->msgFormat[MSG_TIME].prefix = strdup ("#   ");
	settings->msgFormat[MSG_TIME].postfix = NULL;
	settings->msgFormat[MSG_ERR].prefix = strdup ("/!\\ ");
	settings->msgFormat[MSG_ERR].postfix = NULL;
	settings->msgFormat[MSG_QUESTION].prefix = strdup ("[?] ");
	settings->msgFormat[MSG_QUESTION].postfix = NULL;
	settings->msgFormat[MSG_LIST].prefix = strdup ("\t");
	settings->msgFormat[MSG_LIST].postfix = NULL;

	for (size_t i = 0; i < BAR_KS_COUNT; i++) {
		settings->keys[i] = dispatchActions[i].defaultKey;
	}

	/* read config files */
	for (size_t j = 0; j < sizeof (configfiles) / sizeof (*configfiles); j++) {
		static const char *formatMsgPrefix = "format_msg_";
		FILE *configfd;
		char line[512];
		size_t lineNum = 0;

		char * const path = BarGetXdgConfigDir (configfiles[j]);
		assert (path != NULL);
		if ((configfd = fopen (path, "r")) == NULL) {
			free (path);
			continue;
		}

		while (1) {
			++lineNum;
			char * const ret = fgets (line, sizeof (line), configfd);
			if (ret == NULL) {
				/* EOF or error */
				break;
			}
			if (strchr (line, '\n') == NULL && !feof (configfd)) {
				BarUiMsg (settings, MSG_INFO, "Line %s:%zu too long, "
						"ignoring\n", path, lineNum);
				continue;
			}
			/* parse lines that match "^\s*(.*?)\s?=\s?(.*)$". Windows and Unix
			 * line terminators are supported. */
			char *key = line;

			/* skip leading spaces */
			while (isspace ((unsigned char) key[0])) {
				++key;
			}

			/* skip comments */
			if (key[0] == '#') {
				continue;
			}

			/* search for delimiter and split key-value pair */
			char *val = strchr (line, '=');
			if (val == NULL) {
				/* no warning for empty lines */
				if (key[0] != '\0') {
					BarUiMsg (settings, MSG_INFO,
							"Invalid line at %s:%zu\n", path, lineNum);
				}
				/* invalid line */
				continue;
			}
			*val = '\0';
			++val;

			/* drop spaces at the end */
			char *keyend = &key[strlen (key)-1];
			while (keyend >= key && isspace ((unsigned char) *keyend)) {
				*keyend = '\0';
				--keyend;
			}

			/* strip at most one space, legacy cruft, required for values with
			 * leading spaces like love_icon */
			if (isspace ((unsigned char) val[0])) {
				++val;
			}
			/* drop trailing cr/lf */
			char *valend = &val[strlen (val)-1];
			while (valend >= val && (*valend == '\r' || *valend == '\n')) {
				*valend = '\0';
				--valend;
			}

			if (streq ("control_proxy", key)) {
				settings->controlProxy = strdup (val);
			} else if (streq ("proxy", key)) {
				settings->proxy = strdup (val);
			} else if (streq ("bind_to", key)) {
				settings->bindTo = strdup (val);
			} else if (streq ("user", key)) {
				settings->username = strdup (val);
			} else if (streq ("password", key)) {
				settings->password = strdup (val);
			} else if (streq ("password_command", key)) {
				settings->passwordCmd = strdup (val);
			} else if (streq ("rpc_host", key)) {
				free (settings->rpcHost);
				settings->rpcHost = strdup (val);
			} else if (streq ("rpc_tls_port", key)) {
				free (settings->rpcTlsPort);
				settings->rpcTlsPort = strdup (val);
			} else if (streq ("partner_user", key)) {
				free (settings->partnerUser);
				settings->partnerUser = strdup (val);
			} else if (streq ("partner_password", key)) {
				free (settings->partnerPassword);
				settings->partnerPassword = strdup (val);
			} else if (streq ("device", key)) {
				free (settings->device);
				settings->device = strdup (val);
			} else if (streq ("encrypt_password", key)) {
				free (settings->outkey);
				settings->outkey = strdup (val);
			} else if (streq ("decrypt_password", key)) {
				free (settings->inkey);
				settings->inkey = strdup (val);
			} else if (streq ("ca_bundle", key)) {
				free (settings->caBundle);
				settings->caBundle = strdup (val);
			} else if (memcmp ("act_", key, 4) == 0) {
				size_t i;
				/* keyboard shortcuts */
				for (i = 0; i < BAR_KS_COUNT; i++) {
					if (streq (dispatchActions[i].configKey, key)) {
						if (streq (val, "disabled")) {
							settings->keys[i] = BAR_KS_DISABLED;
						} else {
							settings->keys[i] = val[0];
						}
						break;
					}
				}
			} else if (streq ("audio_quality", key)) {
				if (streq (val, "low")) {
					settings->audioQuality = PIANO_AQ_LOW;
				} else if (streq (val, "medium")) {
					settings->audioQuality = PIANO_AQ_MEDIUM;
				} else if (streq (val, "high")) {
					settings->audioQuality = PIANO_AQ_HIGH;
				}
			} else if (streq ("autostart_station", key)) {
				free (settings->autostartStation);
				settings->autostartStation = strdup (val);
			} else if (streq ("event_command", key)) {
				settings->eventCmd = BarSettingsExpandTilde (val, userhome);
			} else if (streq ("history", key)) {
				settings->history = atoi (val);
			} else if (streq ("max_retry", key)) {
				settings->maxRetry = atoi (val);
			} else if (streq ("timeout", key)) {
				settings->timeout = atoi (val);
			} else if (streq ("buffer_seconds", key)) {
				settings->bufferSecs = atoi (val);
			} else if (streq ("sort", key)) {
				size_t i;
				static const char *mapping[] = {"name_az",
						"name_za",
						"quickmix_01_name_az",
						"quickmix_01_name_za",
						"quickmix_10_name_az",
						"quickmix_10_name_za",
						};
				for (i = 0; i < BAR_SORT_COUNT; i++) {
					if (streq (mapping[i], val)) {
						settings->sortOrder = i;
						break;
					}
				}
			} else if (streq ("love_icon", key)) {
				free (settings->loveIcon);
				settings->loveIcon = strdup (val);
			} else if (streq ("ban_icon", key)) {
				free (settings->banIcon);
				settings->banIcon = strdup (val);
			} else if (streq ("tired_icon", key)) {
				free (settings->tiredIcon);
				settings->tiredIcon = strdup (val);
			} else if (streq ("at_icon", key)) {
				free (settings->atIcon);
				settings->atIcon = strdup (val);
			} else if (streq ("volume", key)) {
				settings->volume = atoi (val);
			} else if (streq ("gain_mul", key)) {
				settings->gainMul = atof (val);
			} else if (streq ("format_nowplaying_song", key)) {
				free (settings->npSongFormat);
				settings->npSongFormat = strdup (val);
			} else if (streq ("format_nowplaying_station", key)) {
				free (settings->npStationFormat);
				settings->npStationFormat = strdup (val);
			} else if (streq ("format_list_song", key)) {
				free (settings->listSongFormat);
				settings->listSongFormat = strdup (val);
			} else if (streq ("format_time", key)) {
				free (settings->timeFormat);
				settings->timeFormat = strdup (val);
			} else if (streq ("fifo", key)) {
				free (settings->fifo);
				settings->fifo = BarSettingsExpandTilde (val, userhome);
			} else if (streq ("audio_pipe", key)) {
				free (settings->audioPipe);
				settings->audioPipe = BarSettingsExpandTilde (val, userhome);
			} else if (streq ("autoselect", key)) {
				settings->autoselect = atoi (val);
			} else if (streq ("sample_rate", key)) {
				settings->sampleRate = atoi (val);
			} else if (strncmp (formatMsgPrefix, key,
					strlen (formatMsgPrefix)) == 0) {
				static const char *mapping[] = {"none", "info", "nowplaying",
						"time", "err", "question", "list"};
				const char *typeStart = key + strlen (formatMsgPrefix);
				for (size_t i = 0; i < sizeof (mapping) / sizeof (*mapping); i++) {
					if (streq (typeStart, mapping[i])) {
						const char *formatPos = strstr (val, "%s");

						/* keep default if there is no format character */
						if (formatPos != NULL) {
							BarMsgFormatStr_t *format = &settings->msgFormat[i];

							free (format->prefix);
							free (format->postfix);

							const size_t prefixLen = formatPos - val;
							format->prefix = calloc (prefixLen + 1,
									sizeof (*format->prefix));
							memcpy (format->prefix, val, prefixLen);

							const size_t postfixLen = strlen (val) -
									(formatPos-val) - 2;
							format->postfix = calloc (postfixLen + 1,
									sizeof (*format->postfix));
							memcpy (format->postfix, formatPos+2, postfixLen);
						}
						break;
					}
				}
			} else {
				BarUiMsg (settings, MSG_INFO,
						"Unrecognized key %s at %s:%zu\n", key, path, lineNum);
			}
		}

		fclose (configfd);
		free (path);
	}

	/* check environment variable if proxy is not set explicitly */
	if (settings->proxy == NULL) {
		char *tmpProxy = getenv ("http_proxy");
		if (tmpProxy != NULL && strlen (tmpProxy) > 0) {
			settings->proxy = strdup (tmpProxy);
		}
	}

	/* ffmpeg does not support setting an http proxy explicitly */
	if (settings->proxy != NULL) {
		setenv ("http_proxy", settings->proxy, 1);
	}

	free (userhome);
}

/*	write statefile
 */
void BarSettingsWrite (PianoStation_t *station, BarSettings_t *settings) {
	FILE *fd;

	assert (settings != NULL);

	char * const path = BarGetXdgConfigDir (PACKAGE "/state");
	assert (path != NULL);
	if ((fd = fopen (path, "w")) == NULL) {
		free (path);
		return;
	}

	fputs ("# do not edit this file\n", fd);
	fprintf (fd, "volume = %i\n", settings->volume);
	if (station != NULL) {
		fprintf (fd, "autostart_station = %s\n", station->id);
	}

	fclose (fd);
	free (path);
}


text:
using SuperMap.WinRT.Service;
using System;
using SuperMap.WinRT.REST.Resources;
using System.Collections.Generic;
using SuperMap.WinRT.Core;
using SuperMap.WinRT.Utilities;
using Windows.Data.Json;
using System.Threading.Tasks;
namespace SuperMap.WinRT.REST.Data
{
    ///
    /// 	<para>${REST_GetFeaturesByGeometryService_Title}</para>
    /// 	<para>${REST_GetFeaturesByGeometryService_Description}</para>
    ///
    public class GetFeaturesByGeometryService : ServiceBase
    {
        /// ${REST_GetFeaturesByGeometryService_constructor_D}
        /// <overloads>${REST_GetFeaturesByBufferService_constructor_overloads_D}</overloads>
        public GetFeaturesByGeometryService()
        {

        }
        /// ${REST_GetFeaturesByBufferService_constructor_String_D}
        /// <param name="url">${REST_GetFeaturesByGeometryService_constructor_param_url}</param>
        public GetFeaturesByGeometryService(string url)
            : base(url)
        {

        }

        /// ${REST_GetFeaturesByGeometryService_method_ProcessAsync_D}
        /// <param name="parameters">${REST_GetFeaturesByGeometryService_method_ProcessAsync_param_Parameters}</param>
        /// <param name="state">${REST_GetFeaturesByGeometryService_method_ProcessAsync_param_state}</param>
        public async Task<GetFeaturesResult> ProcessAsync(GetFeaturesByGeometryParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(ExceptionStrings.ArgumentIsNull);
            }
            if (string.IsNullOrEmpty(this.Url))
            {
                throw new InvalidOperationException(ExceptionStrings.InvalidUrl);
            }

            //base.Url += ".json?returnContent=true";
            base.Url += string.Format(".json?returnContent=true&debug=true&fromIndex={0}&toIndex={1}", parameters.FromIndex, parameters.ToIndex);

            var result = await base.SubmitRequest(base.Url, GetParameters(parameters), true);
            JsonObject jsonObject = JsonObject.Parse(result);
            return GetFeaturesResult.FromJson(jsonObject);
        }

        private Dictionary<string, string> GetParameters(GetFeaturesByGeometryParameters parameters)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();

            if (string.IsNullOrEmpty(parameters.AttributeFilter))
            {
                dictionary.Add("getFeatureMode", "\"SPATIAL\"");
            }
            else
            {
                dictionary.Add("getFeatureMode", "\"SPATIAL_ATTRIBUTEFILTER\"");
                dictionary.Add("attributeFilter", parameters.AttributeFilter);
            }
            if (parameters.DatasetNames != null && parameters.DatasetNames.Count > 0)
            {
                string jsonDatasetNames = "[";
                List<string> list = new List<string>();
                for (int i = 0; i < parameters.DatasetNames.Count; i++)
                {
                    list.Add(string.Format("\"{0}\"", parameters.DatasetNames[i]));
                }
                jsonDatasetNames += string.Join(",", list.ToArray());
                jsonDatasetNames += "]";

                dictionary.Add("datasetNames", jsonDatasetNames);
            }
            else
            {
                throw new ArgumentNullException(ExceptionStrings.ArgumentIsNull);
            }
            dictionary.Add("spatialQueryMode", parameters.SpatialQueryMode.ToString().ToUpper());

            if (parameters.Geometry != null)
            {
                dictionary.Add("geometry", ServerGeometry.ToJson(Bridge.ToServerGeometry(parameters.Geometry)));
            }
            else
            {
                throw new ArgumentNullException(ExceptionStrings.ArgumentIsNull);
            }

            if (parameters.Fields != null && parameters.Fields.Count > 0)
            {
                FilterParameter fp = new FilterParameter();
                fp.Fields = parameters.Fields;
                dictionary.Add("queryParameter", FilterParameter.ToJson(fp));
            }
            return dictionary;
        }
        //private void request_Completed(object sender, RequestEventArgs e)
        //{
        //    JsonObject jsonObject = JsonObject.Parse(e.Result);
        //    GetFeaturesResult result = GetFeaturesResult.FromJson(jsonObject);
        //    LastResult = result;
        //    GetFeaturesEventArgs args = new GetFeaturesEventArgs(result, e.Result, e.UserState);
        //    OnProcessCompleted(args);
        //}

        //private void OnProcessCompleted(GetFeaturesEventArgs args)
        //{
        //    if (ProcessCompleted != null)
        //    {
        //        this.ProcessCompleted(this, args);
        //    }
        //}

        ///// ${REST_GetFeaturesByGeometryService_event_processCompleted_D}

        //public event EventHandler<GetFeaturesEventArgs> ProcessCompleted;

        //private GetFeaturesResult lastResult;
        ///// ${REST_GetFeaturesByGeometryService_attribute_LastResult_D}
        //public GetFeaturesResult LastResult
        //{
        //    get
        //    {
        //        return lastResult;
        //    }
        //    private set
        //    {
        //        lastResult = value;
        //        base.OnPropertyChanged("LastResult");
        //    }
        //}
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02.Students_and_workers
{
    class Worker : Human
    {
        // Fields
        private double weekSalary;
        private double workHoursPerDay;

        // Properties
        public double WorkHoursPerDay
        {
            get { return workHoursPerDay; }
            set
            {
                if (value<0 || value > 24)
                {
                    throw new ArgumentException("Invalid daily workhours value!");
                }

                workHoursPerDay = value; }
        }

        public double WeekSalary
        {
            get
            {
                return this.weekSalary;
            }
            set
            {
                if (value<0)
                {
                    throw new ArgumentException("Invalid salary value! Cannot be negative!");
                }

                this.weekSalary = value;
            }
        }

        // Constructors
        public Worker(string first, string last, double salary, double workHours)
            : this (first, last)
        {
            this.WeekSalary = salary;
            this.WorkHoursPerDay = workHours;
        }

        public Worker(string first, string last)
            : base(first, last)
        { }

        // Mehods
        public double MoneyPerHour()
        {
            return this.WeekSalary / (this.WorkHoursPerDay * 5);
        }

        public override string ToString()
        {
            return String.Format("{0} {1}, Money/hour: {2}", this.FirstName, this.LastName, this.MoneyPerHour());
        }
    }
}


text:
package java.security.cert;

import java.util.Collection;
import java.util.Collections;

/**
 * The parameters to initialize a Collection type {@code CertStore} instance.
 *

 * It is used to specify the {@code Collection} where the {@code CertStore} will
 * retrieve the certificates and CRLs from.
 */
public class CollectionCertStoreParameters implements CertStoreParameters {
    // Default empty and immutable collection.
    // Used if CollectionCertStoreParametersinstance
    // created by the no arg constructor
    private static final Collection<?> defaultCollection = Collections.EMPTY_SET;
    // A Collection of Certificates
    // and CRLs
    private final Collection<?> collection;

    /**
     * Creates a new {@code CollectionCertStoreParameters} without a collection.
     *

     * The default collection is an empty and unmodifiable {@code Collection}.
     */
    public CollectionCertStoreParameters() {
        this.collection = defaultCollection;
    }

    /**
     * Creates a new {@code CollectionCertStoreParameters} with the specified
     * collection.
     *

     * The specified collection is not copied and therefore may be modified at
     * any time.
     *
     * @param collection
     *            the collection where the {@code Certificate}s and {@code CRL}s
     *            will be retrieved from.
     * @throws NullPointerException
     *             if {@code collection is null}.
     */
    public CollectionCertStoreParameters(Collection<?> collection) {
        if (collection == null) {
            throw new NullPointerException("collection == null");
        }
        this.collection = collection;
    }

    /**
     * Clones this {@code CollectionCertStoreParameters} instance, but not the
     * underlying collection.
     *
     * @return the cloned instance.
     */
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }

    /**
     * Returns the collection where the {@code Certificate}s and {@code CRL}s
     * are retrieved from.
     *
     * @return the collection where the {@code Certificate}s and {@code CRL}s
     *         will be retrieved from.
     */
    public Collection<?> getCollection() {
        return collection;
    }

    /**
     * Returns the string representation of this instance.
     *
     * @return the string representation of this instance.
     */
    public String toString() {
        StringBuilder sb =
            new StringBuilder("CollectionCertStoreParameters: [\ncollection: ");
        sb.append(getCollection().toString());
        sb.append("\n]");
        return sb.toString();
    }
}


text:
import loadNone from './code-splitting/lazy-load-none';
import loadStatic from './code-splitting/lazy-load-entry-static';
import loadDynamic from './code-splitting/lazy-load-entry-dynamic';


text:
#pragma once

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#pragma clang diagnostic ignored "-Winfinite-recursion"
#endif

#include "cpprest/details/cpprest_compat.h"
#include "cpprest/details/basic_types.h"

#ifdef _WIN32
#ifdef CPPREST_TARGET_XP
#include <winsdkver.h>
#ifndef _WIN32_WINNT
#define _WIN32_WINNT _WIN32_WINNT_WS03 //Windows XP with SP2
#endif
#endif
#include <SDKDDKVer.h>
// use the debug version of the CRT if _DEBUG is defined
#ifdef _DEBUG
    #define _CRTDBG_MAP_ALLOC
    #include <stdlib.h>
    #include <crtdbg.h>
#endif

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#define NOMINMAX
#endif

#include <windows.h>
#include <objbase.h>

// Windows Header Files:
#if !defined(__cplusplus_winrt)
#include <winhttp.h>

#endif // #if !defined(__cplusplus_winrt)
#else // LINUX or APPLE
#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <cstdint>
#include <string>
#include <sstream>
#include <thread>
#include <atomic>
#include <signal.h>
#include "pthread.h"
#if (defined(ANDROID) || defined(__ANDROID__))
// Boost doesn't recognize libstdcpp on top of clang correctly
#include "boost/config.hpp"
#include "boost/config/stdlib/libstdcpp3.hpp"
#undef BOOST_NO_CXX11_SMART_PTR
#undef BOOST_NO_CXX11_NULLPTR
#endif
#include "boost/thread/mutex.hpp"
#include "boost/thread/condition_variable.hpp"
#include "boost/date_time/posix_time/posix_time_types.hpp"
#include "boost/bind/bind.hpp"
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#endif // _WIN32

// Macro indicating the C++ Rest SDK product itself is being built.
// This is to help track how many developers are directly building from source themselves.
#define _CASA_BUILD_FROM_SRC

#include <iostream>
#include <fstream>
#include <algorithm>
#include <exception>
#include <assert.h>
#include <streambuf>
#include <mutex>
#include <array>
#include <vector>
#include <memory>
#include <thread>
#include <set>

#include "pplx/pplxtasks.h"
#include "cpprest/version.h"

// streams
#include "cpprest/streams.h"
#include "cpprest/astreambuf.h"
#include "cpprest/rawptrstream.h"
#include "cpprest/interopstream.h"
#include "cpprest/producerconsumerstream.h"

// json
#include "cpprest/json.h"

// uri
#include "cpprest/base_uri.h"
#include "cpprest/details/uri_parser.h"

// utilities
#include "cpprest/asyncrt_utils.h"
#include "cpprest/details/web_utilities.h"

// http
#include "cpprest/http_headers.h"
#include "cpprest/http_msg.h"
#include "cpprest/http_client.h"
#include "cpprest/details/http_helpers.h"

// oauth
#if !defined(_WIN32) || _WIN32_WINNT >= _WIN32_WINNT_VISTA
#include "cpprest/oauth1.h"
#endif
#include "cpprest/oauth2.h"

// websockets
#include "cpprest/ws_client.h"
#include "cpprest/ws_msg.h"

#if !defined(__cplusplus_winrt)
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
#include "cpprest/details/http_server.h"
#include "cpprest/http_listener.h"
#include "cpprest/details/http_server_api.h"
#endif // _WIN32_WINNT >= _WIN32_WINNT_VISTA
#endif

#if defined(max)
#error: max macro defined -- make sure to #define NOMINMAX before including windows.h
#endif
#if defined(min)
#error: min macro defined -- make sure to #define NOMINMAX before including windows.h
#endif

#if defined(__clang__)
#pragma clang diagnostic pop
#endif


text:
<?php

namespace Drafterbit\Bundle\SystemBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;

class DashboardPass implements CompilerPassInterface {

    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('drafterbit_system.dashboard_manager')) {
            return;
        }

        $definition = $container->getDefinition(
            'drafterbit_system.dashboard_manager'
        );

        $taggedServices = $container->findTaggedServiceIds(
            'drafterbit_system.dashboard.panel'
        );

        foreach ($taggedServices as $id => $tags) {
            $definition->addMethodCall(
                'addPanel',
                array(new Reference($id))
            );
        }
    }
}


text:
package org.hisp.dhis.fileresource;

import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.MergeMode;

import java.util.Date;

/**
 * @author Stian Sandvold
 */
public class ExternalFileResource
    extends BaseIdentifiableObject
{

    /**
     * FileResource containing the file we are exposing
     */
    private FileResource fileResource;

    /**
     * The accessToken required to identify ExternalFileResources trough the api
     */
    private String accessToken;

    /**
     * Date when the resource expires. Null means it never expires
     */
    private Date expires;

    public Date getExpires()
    {
        return expires;
    }

    public void setExpires( Date expires )
    {
        this.expires = expires;
    }

    public String getAccessToken()
    {
        return accessToken;
    }

    public void setAccessToken( String accessToken )
    {
        this.accessToken = accessToken;
    }

    public FileResource getFileResource()
    {
        return fileResource;
    }

    public void setFileResource( FileResource fileResource )
    {
        this.fileResource = fileResource;
    }

    @Override
    public void mergeWith( IdentifiableObject other, MergeMode mergeMode )
    {

        super.mergeWith( other, mergeMode );

        if ( other.getClass().isInstance( this ) )
        {

            ExternalFileResource externalFileResource = (ExternalFileResource) other;

            if ( mergeMode.isReplace() )
            {
                fileResource = externalFileResource.getFileResource();
                accessToken = externalFileResource.getAccessToken();
                expires = externalFileResource.getExpires();
            }

            if ( mergeMode.isMerge() )
            {
                fileResource = (externalFileResource.getFileResource() != null ?
                    externalFileResource.getFileResource() :
                    null);
                accessToken = (externalFileResource.getAccessToken() != null ?
                    externalFileResource.getAccessToken() :
                    null);
                expires = (externalFileResource.getExpires() != null ? externalFileResource.getExpires() : null);
            }
        }
    }
}


text:
package test.fvd;

public interface Bounceable extends Abstract, Value {
    Bounceable validateAndReplace();
}


text:
namespace AssortedWidgets
{
	namespace Theme
	{
		class SubImage
		{
		private:
            GLfloat m_UpLeftX;
            GLfloat m_UpLeftY;
            GLfloat m_BottomRightX;
            GLfloat m_BottomRightY;
            GLuint m_textureID;

		public:
            SubImage(GLfloat _UpLeftX, GLfloat _UpLeftY, GLfloat _BottomRightX, GLfloat _BottomRightY, GLuint _textureID)
                :m_UpLeftX(_UpLeftX),
                  m_UpLeftY(_UpLeftY),
                  m_BottomRightX(_BottomRightX),
                  m_BottomRightY(_BottomRightY),
                  m_textureID(_textureID)
            {

            }
            void paint(const float x1,const float y1,const float x2,const float y2) const;

		public:
			~SubImage(void)
			{
            }
		};
	}
}


text:
package voodoo

import "errors"

var (
	ErrNoKeyExists = errors.New("voodoo/keyvalue: no key exists")
)

// KeyValue is the primitive interface
// on top of which SQL is mapped.
//
// /columnspace/pkey = row
type KeyValue interface {
	Get(key []byte) ([]byte, error)
	Set(key []byte, val []byte) error

	// Walk is used to traverse parts of the keyspace
	Walk(prefix []byte) (Iterator, error)
}

// An Iterator is used to traverse the keyspace
type Iterator interface {
	// get the value at the iterator location
	Val() []byte
	// get the current key
	Key() []byte
	// move to the first key
	First() bool
	// move to the last key
	Last() bool
	// move to the next key
	Next() bool
	// move to the previous key
	Prev() bool
}


text:
#pragma once

#include <VoxieClient/VoxieClient.hpp>

#include <QtCore/QObject>
#include <QtCore/QRunnable>
#include <QtCore/QSharedPointer>

#include <functional>
#include <type_traits>

// QList::toStdVector() was deprecated in Qt 5.14, but in many cases using this
// is much easier than calling the std::vector constructor with two arguments.
template <typename T>
std::vector<T> toStdVector(const QVector<T>& vector) {
  return std::vector<T>(vector.begin(), vector.end());
}
template <typename T>
std::vector<T> toStdVector(const QList<T>& list) {
  return std::vector<T>(list.begin(), list.end());
}

// QVector::fromStdVector() was deprecated in Qt 5.14, but the replacement is
// not available before Qt 5.14.
template <typename T>
QVector<T> toQVector(const std::vector<T>& vector) {
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
  return QVector<T>::fromStdVector(vector);
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
template <typename T>
QList<T> toQList(const std::vector<T>& vector) {
  return toQVector(vector).toList();
}

// QSet::fromList() was deprecated in Qt 5.14, but the replacement is
// not available before Qt 5.14.
template <typename T>
QSet<T> toQSet(const QList<T>& list) {
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
  return QSet<T>::fromList(list);
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}

template <typename T, typename... U>
static inline QSharedPointer<T> createQSharedPointer(U&&... par) {
  // Creating a QSharedPointer for a QObject with a default deallocator is
  // almost always the wrong thing to do: If a background thread drops the last
  // reference, the destructor would be run on a background thread. Use
  // makeSharedQObject<>() instead.
  static_assert(!std::is_base_of<QObject, T>::value,
                "Trying to call createQSharedPointer for a QObject");

  // QSharedPointer<T>::create() is broken: If the constructor throws an
  // exception, it will call the objects destructor.
  // https://bugreports.qt.io/browse/QTBUG-49824
  return QSharedPointer<T>(new T(std::forward<U>(par)...));
}

namespace vx {
class RefCountedObject;

/**
 * Make sure that the code is running on the main thread.
 */
VOXIECLIENT_EXPORT void checkOnMainThread(const char* what);

/**
 * Make sure that the code is *not* running on the main thread. This might be
 * usedful for avoiding deadlocks.
 */
VOXIECLIENT_EXPORT void checkNotOnMainThread(const char* what);
}  // namespace vx

// Allocate T and free it using deleteLater() when the reference count drops to
// zero.
template <typename T, typename... U>
static inline QSharedPointer<T> makeSharedQObject(U&&... par) {
  static_assert(
      std::is_base_of<QObject, T>::value,
      "makeSharedQObject requires its first template argument to be a QObject");

  vx::checkOnMainThread("makeSharedQObject");

  // For objects derived from RefCountedObject, the createBase() / create()
  // methods should be used instead of makeSharedQObject() (which would not call
  // initialize() etc.).
  static_assert(!std::is_base_of<vx::RefCountedObject, T>::value,
                "Trying to call makeSharedQObject for a vx::RefCountedObject");

  // TODO: Use deleteLater() only when the objects thread is not the current
  // thread? (Same then for RefCountedObject)

  return QSharedPointer<T>(new T(std::forward<U>(par)...),
                           [](QObject* obj) { obj->deleteLater(); });
}

namespace vx {
VOXIECLIENT_EXPORT QObject* getMainThreadObject();
VOXIECLIENT_EXPORT Qt::ConnectionType getConnectionTypeForExecute(QObject* obj);

// Execute function fun on the thread of object obj. If obj gets destroyed
// before fun is executed it will not be executed at all. The execution will
// always be delayed, even if the method is called from obj's thread.
template <typename T>
inline void enqueueOnThread(QObject* obj, T&& fun) {
  QObject srcObj;
  QObject::connect(&srcObj, &QObject::destroyed, obj, std::move(fun),
                   Qt::QueuedConnection);
}

template <typename T>
inline void enqueueOnMainThread(T&& fun) {
  enqueueOnThread(vx::getMainThreadObject(), std::move(fun));
}

namespace QtUtilPrivate {
VOXIECLIENT_EXPORT Q_NORETURN void throwFailedExecuteFunction();

template <typename T>
struct ExecuteOnThreadHelper {
  template <typename Func>
  static decltype(auto) execute(QObject* obj, Func&& fun) {
    std::exception_ptr error;
    bool executed = false;
    std::remove_reference_t<decltype(fun())> returnValue{};
    {
      QObject srcObj;
      QObject::connect(
          &srcObj, &QObject::destroyed, obj,
          [fun = std::move(fun), &error, &executed, &returnValue]() {
            try {
              returnValue = fun();
              executed = true;
            } catch (...) {
              error = std::current_exception();
            }
          },
          vx::getConnectionTypeForExecute(obj));
    }
    if (error) std::rethrow_exception(error);
    if (!executed) throwFailedExecuteFunction();
    return returnValue;
  }
};

template <>
struct ExecuteOnThreadHelper<void> {
  template <typename Func>
  static void execute(QObject* obj, Func&& fun) {
    std::exception_ptr error;
    bool executed = false;
    {
      QObject srcObj;
      QObject::connect(
          &srcObj, &QObject::destroyed, obj,
          [fun = std::move(fun), &error, &executed]() {
            try {
              fun();
              executed = true;
            } catch (...) {
              error = std::current_exception();
            }
          },
          vx::getConnectionTypeForExecute(obj));
    }
    if (error) std::rethrow_exception(error);
    if (!executed) throwFailedExecuteFunction();
  }
};

}  // namespace QtUtilPrivate

// Execute function fun on the thread of object obj. If obj gets destroyed
// before fun is executed it will not be executed at all. If the method is
// called from obj's thread, it will be executed directly, without being
// enqueued. If the method is called from another thread, it will wait until
// the function has executed.
template <typename T>
inline decltype(auto) executeOnThread(QObject* obj, T&& fun) {
  return QtUtilPrivate::ExecuteOnThreadHelper<decltype(fun())>::execute(
      obj, std::move(fun));
}

template <typename T>
inline decltype(auto) executeOnMainThread(T&& fun) {
  return executeOnThread<T>(vx::getMainThreadObject(), std::move(fun));
}

VOXIECLIENT_EXPORT void enqueueOnBackgroundThread(std::function<void()> fun);

/**
 * QRunnable subclass that supports being constructed
 * from a lambda (or any other callable object).
 */
template <typename Function>
class FunctionalRunnable : public QRunnable {
 public:
  FunctionalRunnable(Function function) : function(std::move(function)) {}

  void run() override { this->function(); }

 private:
  Function function;
};

template <typename Function>
FunctionalRunnable<Function>* functionalRunnable(Function function) {
  return new FunctionalRunnable<Function>(std::move(function));
}
}  // namespace vx


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class VpnClientConfiguration : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (VpnClientAddressPool != null)
            {
                writer.WritePropertyName("vpnClientAddressPool");
                writer.WriteObjectValue(VpnClientAddressPool);
            }
            if (VpnClientRootCertificates != null)
            {
                writer.WritePropertyName("vpnClientRootCertificates");
                writer.WriteStartArray();
                foreach (var item in VpnClientRootCertificates)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (VpnClientRevokedCertificates != null)
            {
                writer.WritePropertyName("vpnClientRevokedCertificates");
                writer.WriteStartArray();
                foreach (var item in VpnClientRevokedCertificates)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (VpnClientProtocols != null)
            {
                writer.WritePropertyName("vpnClientProtocols");
                writer.WriteStartArray();
                foreach (var item in VpnClientProtocols)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (VpnClientIpsecPolicies != null)
            {
                writer.WritePropertyName("vpnClientIpsecPolicies");
                writer.WriteStartArray();
                foreach (var item in VpnClientIpsecPolicies)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (RadiusServerAddress != null)
            {
                writer.WritePropertyName("radiusServerAddress");
                writer.WriteStringValue(RadiusServerAddress);
            }
            if (RadiusServerSecret != null)
            {
                writer.WritePropertyName("radiusServerSecret");
                writer.WriteStringValue(RadiusServerSecret);
            }
            if (RadiusServers != null)
            {
                writer.WritePropertyName("radiusServers");
                writer.WriteStartArray();
                foreach (var item in RadiusServers)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (AadTenant != null)
            {
                writer.WritePropertyName("aadTenant");
                writer.WriteStringValue(AadTenant);
            }
            if (AadAudience != null)
            {
                writer.WritePropertyName("aadAudience");
                writer.WriteStringValue(AadAudience);
            }
            if (AadIssuer != null)
            {
                writer.WritePropertyName("aadIssuer");
                writer.WriteStringValue(AadIssuer);
            }
            writer.WriteEndObject();
        }

        internal static VpnClientConfiguration DeserializeVpnClientConfiguration(JsonElement element)
        {
            AddressSpace vpnClientAddressPool = default;
            IList<VpnClientRootCertificate> vpnClientRootCertificates = default;
            IList<VpnClientRevokedCertificate> vpnClientRevokedCertificates = default;
            IList<VpnClientProtocol> vpnClientProtocols = default;
            IList<IpsecPolicy> vpnClientIpsecPolicies = default;
            string radiusServerAddress = default;
            string radiusServerSecret = default;
            IList<RadiusServer> radiusServers = default;
            string aadTenant = default;
            string aadAudience = default;
            string aadIssuer = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("vpnClientAddressPool"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    vpnClientAddressPool = AddressSpace.DeserializeAddressSpace(property.Value);
                    continue;
                }
                if (property.NameEquals("vpnClientRootCertificates"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<VpnClientRootCertificate> array = new List<VpnClientRootCertificate>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            array.Add(VpnClientRootCertificate.DeserializeVpnClientRootCertificate(item));
                        }
                    }
                    vpnClientRootCertificates = array;
                    continue;
                }
                if (property.NameEquals("vpnClientRevokedCertificates"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<VpnClientRevokedCertificate> array = new List<VpnClientRevokedCertificate>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            array.Add(VpnClientRevokedCertificate.DeserializeVpnClientRevokedCertificate(item));
                        }
                    }
                    vpnClientRevokedCertificates = array;
                    continue;
                }
                if (property.NameEquals("vpnClientProtocols"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<VpnClientProtocol> array = new List<VpnClientProtocol>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(new VpnClientProtocol(item.GetString()));
                    }
                    vpnClientProtocols = array;
                    continue;
                }
                if (property.NameEquals("vpnClientIpsecPolicies"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<IpsecPolicy> array = new List<IpsecPolicy>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            array.Add(IpsecPolicy.DeserializeIpsecPolicy(item));
                        }
                    }
                    vpnClientIpsecPolicies = array;
                    continue;
                }
                if (property.NameEquals("radiusServerAddress"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    radiusServerAddress = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("radiusServerSecret"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    radiusServerSecret = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("radiusServers"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<RadiusServer> array = new List<RadiusServer>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            array.Add(RadiusServer.DeserializeRadiusServer(item));
                        }
                    }
                    radiusServers = array;
                    continue;
                }
                if (property.NameEquals("aadTenant"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    aadTenant = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("aadAudience"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    aadAudience = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("aadIssuer"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    aadIssuer = property.Value.GetString();
                    continue;
                }
            }
            return new VpnClientConfiguration(vpnClientAddressPool, vpnClientRootCertificates, vpnClientRevokedCertificates, vpnClientProtocols, vpnClientIpsecPolicies, radiusServerAddress, radiusServerSecret, radiusServers, aadTenant, aadAudience, aadIssuer);
        }
    }
}


text:
import { setOwner } from '@ember/-internals/owner';
import { runDestroy, buildOwner, moduleFor, AbstractTestCase } from 'internal-test-helpers';
import Service, { inject as injectService } from '@ember/service';
import { Object as EmberObject } from '@ember/-internals/runtime';
import EmberRoute from '../../lib/system/route';
import { defineProperty } from '../../../metal';

let route, routeOne, routeTwo, lookupHash;

moduleFor(
  'Route',
  class extends AbstractTestCase {
    constructor() {
      super();
      route = EmberRoute.create();
    }

    teardown() {
      super.teardown();
      runDestroy(route);
      route = routeOne = routeTwo = lookupHash = undefined;
    }

    ['@test default store utilizes the container to acquire the model factory'](assert) {
      assert.expect(4);

      let Post = EmberObject.extend();
      let post = {};

      Post.reopenClass({
        find() {
          return post;
        },
      });

      let ownerOptions = {
        ownerOptions: {
          hasRegistration() {
            return true;
          },
          factoryFor(fullName) {
            assert.equal(fullName, 'model:post', 'correct factory was looked up');

            return {
              class: Post,
              create() {
                return Post.create();
              },
            };
          },
        },
      };

      let owner = buildOwner(ownerOptions);
      setOwner(route, owner);

      // Override the computed property by redefining it
      defineProperty(route, '_qp', null, null);

      assert.equal(route.model({ post_id: 1 }), post);
      assert.equal(route.findModel('post', 1), post, '#findModel returns the correct post');

      runDestroy(owner);
    }

    ["@test 'store' can be injected by data persistence frameworks"](assert) {
      assert.expect(8);
      runDestroy(route);

      let owner = buildOwner();

      let post = {
        id: 1,
      };

      let Store = EmberObject.extend({
        find(type, value) {
          assert.ok(true, 'injected model was called');
          assert.equal(type, 'post', 'correct type was called');
          assert.equal(value, 1, 'correct value was called');
          return post;
        },
      });

      owner.register('route:index', EmberRoute);
      owner.register('store:main', Store);

      owner.inject('route', 'store', 'store:main');

      route = owner.lookup('route:index');

      assert.equal(route.model({ post_id: 1 }), post, '#model returns the correct post');
      assert.equal(route.findModel('post', 1), post, '#findModel returns the correct post');

      runDestroy(owner);
    }

    ["@test assert if 'store.find' method is not found"]() {
      runDestroy(route);

      let owner = buildOwner();
      let Post = EmberObject.extend();

      owner.register('route:index', EmberRoute);
      owner.register('model:post', Post);

      route = owner.lookup('route:index');

      expectAssertion(function () {
        route.findModel('post', 1);
      }, 'Post has no method `find`.');

      runDestroy(owner);
    }

    ['@test asserts if model class is not found']() {
      runDestroy(route);

      let owner = buildOwner();
      owner.register('route:index', EmberRoute);

      route = owner.lookup('route:index');

      expectAssertion(function () {
        route.model({ post_id: 1 });
      }, /You used the dynamic segment post_id in your route undefined, but <Ember.Object:ember\d+>.Post did not exist and you did not override your route's `model` hook./);

      runDestroy(owner);
    }

    ["@test 'store' does not need to be injected"](assert) {
      runDestroy(route);

      let owner = buildOwner();

      owner.register('route:index', EmberRoute);

      route = owner.lookup('route:index');

      ignoreAssertion(function () {
        route.model({ post_id: 1 });
      });

      assert.ok(true, 'no error was raised');

      runDestroy(owner);
    }

    ["@test modelFor doesn't require the router"](assert) {
      let owner = buildOwner();
      setOwner(route, owner);

      let foo = { name: 'foo' };

      let FooRoute = EmberRoute.extend({
        currentModel: foo,
      });

      owner.register('route:foo', FooRoute);

      assert.strictEqual(route.modelFor('foo'), foo);

      runDestroy(owner);
    }

    ["@test modelFor doesn't require the routerMicrolib"](assert) {
      let route = EmberRoute.create({
        _router: { _routerMicrolib: null },
      });

      let owner = buildOwner();
      setOwner(route, owner);

      let foo = { name: 'foo' };

      let FooRoute = EmberRoute.extend({
        currentModel: foo,
      });

      owner.register('route:foo', FooRoute);

      assert.strictEqual(route.modelFor('foo'), foo);

      runDestroy(owner);
    }

    ['@test .send just calls an action if the router is absent'](assert) {
      assert.expect(7);
      let route = EmberRoute.extend({
        actions: {
          returnsTrue(foo, bar) {
            assert.equal(foo, 1);
            assert.equal(bar, 2);
            assert.equal(this, route);
            return true;
          },

          returnsFalse() {
            assert.ok(true, 'returnsFalse was called');
            return false;
          },
        },
      }).create();

      assert.equal(route.send('returnsTrue', 1, 2), true);
      assert.equal(route.send('returnsFalse'), false);
      assert.equal(route.send('nonexistent', 1, 2, 3), undefined);

      runDestroy(route);
    }

    ['@test .send just calls an action if the routers internal router property is absent'](assert) {
      assert.expect(7);
      let route = EmberRoute.extend({
        router: {},
        actions: {
          returnsTrue(foo, bar) {
            assert.equal(foo, 1);
            assert.equal(bar, 2);
            assert.equal(this, route);
            return true;
          },

          returnsFalse() {
            assert.ok(true, 'returnsFalse was called');
            return false;
          },
        },
      }).create();

      assert.equal(true, route.send('returnsTrue', 1, 2));
      assert.equal(false, route.send('returnsFalse'));
      assert.equal(undefined, route.send('nonexistent', 1, 2, 3));

      runDestroy(route);
    }

    ['@test .send asserts if called on a destroyed route']() {
      route.routeName = 'rip-alley';
      runDestroy(route);

      expectAssertion(() => {
        route.send('trigger-me-dead');
      }, "Attempted to call .send() with the action 'trigger-me-dead' on the destroyed route 'rip-alley'.");
    }
  }
);

moduleFor(
  'Route serialize',
  class extends AbstractTestCase {
    constructor() {
      super();
      route = EmberRoute.create();
    }

    teardown() {
      runDestroy(route);
    }

    ['@test returns the models properties if params does not include *_id'](assert) {
      let model = { id: 2, firstName: 'Ned', lastName: 'Ryerson' };

      assert.deepEqual(
        route.serialize(model, ['firstName', 'lastName']),
        { firstName: 'Ned', lastName: 'Ryerson' },
        'serialized correctly'
      );
    }

    ['@test returns model.id if params include *_id'](assert) {
      let model = { id: 2 };

      assert.deepEqual(route.serialize(model, ['post_id']), { post_id: 2 }, 'serialized correctly');
    }

    ['@test returns checks for existence of model.post_id before trying model.id'](assert) {
      let model = { post_id: 3 };

      assert.deepEqual(route.serialize(model, ['post_id']), { post_id: 3 }, 'serialized correctly');
    }

    ['@test returns undefined if model is not set'](assert) {
      assert.equal(route.serialize(undefined, ['post_id']), undefined, 'serialized correctly');
    }
  }
);

moduleFor(
  'Route interaction',
  class extends AbstractTestCase {
    constructor() {
      super();

      let owner = {
        lookup(fullName) {
          return lookupHash[fullName];
        },
      };

      routeOne = EmberRoute.create({ routeName: 'one' });
      routeTwo = EmberRoute.create({ routeName: 'two' });

      setOwner(routeOne, owner);
      setOwner(routeTwo, owner);

      lookupHash = {
        'route:one': routeOne,
        'route:two': routeTwo,
      };
    }

    teardown() {
      runDestroy(routeOne);
      runDestroy(routeTwo);
    }

    ['@test route._qp does not crash if the controller has no QP, or setProperties'](assert) {
      lookupHash['controller:test'] = {};

      routeOne.controllerName = 'test';
      let qp = routeOne.get('_qp');

      assert.deepEqual(qp.map, {}, 'map should be empty');
      assert.deepEqual(qp.propertyNames, [], 'property names should be empty');
      assert.deepEqual(qp.qps, [], 'qps is should be empty');
    }

    ["@test controllerFor uses route's controllerName if specified"](assert) {
      let testController = {};
      lookupHash['controller:test'] = testController;

      routeOne.controllerName = 'test';

      assert.equal(routeTwo.controllerFor('one'), testController);
    }
  }
);

moduleFor(
  'Route injected properties',
  class extends AbstractTestCase {
    ['@test services can be injected into routes'](assert) {
      let owner = buildOwner();

      owner.register(
        'route:application',
        EmberRoute.extend({
          authService: injectService('auth'),
        })
      );

      owner.register('service:auth', Service.extend());

      let appRoute = owner.lookup('route:application');
      let authService = owner.lookup('service:auth');

      assert.equal(authService, appRoute.get('authService'), 'service.auth is injected');
    }
  }
);

moduleFor(
  'Route with engines',
  class extends AbstractTestCase {
    ["@test paramsFor considers an engine's mountPoint"](assert) {
      let router = {
        _deserializeQueryParams() {},
        _routerMicrolib: {
          state: {
            routeInfos: [{ name: 'posts' }],
            params: {
              'foo.bar': { a: 'b' },
              'foo.bar.posts': { c: 'd' },
            },
          },
        },
      };

      let engineInstance = buildOwner({
        ownerOptions: {
          routable: true,

          mountPoint: 'foo.bar',

          lookup(name) {
            if (name === 'route:posts') {
              return postsRoute;
            } else if (name === 'route:application') {
              return applicationRoute;
            }
          },
        },
      });

      let applicationRoute = EmberRoute.create({
        _router: router,
        routeName: 'application',
        fullRouteName: 'foo.bar',
      });
      let postsRoute = EmberRoute.create({
        _router: router,
        routeName: 'posts',
        fullRouteName: 'foo.bar.posts',
      });
      let route = EmberRoute.create({ _router: router });

      setOwner(applicationRoute, engineInstance);
      setOwner(postsRoute, engineInstance);
      setOwner(route, engineInstance);

      assert.deepEqual(
        route.paramsFor('application'),
        { a: 'b' },
        'params match for root `application` route in engine'
      );
      assert.deepEqual(
        route.paramsFor('posts'),
        { c: 'd' },
        'params match for `posts` route in engine'
      );
    }

    ["@test modelFor considers an engine's mountPoint"](assert) {
      let applicationModel = { id: '1' };
      let postsModel = { id: '2' };

      let router = {
        _routerMicrolib: {
          activeTransition: {
            resolvedModels: {
              'foo.bar': applicationModel,
              'foo.bar.posts': postsModel,
            },
          },
        },
      };

      let engineInstance = buildOwner({
        ownerOptions: {
          routable: true,

          mountPoint: 'foo.bar',

          lookup(name) {
            if (name === 'route:posts') {
              return postsRoute;
            } else if (name === 'route:application') {
              return applicationRoute;
            }
          },
        },
      });

      let applicationRoute = EmberRoute.create({
        _router: router,
        routeName: 'application',
      });
      let postsRoute = EmberRoute.create({
        _router: router,
        routeName: 'posts',
      });
      let route = EmberRoute.create({ _router: router });

      setOwner(applicationRoute, engineInstance);
      setOwner(postsRoute, engineInstance);
      setOwner(route, engineInstance);

      assert.strictEqual(route.modelFor('application'), applicationModel);
      assert.strictEqual(route.modelFor('posts'), postsModel);
    }

    ["@test transitionTo considers an engine's mountPoint"](assert) {
      let router = {
        transitionTo(route) {
          return route;
        },
      };

      let engineInstance = buildOwner({
        ownerOptions: {
          routable: true,
          mountPoint: 'foo.bar',
        },
      });

      let route = EmberRoute.create({ _router: router });
      setOwner(route, engineInstance);

      assert.strictEqual(
        route.transitionTo('application'),
        'foo.bar.application',
        'properly prefixes application route'
      );
      assert.strictEqual(
        route.transitionTo('posts'),
        'foo.bar.posts',
        'properly prefixes child routes'
      );
      assert.throws(() => route.transitionTo('/posts'), 'throws when trying to use a url');

      let queryParams = {};
      assert.strictEqual(
        route.transitionTo(queryParams),
        queryParams,
        'passes query param only transitions through'
      );
    }

    ["@test intermediateTransitionTo considers an engine's mountPoint"](assert) {
      let lastRoute;
      let router = {
        intermediateTransitionTo(route) {
          lastRoute = route;
        },
      };

      let engineInstance = buildOwner({
        ownerOptions: {
          routable: true,
          mountPoint: 'foo.bar',
        },
      });

      let route = EmberRoute.create({ _router: router });
      setOwner(route, engineInstance);

      route.intermediateTransitionTo('application');
      assert.strictEqual(lastRoute, 'foo.bar.application', 'properly prefixes application route');

      route.intermediateTransitionTo('posts');
      assert.strictEqual(lastRoute, 'foo.bar.posts', 'properly prefixes child routes');

      assert.throws(
        () => route.intermediateTransitionTo('/posts'),
        'throws when trying to use a url'
      );

      let queryParams = {};
      route.intermediateTransitionTo(queryParams);
      assert.strictEqual(lastRoute, queryParams, 'passes query param only transitions through');
    }

    ["@test replaceWith considers an engine's mountPoint"](assert) {
      let router = {
        replaceWith(route) {
          return route;
        },
      };

      let engineInstance = buildOwner({
        ownerOptions: {
          routable: true,
          mountPoint: 'foo.bar',
        },
      });

      let route = EmberRoute.create({ _router: router });
      setOwner(route, engineInstance);

      assert.strictEqual(
        route.replaceWith('application'),
        'foo.bar.application',
        'properly prefixes application route'
      );
      assert.strictEqual(
        route.replaceWith('posts'),
        'foo.bar.posts',
        'properly prefixes child routes'
      );
      assert.throws(() => route.replaceWith('/posts'), 'throws when trying to use a url');

      let queryParams = {};
      assert.strictEqual(
        route.replaceWith(queryParams),
        queryParams,
        'passes query param only transitions through'
      );
    }
  }
);


text:
package updateprocessors_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	apiv3 "github.com/projectcalico/libcalico-go/lib/apis/v3"
	"github.com/projectcalico/libcalico-go/lib/backend/model"
	"github.com/projectcalico/libcalico-go/lib/backend/syncersv1/updateprocessors"
	"github.com/projectcalico/libcalico-go/lib/net"
	"github.com/projectcalico/libcalico-go/lib/numorstring"
)

var _ = Describe("Test the HostEndpoint update processor", func() {
	name1 := "name1"
	name2 := "name2"
	hn1 := "host1"
	hn2 := "host2"
	v3HostEndpointKey1 := model.ResourceKey{
		Kind: apiv3.KindHostEndpoint,
		Name: name1,
	}
	v3HostEndpointKey2 := model.ResourceKey{
		Kind: apiv3.KindHostEndpoint,
		Name: name2,
	}
	v1HostEndpointKey1 := model.HostEndpointKey{
		Hostname:   hn1,
		EndpointID: name1,
	}
	v1HostEndpointKey2 := model.HostEndpointKey{
		Hostname:   hn2,
		EndpointID: name2,
	}

	It("should handle conversion of valid HostEndpoints", func() {
		up := updateprocessors.NewHostEndpointUpdateProcessor()

		By("converting a HostEndpoint with minimum configuration")
		res := apiv3.NewHostEndpoint()
		res.Name = v3HostEndpointKey1.Name
		res.Spec.Node = hn1
		res.Spec.InterfaceName = name1

		kvps, err := up.Process(&model.KVPair{
			Key:      v3HostEndpointKey1,
			Value:    res,
			Revision: "abcde",
		})
		Expect(err).NotTo(HaveOccurred())
		Expect(kvps).To(HaveLen(1))
		Expect(kvps[0]).To(Equal(&model.KVPair{
			Key: v1HostEndpointKey1,
			Value: &model.HostEndpoint{
				Name:  name1,
				Ports: []model.EndpointPort{},
			},
			Revision: "abcde",
		}))

		By("adding another HostEndpoint with a full configuration")
		res = apiv3.NewHostEndpoint()
		res.Name = v3HostEndpointKey2.Name
		res.Labels = map[string]string{"testLabel": "label"}
		res.Spec.Node = hn2
		res.Spec.InterfaceName = name2
		res.Spec.ExpectedIPs = []string{"10.100.10.1"}
		expectedIpv4 := *net.ParseIP("10.100.10.1")
		res.Spec.Profiles = []string{"testProfile"}
		res.Spec.Ports = []apiv3.EndpointPort{
			apiv3.EndpointPort{
				Name:     "portname",
				Protocol: numorstring.ProtocolFromInt(uint8(30)),
				Port:     uint16(8080),
			},
		}

		kvps, err = up.Process(&model.KVPair{
			Key:      v3HostEndpointKey2,
			Value:    res,
			Revision: "1234",
		})
		Expect(err).NotTo(HaveOccurred())
		Expect(kvps).To(Equal([]*model.KVPair{
			{
				Key: v1HostEndpointKey2,
				Value: &model.HostEndpoint{
					Name:              name2,
					ExpectedIPv4Addrs: []net.IP{expectedIpv4},
					Labels:            map[string]string{"testLabel": "label"},
					ProfileIDs:        []string{"testProfile"},
					Ports: []model.EndpointPort{
						model.EndpointPort{
							Name:     "portname",
							Protocol: numorstring.ProtocolFromInt(uint8(30)),
							Port:     uint16(8080),
						},
					},
				},
				Revision: "1234",
			},
		}))

		By("deleting the first host endpoint")
		kvps, err = up.Process(&model.KVPair{
			Key: v3HostEndpointKey1,
		})
		Expect(err).NotTo(HaveOccurred())
		Expect(kvps).To(Equal([]*model.KVPair{
			{
				Key: v1HostEndpointKey1,
			},
		}))

		By("clearing the cache (by starting sync) and failing to delete the second host endpoint")
		up.OnSyncerStarting()
		kvps, err = up.Process(&model.KVPair{
			Key: v3HostEndpointKey2,
		})
		Expect(err).To(HaveOccurred())
	})

	It("should fail to convert an invalid resource", func() {
		up := updateprocessors.NewHostEndpointUpdateProcessor()

		By("trying to convert with the wrong key type")
		res := apiv3.NewHostEndpoint()
		res.Spec.Node = hn1

		_, err := up.Process(&model.KVPair{
			Key: model.GlobalBGPPeerKey{
				PeerIP: net.MustParseIP("1.2.3.4"),
			},
			Value:    res,
			Revision: "abcde",
		})
		Expect(err).To(HaveOccurred())

		By("trying to convert with the wrong value type")
		wres := apiv3.NewIPPool()

		_, err = up.Process(&model.KVPair{
			Key:      v3HostEndpointKey1,
			Value:    wres,
			Revision: "abcde",
		})
		Expect(err).To(HaveOccurred())
	})
})


text:
namespace bbg {

Util::Util(void)
{
	srand (time(NULL));
}

Util::~Util(void)
{
}

string Util::GetRandomQuote()
{
	//https://www.cs.cmu.edu/~pattis/quotations.html
	std::vector<string> quotes;
	quotes.push_back("The question of whether a computer can think is no more interesting than the question of whether a submarine can swim.");
	quotes.push_back("C is quirky, flawed, and an enormous success.");
	quotes.push_back("An algorithm must be seen to be believed.");
	quotes.push_back("I don't know how many of you have ever met Dijkstra, but you probably know that arrogance in computer science is measured in nano-Dijkstras.");
	quotes.push_back("Suppose whatever we can recognize we can find. We can if P=NP.");
	quotes.push_back("The most important property of a program is whether it accomplishes the intention of its user.");
	quotes.push_back("Is it possible that software is not like anything else, that it is meant to be discarded: that the whole point is to always see it as a soap bubble?");
	quotes.push_back("Programs must be written for people to read, and only incidentally for machines to execute.");
	quotes.push_back("Good teaching is more a giving of the right questions than a giving of the right answers.");
	quotes.push_back("Computer Science is a science of abstraction -creating the right model for a problem and devising the appropriate mechanizable techniques to solve it.");
	quotes.push_back("Eighty percent of success is showing up.");
	quotes.push_back("Don't worry about people stealing your ideas. If your ideas are any good, you'll have to ram them down people's throats.");
	quotes.push_back("More is different.");
	quotes.push_back("Today, most software exists, not to solve a problem, but to interface with other software.");
	quotes.push_back("All programmers are playwrights and all computers are lousy actors.");
	quotes.push_back("Bad code isn't bad, its just misunderstood.");
	quotes.push_back("Debugging is anticipated with distaste, performed with reluctance, and bragged about forever.");
	quotes.push_back("Experience is a poor teacher: it gives its tests before it teaches its lessons.");
	quotes.push_back("If I had eight hours to chop down a tree, I would spend 6 hours sharpening an axe.");
	quotes.push_back("If you understand what you're doing, you're not learning anything.");
	quotes.push_back("In theory, there is no difference between theory and practice, but not in practice.");
	quotes.push_back("It is easier to measure something than to understand what you have measured.");
	quotes.push_back("Measure twice, cut once.");
	quotes.push_back("Microsoft, where quality is job 1.1");
	quotes.push_back("Programs for sale: Fast, Reliable, Cheap: choose two.");
	quotes.push_back("Real programmers don't comment their code. If it was hard to write, it should be hard to understand.");
	quotes.push_back("Recurses! Called again.");
	quotes.push_back("The person who knows HOW will always have a job. The person who knows WHY will always be his/her boss.");
	quotes.push_back("The sooner you get behind in your work, the more time you have to catch up.");
	quotes.push_back("There are only 10 different kinds of people in the world: those who know binary and those who don't.");
	quotes.push_back("Think (design) globally; act (code) locally.");
	quotes.push_back("Think twice, code once.");
	quotes.push_back("Time is an excellent teacher, but eventually it kills all its students.");
	quotes.push_back("Weeks of programming can save you hours of planning.");
	quotes.push_back("When a programming language is created that allows programmers to program in simple English, it will be discovered that programmers cannot speak English.");
	quotes.push_back("Why do we never have time to do it right, but always have time to do it over?");
	quotes.push_back("By viewing the old we learn the new.");
	quotes.push_back("Give me a fish and I eat for a day. Teach me to fish and I eat for a lifetime.");
	quotes.push_back("He who asks is a fool for five minutes; he who does not ask remains a fool forever.");
	quotes.push_back("Teachers open the door, but you must enter by yourself.");
	quotes.push_back("Tell me and I forget. Show me and I remember. Involve me and I understand.");
	quotes.push_back("The first step towards wisdom is calling things by their right names.");
	quotes.push_back("The best software is simple, elegant, and full of drama - Grady Booch");
	int sz = quotes.size();
	int m = rand();
	int n = m % sz;
	//printf("n=%d; m=%d\n",n,m);
	return quotes[n];
}

void Util::GenerateRandomChars(char *s, const int len)
{
	srand (time(NULL));
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < len; ++i) {
		int n = (sizeof(alphanum) - 1);
		int m = rand();
		int t = m % n;
        s[i] = alphanum[t];
    }
    s[len] = 0;
}

std::wstring Util::CreateGuid()
{
	::GUID guid;
	(void)::CoCreateGuid(&guid);
	//::UuidCreate(&guid);
	//sizeof char array provides count of chars (+2 for braces)(+1 for null)
	wchar_t buff[cchGUID + 2 + 1];
	//sizeof(x)/sizeof(*x) yields count of elements (cch)
	//the return value includes the null terminator
	auto ret = ::StringFromGUID2(guid, buff, sizeof(buff)/sizeof(*buff));
	//create string without {} -- minus 3 for null and {}
	std::wstring retval;
	if (ret > 3)
	{
		retval.reserve(cchGUID+1);
		retval.assign(&buff[1], ret-3);
	}
	transform( retval.begin(), retval.end(), retval.begin(), towlower);
	return retval;
}

std::vector<string> Util::Split(char* str,const char* delim)
{
    char* saveptr;
    char* token = strtok_s(str,delim, &saveptr);
    vector<string> result;
    while(token != NULL)
    {
        result.push_back(token);
        token = strtok_s(NULL,delim, &saveptr);
    }
    return result;
}

string Util::Token(int len)
{
	string t="";
	for(int i=0;i<len;i++)
	{
		switch(rand()%3)
		{
			case 0:
				t+=('0'+rand()%10);
				break;
			case 1:
				t+=('A'+rand()%26);
				break;
			case 2:
				t+=('a'+rand()%26);
				break;
		}
	}
	return t;
}

std::vector<string> Util::GatherMessages(char* str, int len)
{
	std::vector<string> list;
	string message;
	BOOL isValid = false;
	for(int i=0; i<len; i++)
	{
		isValid = false;
		while(str[i]!=';' && i<len)
		{
			message = message + str[i];
			i++;
		}
		if (str[i]==';')
			isValid = true;
		if (i<len)
		{
			message = message + str[i];
			i++;
		}
		if (message.size() > 0 && isValid)
			list.push_back(message);
		message = "";
	}
	return list;
}

std::vector<string> Util::Parse(char* str,const char* delim, int len)
{
	std::vector<string> list;
	string token;
	for(int i=0; i<len; i++ )
	{
		while(str[i]==' ' && i<len)
		{
			i++;
		}
		token = "";
		if (str[i] == '\"' || str[i] == '\'')
		{
			if (str[i] == '\"' )
			{
				token = "";
				i++;
				while(str[i] !='\"' && i<len)
				{
					token = token + str[i];
					i++;
				}
				if (i<len) i++;
				list.push_back(token);
			}
			if (str[i] == '\'' )
			{
				token = "";
				i++;
				while(str[i] !='\'' && i<len)
				{
					token = token + str[i];
					i++;
				}
				if (i<len) i++;
				list.push_back(token);
			}
			if (str[i] != ' ' )
			{
				token = "";
				while(str[i] !=' ' && i<len)
				{
					token = token + str[i];
					i++;
				}
			}
		}
		else
		{
			token = "";
			while((str[i] !=' ' && str[i] !=';') && i<len)
			{
				token = token + str[i];
				i++;
			}
			if (str[i] ==';' && i<len)
			{
				i++;
			}
			list.push_back(token);
		}
	}
	return list;
}

}


text:
L.AGS.Tools.Identify = L.AGS.Tools.extend({
  options: {
    f: 'json',
    sr: '4326',
    layers: 'top',
    returnGeometry: true,
    tolerance: 1
  },

  initialize: function(layer, options, callback) {
    this._layer = layer;

    if (typeof options === 'function') {
      this._callback = options;
      var options = {};
    } else {
      this._callback = callback;
    }

    L.Util.setOptions(this, options);
    this.parseLayerDefs();
    this.setMapExtent();
    this.setImageDisplay();
  },

  parseGeometry: function(geometry) {
    if (typeof this.options.geometryType === 'undefined') {
      if (typeof geometry === 'string') {
        var len = geometry.split(',').length;
        if (len == 2) {
          this.options.geometryType = 'esriGeometryPoint';
        } else if (len == 4) {
          this.options.geometryType = 'esriGeometryEnvelope';
        }
      } else if (geometry instanceof Array) {
        if (typeof geometry[1][0] === 'number') {
          this.options.geometryType = 'esriGeometryPolyline';
        } else if (geometry[1][0] instanceof Array) {
          this.options.geometryType = 'esriGeometryPolygon';
        }
      } else if (typeof geometry === 'object') {
        if (typeof geometry.x !== 'undefined') {
          this.options.geometryType = 'esriGeometryPoint';
        }
      }
    }

    this.options.geometry = geometry;
  },

  parseLayerDefs: function() {
    var defType = typeof this.options.layerDefs;

    if (defType !== 'undefined') {
      if (defType === 'object' && !(this.options.layerDefs instanceof Array)) {
        this.options.layerDefs = JSON.stringify(this.options.layerDefs);
      } else if (this.options.layerDefs instanceof Array) {
        var defs = {};

        for (var i = 0, len = this.options.layerDefs.length; i < len; i++) {
          if (this.options.layerDefs[i]) {
            defs[i] = this.options.layerDefs[i];
          }
        }

        this.options.layerDefs = JSON.stringify(defs);
      }
    }

    return;
  },

  setImageDisplay: function() {
    if (typeof this.options.imageDisplay === 'undefined') {
      var mapSize = this._layer._map.getSize();
      this.options.imageDisplay = mapSize.x + ',' + mapSize.y + ',96';
    }
    return;
  },

  setMapExtent: function() {
    if (typeof this.options.mapExtent === 'undefined') {
      var bounds = this._layer._map.getBounds();
      this.options.mapExtent = bounds._northEast.lng + ',' + bounds._southWest.lat + ',' + bounds._southWest.lng + ',' + bounds._northEast.lat;
    }
  },

  execute: function(geometry) {
    this.parseGeometry(geometry);

    var _t = this;

    var url = this._layer._url + '/identify';

    var getJsonP = function(url, params) {
      window.parseResponse = function(response) {
        document.body.removeChild(document.getElementById('getJsonP'));
        _t.findBestFeature(response, geometry);
        delete window.parseResponse;
      };

      this.options.f = 'pjson';
      var script = document.createElement('script');
      script.id = 'getJsonP';
      script.src = url + L.Util.getParamString(this.options) + '&callback=parseResponse';
      document.body.appendChild(script);
    };

    var findBestFeature = function(response, clickGeometry) {
      var clickGeometry = clickGeometry.split(','),
          clickPoint = new L.LatLng(clickGeometry[1], clickGeometry[0]),
          map = _t._layer._map;

      response = JSON.parse(response);

      if (response.results instanceof Array) {
        if (response.results.length == 1) {
          if (typeof _t._callback !== 'undefined') {
            _t._callback(response.results[0]);
          } // check for callback?
        } else if (response.results.length > 1) {
          var bestGeom = {
            type: null,
            dist: 1000000,
            index: null
          };

          for (var i = 0, len = response.results.length; i < len; i++) {
            if (typeof response.results[i] !== 'undefined') {
              var attrs = response.results[i].attributes,
                  geom = response.results[i].geometry;

              if (geom.hasOwnProperty('x') && geom.hasOwnProperty('y')) {
                var point = new L.LatLng(geom.y, geom.x),
                    dist = point.distanceTo(clickPoint);

                if (dist < bestGeom.dist) {
                  bestGeom.type = 'point';
                  bestGeom.dist = dist;
                  bestGeom.index = i;
                }
              } else if (geom.hasOwnPropety('rings')) {
                var vertices = [],
                    rings = geom.rings;

                for (var j = 0, len = rings.length; j < len; j++) {
                  vertices.push(new L.LatLng(rings[0][j][1], rings[0][j][0]));
                }

                var inPoly = false,
                    l = vertices.length - 1;

                for (var k = 0, len = vertices.length; k < len; k++) {
                  var vLat1 = vertices[k].lat,
                      vLng1 = vertices[k].lng,
                      vLat2 = vertices[l].lat,
                      vLng2 = vertices[l].lng,
                      pLat = clickPoint.lat,
                      pLng = clickPoint.lng;

                  if (vLng1 < pLng && vLng2 >= pLng || vLng2 < pLng && vLng1 >= pLng) {
                    if (vLat1 + (pLng - vLng1) / (vLng2 - vLng1) * (vLat2 - vLat1) < pLat) {
                      inPoly = !inPoly;
                    }
                  }

                  l = k;
                }

                if (inPoly) {
                  bestGeom.type = 'polygon';
                  bestGeom.index = i;
                  break;
                }
              }
            }
          }
          var result = response.results[bestGeom.index];

          if (typeof _t._callback !== 'undefined') {
            _t._callback(result);
          } // check for callback?
        }
      }
    };

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        if (xhr.status == 400 || xhr.status == 0) {
          getJsonP(url, this.options);
        } else if (xhr.status == 200 || xhr.status == 302) {
          findBestFeature(xhr.responseText, geometry);
        }
      }
    };

    formData = L.Util.getParamString(this.options).split('?')[1];

    if ('XDomainRequest' in window) {
      var xdr = new XDomainRequest();
      xdr.onerror = function() {
        xdr.abort();
        getJsonP(url, this.options);
      };
      xdr.onload = function() {
        setToken(xdr.responseText);
      };
      xdr.open('POST', url, true);
      xdr.send(formData);
    } else {
      xhr.open('POST', url, true);

      if (typeof formData === 'string') {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      }

      xhr.send(formData);
    }
  }
});


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lib.Web.Mvc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tomasz Pęczek")]
[assembly: AssemblyProduct("Lib.Web.Mvc")]
[assembly: AssemblyCopyright("Copyright © 2009 - 2015 Tomasz Pęczek")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
[assembly: ComVisible(false)]
[assembly: Guid("68e6372a-38aa-427a-b5f8-1952175d5ccd")]
[assembly: AssemblyVersion("6.6.0.0")]
[assembly: AssemblyFileVersion("6.6.0.0")]


text:
package tc

import (
	"database/sql"
	"errors"
	"strings"

	"github.com/apache/trafficcontrol/lib/go-util"
)

type SteeringTarget struct {
	DeliveryService   DeliveryServiceName `json:"deliveryService" db:"deliveryservice_name"`
	DeliveryServiceID int                 `json:"deliveryServiceId" db:"deliveryservice"`
	Target            DeliveryServiceName `json:"target" db:"target_name"`
	TargetID          int                 `json:"targetId" db:"target"`
	Type              string              `json:"type" db:"type"`      // TODO enum?
	TypeID            int                 `json:"typeId" db:"type_id"` // TODO enum?
	Value             util.JSONIntStr     `json:"value" db:"value"`
}

type SteeringTargetNullable struct {
	DeliveryService   *DeliveryServiceName `json:"deliveryService" db:"deliveryservice_name"`
	DeliveryServiceID *uint64              `json:"deliveryServiceId" db:"deliveryservice"`
	Target            *DeliveryServiceName `json:"target" db:"target_name"`
	TargetID          *uint64              `json:"targetId" db:"target"`
	Type              *string              `json:"type" db:"type_name"` // TODO enum?
	TypeID            *int                 `json:"typeId" db:"type_id"` // TODO enum?
	Value             *util.JSONIntStr     `json:"value" db:"value"`
}

func (st SteeringTargetNullable) Validate(tx *sql.Tx) error {
	errs := []string{}
	if st.TypeID == nil {
		errs = append(errs, "missing typeId")
	}
	valid, err := ValidateTypeID(tx, st.TypeID, "steering_target")
	if valid == "" {
		errs = append(errs, err.Error())
	}
	if st.Value == nil {
		errs = append(errs, "missing value")
	}
	if len(errs) > 0 {
		return errors.New(strings.Join(errs, "; "))
	}
	return nil
}


text:
package org.olat.ims.qti.process;

import java.util.Date;

/**
 */
public interface Persister {

	public boolean exists();

	public Date getLastModified();

	public void persist(Object o, String info);

	public Object toRAM();

	public void cleanUp();
}


text:
package org.hisp.dhis.reporting.reportviewer.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import org.hisp.dhis.util.ContextUtils;
import org.springframework.core.io.ClassPathResource;

import com.opensymphony.xwork2.Action;

/**
 * @author Lars Helge Overland
 */
public class GetReportTemplateAction
    implements Action
{
    private static final String TEMPLATE_JASPER = "jasper-report-template.jrxml";
    private static final String TEMPLATE_HTML = "html-report-template.html";

    private static final String TYPE_JASPER = "jasper";
    private static final String TYPE_HTML = "html";

    private String type;

    public void setType( String type )
    {
        this.type = type;
    }

    @Override
    public String execute()
        throws Exception
    {
        HttpServletResponse response = ServletActionContext.getResponse();

        Map<String, String> typeTemplateMap = new HashMap<>();
        typeTemplateMap.put( TYPE_JASPER, TEMPLATE_JASPER );
        typeTemplateMap.put( TYPE_HTML, TEMPLATE_HTML );

        Map<String, String> typeContentTypeMap = new HashMap<>();
        typeContentTypeMap.put( TYPE_JASPER, ContextUtils.CONTENT_TYPE_XML );
        typeContentTypeMap.put( TYPE_HTML, ContextUtils.CONTENT_TYPE_HTML );

        if ( type != null & typeTemplateMap.containsKey( type ) )
        {
            String template = typeTemplateMap.get( type );
            String contentType = typeContentTypeMap.get( type );

            ContextUtils.configureResponse( response, contentType, false, template, true );

            IOUtils.copy( new BufferedInputStream( new ClassPathResource( template ).getInputStream() ),
                new BufferedOutputStream( response.getOutputStream() ) );
        }

        return SUCCESS;
    }
}


text:
<?php include(APPPATH.'views/includes/header.php'); ?>
<?php include(APPPATH.'views/includes/team-rank.php'); ?>

		<?php include(APPPATH.'views/includes/left-menu.php'); ?>

		<?php foreach($upcoming_challenge as $list_challenge){ ?>
		<div class="bg-post post-item" id="<?php echo md5($list_challenge['challenge_id']); ?>">

				<a href="<?php echo base_url().'team/profile/'.md5($list_challenge['inviter_team_id']); ?>">
					<img class="img-circle post-img" src="<?php echo base_url().'uploadfiles/team-images/'.$list_challenge['inviter_team_image']; ?>">

				<a href="<?php echo base_url().'team/profile/'.md5($list_challenge['inviter_team_id']); ?>" class="url-color">

<?php echo $list_challenge['inviter_team_name']; ?>

VS

					<?php echo 'Tanggal '.$list_challenge['challenge_date'].
    						'
 Jam '.$list_challenge['challenge_time'].
    						'
 di '.$list_challenge['nama_lapangan'].
    						'
 '.$list_challenge['daerah'].', '.$list_challenge['kota'];
    				?>

				<a href="<?php echo base_url().'team/profile/'.md5($list_challenge['rival_team_id']); ?>">
					<img class="img-circle post-img" src="<?php echo base_url().'uploadfiles/team-images/'.$list_challenge['rival_team_image']; ?>">

				<a href="<?php echo base_url().'team/profile/'.md5($list_challenge['rival_team_id']); ?>" class="url-color">

<?php echo $list_challenge['rival_team_name']; ?>

			<div id="<?php echo md5($list_challenge['challenge_id']); ?>_history" class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="margin-top: 20px;">

				<a href="#<?php echo md5($list_challenge['challenge_id']); ?>_history" onclick="load_history_upteam('<?php echo md5($list_challenge['challenge_id']); ?>', '<?php echo md5($list_challenge['inviter_team_id']); ?>', '<?php echo md5($list_challenge['rival_team_id']); ?>')">History Pertandingan
				<a href="#comment-content" class="popup-with-move-anim-challenge" data-id="<?php echo md5($list_challenge['challenge_id']); ?>"><button type="button" class="btn btn-inverse">Comment</button>

		<?php } ?>

<?php include(APPPATH.'views/includes/footer.php'); ?>


text:
FILKOM UNIVERSITAS BRAWIJAYA MALANG.
          maybemai@maybe.com

Phone : +999 9999999

&copy 2016 MAYBE. All rights reserved | Design by W3layouts.

</html


text:
package gov.nih.nci.cabig.caaers.dao.query;

import junit.framework.TestCase;
/**
 *
 * @author Biju Joseph
 *
 */
public class AbstractQueryTest extends TestCase {
	AbstractQuery query;

	protected void setUp() throws Exception {
		super.setUp();
		query = new AbstractQuery("select * from emp"){

		};
	}
	public void testGetQueryString() {
		query.andWhere("x = 1");
		query.orWhere("y = 2");
		query.orWhere("z = 3");
		assertEquals("select * from emp WHERE x = 1 AND ( y = 2 OR z = 3 )",query.getQueryString());
	}

	public void testGetQueryString_WithoutAnd(){
		query.orWhere("y = 2");
		query.orWhere("z = 3");
		assertEquals("select * from emp WHERE y = 2 OR z = 3",query.getQueryString());
	}

	public void test2(){
		query.orWhere("y = 3");
        assertEquals("select * from emp WHERE y = 3", query.getQueryString());
	}

	public void testOneAnd(){
		query.andWhere("dept = 'ABC'");
        assertEquals("select * from emp WHERE dept = 'ABC'", query.getQueryString());
	}

    public void testWithMultipleAndAndOr(){
        query.join("dept on dept.id = emp.id");
        query.andWhere("j = 1");
        query.andWhere("m = 5");
		query.orWhere("y = 3");
        query.orWhere("y = 4");
        assertEquals("select * from emp join dept on dept.id = emp.id WHERE j = 1 AND m = 5 AND ( y = 3 OR y = 4 )", query.getQueryString());
	}
}


text:
angular.module("notesApp.deliberations.controllers", []).controller("DeliberationController", ["$scope", "$http", "Annee","Departement", "Niveau",
    function($scope, $http, Annee, Departement, Niveau){
        var deps = Departement.query(function () {
            $scope.departements = deps;
        });
        $scope.selection = true;
        var niv = Niveau.query(function () {
            $scope.niveaux = niv;
        });
        var anns = Annee.query(function () {
            $scope.annees = anns;
        });
        $scope.infInclusive = true;
        $scope.supInclusive = false;
        $scope.strict = true;
        $scope.borneInf =  9;
        $scope.borneSup = 10;
        $scope.moyenneFinale = 10;
        $scope.updateOptions = function () {
            if (($scope.departement) && ($scope.niveau)) {
                $http.get('api/options/' + $scope.departement.id + '/' + $scope.niveau.id).success(function (data, status, config, headers) {
                    $scope.options = data;
                });
            }
        };
        $scope.changerOption = function () {
            if (($scope.option) && ($scope.niveau)) {
                $http.get('api/cours/' + $scope.niveau.id + '/' + $scope.option.id).success(function (data, status, config, headers) {
                    $scope.cours = data;
                });
            }
        };

        $scope.proceder = function(){
            var fd = new FormData();
            //Take the first selected file
            fd.append("departementId", $scope.departement.id);
            fd.append("niveauId", $scope.niveau.id);
            fd.append("optionId", $scope.option.id);
            fd.append("coursId", $scope.cour.id);
            fd.append("anneeId", $scope.annee);
            fd.append("borneInf", $scope.borneInf);
            fd.append("borneSup", $scope.borneSup);
            fd.append("infInclusive", $scope.infInclusive);
            fd.append("supInclusive", $scope.supInclusive);
            fd.append("moyenne", $scope.moyenneFinale);
            fd.append("strict", $scope.strict);
            if ($scope.session)
                fd.append("session", $scope.session);
            $http.post('api/notes/deliberation', fd, {
                withCredentials: true,
                headers: {'Content-Type': undefined},
                transformRequest: angular.identity
            }).success(function (data) {
                $scope.selection = false;
                $scope.deliberations = data;
            }).error(function () {
            });

        };

        $scope.valider = function(){
            var fd = new FormData();
            //Take the first selected file
            fd.append("departementId", $scope.departement.id);
            fd.append("niveauId", $scope.niveau.id);
            fd.append("optionId", $scope.option.id);
            fd.append("coursId", $scope.cour.id);
            fd.append("anneeId", $scope.annee);
            fd.append("borneInf", $scope.borneInf);
            fd.append("borneSup", $scope.borneSup);
            fd.append("infInclusive", $scope.infInclusive);
            fd.append("supInclusive", $scope.supInclusive);
            fd.append("moyenne", $scope.moyenneFinale);
            fd.append("strict", $scope.strict);
            if ($scope.session)
                fd.append("session", $scope.session);
            $http.put('api/notes/deliberation', fd, {
                withCredentials: true,
                headers: {'Content-Type': undefined},
                transformRequest: angular.identity
            }).success(function (data) {
                $scope.deliberations = null;
                $scope.nombre = data;
            }).error(function () {
            });

        };
    }]);


text:
MicroPython libraries
=====================

Functionality specific to the MicroPython implementation is available in
the following library.

.. toctree::
   :maxdepth: 1

   micropython.rst

Python standard libraries
-------------------------

The following standard Python libraries are built in to MicroPython.

For additional libraries, please download them from the `micropython-lib repository
<https://github.com/micropython/micropython-lib>`_.

.. only:: port_unix

    .. toctree::
       :maxdepth: 1

       cmath.rst
       gc.rst
       math.rst
       os.rst
       struct.rst
       sys.rst
       time.rst

.. only:: port_pyboard

    .. toctree::
       :maxdepth: 1

       cmath.rst
       gc.rst
       math.rst
       os.rst
       select.rst
       struct.rst
       sys.rst
       time.rst

.. only:: port_wipy

    .. toctree::
       :maxdepth: 1

       gc.rst
       os.rst
       select.rst
       sys.rst
       time.rst

Python micro-libraries
----------------------

The following standard Python libraries have been "micro-ified" to fit in with
the philosophy of MicroPython.  They provide the core functionality of that
module and are intended to be a drop-in replacement for the standard Python
library.

.. only:: not port_unix

    The modules are available by their u-name, and also by their non-u-name.  The
    non-u-name can be overridden by a file of that name in your package path.
    For example, ``import json`` will first search for a file ``json.py`` or
    directory ``json`` and load that package if it is found.  If nothing is found,
    it will fallback to loading the built-in ``ujson`` module.

.. only:: port_pyboard or port_unix

   .. toctree::
      :maxdepth: 1

      ubinascii.rst
      uctypes.rst
      uhashlib.rst
      uheapq.rst
      ujson.rst
      ure.rst
      usocket.rst
      uzlib.rst

.. only:: port_pyboard

   Libraries specific to the pyboard
   ---------------------------------

   The following libraries are specific to the pyboard.

   .. toctree::
      :maxdepth: 2

      pyb.rst
      network.rst

.. only:: port_wipy

   .. toctree::
      :maxdepth: 1

      ubinascii.rst
      ujson.rst
      ure.rst
      usocket.rst
      ussl.rst

.. only:: port_wipy

   Libraries specific to the WiPy
   ---------------------------------

   The following libraries are specific to the WiPy.

   .. toctree::
      :maxdepth: 2

      machine.rst
      network.rst
      wipy.rst

.. only:: port_esp8266

   Libraries specific to the ESP8266
   ---------------------------------

   The following libraries are specific to the ESP8266.

   .. toctree::
      :maxdepth: 2

      pyb.rst
      esp.rst
      network.rst


text:
@interface IDPLoadingView : UIView

+ (id)loadingViewInView:(UIView *)view;
+ (id)loadingViewInView:(UIView *)view withMessage:(NSString *)message;

@end