text:
/*
 * xdm - display manager daemon
 * Author:  Keith Packard, MIT X Consortium
 *
 * display manager
 */

#include	"dm.h"
#include	"dm_auth.h"
#include	"dm_error.h"

#include	<stdio.h>
#ifdef X_POSIX_C_SOURCE
# define _POSIX_C_SOURCE X_POSIX_C_SOURCE
# include <signal.h>
# undef _POSIX_C_SOURCE
#else
# if defined(X_NOT_POSIX) || defined(_POSIX_SOURCE)
#  include <signal.h>
# else
#  define _POSIX_SOURCE
#  include <signal.h>
#  undef _POSIX_SOURCE
# endif
#endif
#ifdef __NetBSD__
# include <sys/param.h>
#endif
#ifdef USESECUREWARE
# include <prot.h>
#endif

#ifndef sigmask
# define sigmask(m)  (1 << ((m - 1)))
#endif

#include	<sys/stat.h>
#include	<errno.h>
#include	<X11/Xfuncproto.h>
#include	<X11/Xatom.h>
#include	<stdarg.h>
#include	<stdint.h>

#ifndef F_TLOCK
# ifndef X_NOT_POSIX
#  include	<unistd.h>
# endif
#endif

#if defined(HAVE_OPENLOG) && defined(HAVE_SYSLOG_H)
# define USE_SYSLOG
# include <syslog.h>
# ifndef LOG_AUTHPRIV
#  define LOG_AUTHPRIV LOG_AUTH
# endif
# ifndef LOG_PID
#  define LOG_PID 0
# endif
#endif

#if defined(SVR4) && !defined(sun)
extern FILE    *fdopen();
#endif

static SIGVAL	StopAll (int n), RescanNotify (int n);
static void	RescanServers (void);
static void	RestartDisplay (struct display *d, int forceReserver);
static void	ScanServers (void);
static void	SetAccessFileTime (void);
static void	SetConfigFileTime (void);
static void	StartDisplays (void);
static void	TerminateProcess (pid_t pid, int signal);

volatile int	Rescan;
static long	ServersModTime, ConfigModTime, AccessFileModTime;

int nofork_session = 0;

#ifndef NOXDMTITLE
static char *Title;
static int TitleLen;
#endif

#ifndef UNRELIABLE_SIGNALS
static SIGVAL ChildNotify (int n);
#endif

static long StorePid (void);
static void RemovePid (void);

static pid_t parent_pid = -1; 	/* PID of parent xdm process */

int
main (int argc, char **argv)
{
    int	oldpid;
    mode_t oldumask;
    char cmdbuf[1024];

    /* make sure at least world write access is disabled */
    if (((oldumask = umask(022)) & 002) == 002)
	(void) umask (oldumask);
#ifndef NOXDMTITLE
    Title = argv[0];
    TitleLen = (argv[argc - 1] + strlen(argv[argc - 1])) - Title;
#endif

#ifdef USESECUREWARE
    set_auth_parameters (argc, argv);
#endif

    /*
     * Step 1 - load configuration parameters
     */
    InitResources (argc, argv);
    SetConfigFileTime ();
    LoadDMResources ();
    /*
     * Only allow root to run in non-debug mode to avoid problems
     */
    if (debugLevel == 0 && getuid() != 0)
    {
	fprintf (stderr, "Only root wants to run %s\n", argv[0]);
	exit (1);
    }
    if (debugLevel == 0 && daemonMode)
	BecomeDaemon ();
    if (debugLevel == 0)
	InitErrorLog ();
    if (debugLevel >= 10)
	nofork_session = 1;
    /* SUPPRESS 560 */
    if ((oldpid = StorePid ()))
    {
	if (oldpid == -1)
	    LogError ("Can't create/lock pid file %s\n", pidFile);
	else
	    LogError ("Can't lock pid file %s, another xdm is running (pid %d)\n",
		 pidFile, oldpid);
	exit (1);
    }

    LogInfo ("Starting\n");

    if (atexit (RemovePid))
	LogError ("could not register RemovePid() with atexit()\n");

    if (nofork_session == 0) {
	/* Clean up any old Authorization files */
	/* AUD: all good? */
	snprintf(cmdbuf, sizeof(cmdbuf), "/bin/rm -f %s/authdir/authfiles/A*", authDir);
	system(cmdbuf);
    }
#if!defined(HAVE_ARC4RANDOM) && !defined(DEV_RANDOM)
    AddOtherEntropy ();
#endif
#ifdef XDMCP
    init_session_id ();
    CreateWellKnownSockets ();
#else
    Debug ("xdm: not compiled for XDMCP\n");
#endif
    parent_pid = getpid ();
    (void) Signal (SIGTERM, StopAll);
    (void) Signal (SIGINT, StopAll);
    /*
     * Step 2 - Read /etc/Xservers and set up
     *	    the socket.
     *
     *	    Keep a sub-daemon running
     *	    for each entry
     */
    SetAccessFileTime ();
#ifdef XDMCP
    ScanAccessDatabase ();
    UpdateListenSockets ();
#endif
    ScanServers ();
    StartDisplays ();
#if !defined(HAVE_ARC4RANDOM) && !defined(DEV_RANDOM)
    AddOtherEntropy();
#endif
    (void) Signal (SIGHUP, RescanNotify);
#ifndef UNRELIABLE_SIGNALS
    (void) Signal (SIGCHLD, ChildNotify);
#endif
    Debug ("startup successful; entering main loop\n");
    while (
#ifdef XDMCP
	   AnyWellKnownSockets() ||
#endif
	   AnyDisplaysLeft ())
    {
	if (Rescan)
	{
	    RescanServers ();
	    Rescan = 0;
	}
#if defined(UNRELIABLE_SIGNALS) || !defined(XDMCP)
	WaitForChild ();
#else
	WaitForSomething ();
#endif
    }
    Debug ("Nothing left to do, exiting\n");
    LogInfo ("Exiting\n");
    exit(0);
    /*NOTREACHED*/
}

/* ARGSUSED */
static SIGVAL
RescanNotify (int n)
{
    int olderrno = errno;

    Debug ("Caught SIGHUP\n");
    Rescan = 1;
#ifdef SIGNALS_RESET_WHEN_CAUGHT
    (void) Signal (SIGHUP, RescanNotify);
#endif
    errno = olderrno;
}

static void
ScanServers (void)
{
    char	lineBuf[10240];
    int		len;
    FILE	*serversFile;
    struct stat	statb;
    static DisplayType	acceptableTypes[] =
	    { { Local, Permanent, FromFile },
	      { Foreign, Permanent, FromFile },
	    };

#define NumTypes    (sizeof (acceptableTypes) / sizeof (acceptableTypes[0]))

    if (servers[0] == '/')
    {
	serversFile = fopen (servers, "r");
	if (serversFile == NULL)
	{
	    LogError ("cannot access servers file %s\n", servers);
	    return;
	}
	if (ServersModTime == 0)
	{
	    fstat (fileno (serversFile), &statb);
	    ServersModTime = statb.st_mtime;
	}
	while (fgets (lineBuf, sizeof (lineBuf)-1, serversFile))
	{
	    len = strlen (lineBuf);
	    if (lineBuf[len-1] == '\n')
		lineBuf[len-1] = '\0';
	    ParseDisplay (lineBuf, acceptableTypes, NumTypes);
	}
	fclose (serversFile);
    }
    else
    {
	ParseDisplay (servers, acceptableTypes, NumTypes);
    }
}

static void
MarkDisplay (struct display *d)
{
    d->state = MissingEntry;
}

static void
RescanServers (void)
{
    Debug ("rescanning servers\n");
    LogInfo ("Rescanning both config and servers files\n");
    ForEachDisplay (MarkDisplay);
    SetConfigFileTime ();
    ReinitResources ();
    LoadDMResources ();
    ScanServers ();
    SetAccessFileTime ();
#ifdef XDMCP
    ScanAccessDatabase ();
    UpdateListenSockets ();
#endif
    StartDisplays ();
}

static void
SetConfigFileTime (void)
{
    struct stat	statb;

    if (stat (config, &statb) != -1)
	ConfigModTime = statb.st_mtime;
}

static void
SetAccessFileTime (void)
{
    struct stat	statb;

    if (stat (accessFile, &statb) != -1)
	AccessFileModTime = statb.st_mtime;
}

static void
RescanIfMod (void)
{
    struct stat	statb;

    if (config && stat (config, &statb) != -1)
    {
	if (statb.st_mtime != ConfigModTime)
	{
	    Debug ("Config file %s has changed, rereading\n", config);
	    LogInfo ("Rereading configuration file %s\n", config);
	    ConfigModTime = statb.st_mtime;
	    ReinitResources ();
	    LoadDMResources ();
	}
    }
    if (servers[0] == '/' && stat(servers, &statb) != -1)
    {
	if (statb.st_mtime != ServersModTime)
	{
	    Debug ("Servers file %s has changed, rescanning\n", servers);
	    LogInfo ("Rereading servers file %s\n", servers);
	    ServersModTime = statb.st_mtime;
	    ForEachDisplay (MarkDisplay);
	    ScanServers ();
	}
    }
#ifdef XDMCP
    if (accessFile && accessFile[0] && stat (accessFile, &statb) != -1)
    {
	if (statb.st_mtime != AccessFileModTime)
	{
	    Debug ("Access file %s has changed, rereading\n", accessFile);
	    LogInfo ("Rereading access file %s\n", accessFile);
	    AccessFileModTime = statb.st_mtime;
	    ScanAccessDatabase ();
	    UpdateListenSockets();
	}
    }
#endif
}

/*
 * catch a SIGTERM, kill all displays and exit
 */

/* ARGSUSED */
static SIGVAL
StopAll (int n)
{
    int olderrno = errno;

    if (parent_pid != getpid())
    {
	/*
	 * We are a child xdm process that was killed by the
	 * master xdm before we were able to return from fork()
	 * and remove this signal handler.
	 *
	 * See defect XWSog08655 for more information.
	 */
	Debug ("Child xdm caught SIGTERM before it removed that signal.\n");
	(void) Signal (n, SIG_DFL);
	TerminateProcess (getpid(), SIGTERM);
	errno = olderrno;
	return;
    }
    Debug ("Shutting down entire manager\n");
    LogInfo ("Shutting down\n");
#ifdef XDMCP
    DestroyWellKnownSockets ();
#endif
    ForEachDisplay (StopDisplay);
#ifdef SIGNALS_RESET_WHEN_CAUGHT
    /* to avoid another one from killing us unceremoniously */
    (void) Signal (SIGTERM, StopAll);
    (void) Signal (SIGINT, StopAll);
#endif
    errno = olderrno;
}

/*
 * notice that a child has died and may need another
 * sub-daemon started
 */

int	ChildReady;

#ifndef UNRELIABLE_SIGNALS
/* ARGSUSED */
static SIGVAL
ChildNotify (int n)
{
    int olderrno = errno;

    ChildReady = 1;
# ifdef ISC
    (void) Signal (SIGCHLD, ChildNotify);
# endif
    errno = olderrno;
}
#endif

void
WaitForChild (void)
{
    pid_t		pid;
    struct display	*d;
    waitType	status;
#if !defined(X_NOT_POSIX) && !defined(__UNIXOS2__)
    sigset_t mask, omask;
#else
    int		omask;
#endif

#ifdef UNRELIABLE_SIGNALS
    /* XXX classic System V signal race condition here with RescanNotify */
    if ((pid = wait (&status)) != -1)
#else
# ifndef X_NOT_POSIX
    sigemptyset(&mask);
    sigaddset(&mask, SIGCHLD);
    sigaddset(&mask, SIGHUP);
    sigprocmask(SIG_BLOCK, &mask, &omask);
    Debug ("signals blocked\n");
# else
    omask = sigblock (sigmask (SIGCHLD) | sigmask (SIGHUP));
    Debug ("signals blocked, mask was 0x%x\n", omask);
# endif
    if (!ChildReady && !Rescan)
# ifndef X_NOT_POSIX
	sigsuspend(&omask);
# else
	sigpause (omask);
# endif
    ChildReady = 0;
# ifndef X_NOT_POSIX
    sigprocmask(SIG_SETMASK, &omask, (sigset_t *)NULL);
# else
    sigsetmask (omask);
# endif
    while ((pid = waitpid (-1, &status, WNOHANG)) > 0)
#endif
    {
	Debug ("Manager wait returns pid: %d sig %d core %d code %d\n",
	       pid, waitSig(status), waitCore(status), waitCode(status));
	if (autoRescan)
	    RescanIfMod ();
	/* SUPPRESS 560 */
	if ((d = FindDisplayByPid (pid))) {
	    d->pid = -1;
	    switch (waitVal (status)) {
	    case UNMANAGE_DISPLAY:
		Debug ("Display exited with UNMANAGE_DISPLAY\n");
		StopDisplay (d);
		break;
	    case OBEYSESS_DISPLAY:
		d->startTries = 0;
		d->reservTries = 0;
		Debug ("Display exited with OBEYSESS_DISPLAY\n");
		if (d->displayType.lifetime != Permanent ||
		    d->status == zombie)
		    StopDisplay (d);
		else
		    RestartDisplay (d, FALSE);
		break;
	    case OPENFAILED_DISPLAY:
		Debug ("Display exited with OPENFAILED_DISPLAY, try %d of %d\n",
		       d->startTries, d->startAttempts);
		LogError ("Display %s cannot be opened\n", d->name);
		/*
		 * no display connection was ever made, tell the
		 * terminal that the open attempt failed
		 */
#ifdef XDMCP
		if (d->displayType.origin == FromXDMCP)
		    SendFailed (d, "Cannot open display");
#endif
		if (d->displayType.origin == FromXDMCP ||
		    d->status == zombie ||
		    ++d->startTries >= d->startAttempts)
		{
		    LogError ("Display %s is being disabled\n", d->name);
		    StopDisplay (d);
		}
		else
		{
		    RestartDisplay (d, TRUE);
		}
		break;
	    case RESERVER_DISPLAY:
		d->startTries = 0;
		Debug ("Display exited with RESERVER_DISPLAY\n");
		if (d->displayType.origin == FromXDMCP || d->status == zombie)
		    StopDisplay(d);
		else {
		  Time_t now;
		  int crash;

		  time(&now);
		  crash = d->lastReserv &&
		    ((now - d->lastReserv) < XDM_BROKEN_INTERVAL);
		  Debug("time %ji %ji try %i of %i%s\n",
			(intmax_t)now, (intmax_t)d->lastReserv,
			d->reservTries, d->reservAttempts,
			crash ? " crash" : "");

		  if (!crash)
		    d->reservTries = 0;

		  if (crash && ++d->reservTries >= d->reservAttempts) {
		    const char *msg =
			"Server crash frequency too high: stopping display";
		    Debug("%s %s\n", msg, d->name);
		    LogError("%s %s\n", msg, d->name);
#if !defined(HAVE_ARC4RANDOM) && !defined(DEV_RANDOM)
		    AddTimerEntropy();
#endif
		    /* For a local X server either:
		     * 1. The server exit was returned by waitpid().  So
		     *    serverPid==-1 => StopDisplay() calls RemoveDisplay()
		     *
		     * 2. The server is in zombie state or still running.  So
		     *    serverPid>1 => StopDisplay()
		     *                   a. sets status=zombie,
		     *                   b. kills the server.
		     *    The next waitpid() returns this zombie server pid
		     *    and the 'case zombie:' below then calls
		     *    RemoveDisplay().
		     */
		    StopDisplay(d);
		  } else {
		    RestartDisplay(d, TRUE);
		  }
		  d->lastReserv = now;
		}
		break;
	    case waitCompose (SIGTERM,0,0):
		Debug ("Display exited on SIGTERM, try %d of %d\n",
			d->startTries, d->startAttempts);
		if (d->displayType.origin == FromXDMCP ||
		    d->status == zombie ||
		    ++d->startTries >= d->startAttempts)
		{
		    /*
		     * During normal xdm shutdown, killed local X servers
		     * can be zombies; this is not an error.
		     */
		    if (d->status == zombie &&
			(d->startTries < d->startAttempts))
			LogInfo ("display %s is being disabled\n", d->name);
		    else
			LogError ("display %s is being disabled\n", d->name);
		    StopDisplay(d);
		} else
		    RestartDisplay (d, TRUE);
		break;
	    case REMANAGE_DISPLAY:
		d->startTries = 0;
		Debug ("Display exited with REMANAGE_DISPLAY\n");
		/*
		 * XDMCP will restart the session if the display
		 * requests it
		 */
		if (d->displayType.origin == FromXDMCP || d->status == zombie)
		    StopDisplay(d);
		else
		    RestartDisplay (d, FALSE);
		break;
	    default:
		Debug ("Display exited with unknown status %d\n", waitVal(status));
		LogError ("Unknown session exit code %d from process %d\n",
			  waitVal (status), pid);
		StopDisplay (d);
		break;
	    }
	}
	/* SUPPRESS 560 */
	else if ((d = FindDisplayByServerPid (pid)))
	{
	    d->serverPid = -1;
	    switch (d->status)
	    {
	    case zombie:
		Debug ("Zombie server reaped, removing display %s\n", d->name);
		RemoveDisplay (d);
		break;
	    case phoenix:
		Debug ("Phoenix server arises, restarting display %s\n", d->name);
		d->status = notRunning;
		break;
	    case running:
		Debug ("Server for display %s terminated unexpectedly, status %d %d\n", d->name, waitVal (status), status);
		LogError ("Server for display %s terminated unexpectedly: %d\n", d->name, waitVal (status));
		if (d->pid != -1)
		{
		    Debug ("Terminating session pid %d\n", d->pid);
		    TerminateProcess (d->pid, SIGTERM);
		}
		break;
	    case notRunning:
		Debug ("Server exited for notRunning session on display %s\n", d->name);
		break;
	    }
	}
	else
	{
	    Debug ("Unknown child termination, status %d\n", waitVal (status));
	}
    }
    StartDisplays ();
}

static void
CheckDisplayStatus (struct display *d)
{
    if (d->displayType.origin == FromFile)
    {
	switch (d->state) {
	case MissingEntry:
	    StopDisplay (d);
	    break;
	case NewEntry:
	    d->state = OldEntry;
	case OldEntry:
	    if (d->status == notRunning)
		StartDisplay (d);
	    break;
	}
    }
}

static void
StartDisplays (void)
{
    ForEachDisplay (CheckDisplayStatus);
}

static void
SetWindowPath(struct display *d)
{
	/* setting WINDOWPATH for clients */
	Atom prop;
	Atom actualtype;
	int actualformat;
	unsigned long nitems;
	unsigned long bytes_after;
	unsigned char *buf;
	const char *windowpath;
	char *newwindowpath;
	unsigned long num;

	prop = XInternAtom(d->dpy, "XFree86_VT", False);
	if (prop == None) {
		fprintf(stderr, "no XFree86_VT atom\n");
		return;
	}
	if (XGetWindowProperty(d->dpy, DefaultRootWindow(d->dpy), prop, 0, 1,
		False, AnyPropertyType, &actualtype, &actualformat,
		&nitems, &bytes_after, &buf)) {
		fprintf(stderr, "no XFree86_VT property\n");
		return;
	}
	if (nitems != 1) {
		fprintf(stderr, "%lu items in XFree86_VT property!\n", nitems);
		XFree(buf);
		return;
	}
	switch (actualtype) {
	case XA_CARDINAL:
	case XA_INTEGER:
	case XA_WINDOW:
		switch (actualformat) {
		case  8:
			num = (*(uint8_t  *)(void *)buf);
			break;
		case 16:
			num = (*(uint16_t *)(void *)buf);
			break;
		case 32:
			num = (*(uint32_t *)(void *)buf);
			break;
		default:
			fprintf(stderr, "format %d in XFree86_VT property!\n", actualformat);
			XFree(buf);
			return;
		}
		break;
	default:
		fprintf(stderr, "type %lx in XFree86_VT property!\n", actualtype);
		XFree(buf);
		return;
	}
	XFree(buf);
	windowpath = getenv("WINDOWPATH");
	if (!windowpath) {
		asprintf(&newwindowpath, "%lu", num);
	} else {
		asprintf(&newwindowpath, "%s:%lu", windowpath, num);
	}
	free(d->windowPath);
	d->windowPath = newwindowpath;
}

void
StartDisplay (struct display *d)
{
    pid_t	pid;

    Debug ("StartDisplay %s\n", d->name);
    LogInfo ("Starting X server on %s\n", d->name);
    LoadServerResources (d);
    if (d->displayType.location == Local)
    {
	/* don't bother pinging local displays; we'll
	 * certainly notice when they exit
	 */
	d->pingInterval = 0;
	if (d->authorize)
	{
	    Debug ("SetLocalAuthorization %s, auth %s\n",
		    d->name, d->authNames[0]);
	    SetLocalAuthorization (d);
	    /*
	     * reset the server after writing the authorization information
	     * to make it read the file (for compatibility with old
	     * servers which read auth file only on reset instead of
	     * at first connection)
	     */
	    if (d->serverPid != -1 && d->resetForAuth && d->resetSignal)
		kill (d->serverPid, d->resetSignal);
	}
	if (d->serverPid == -1 && !StartServer (d))
	{
	    LogError ("Server for display %s can't be started, session disabled\n", d->name);
	    RemoveDisplay (d);
	    return;
	}
    }
    else
    {
	/* this will only happen when using XDMCP */
	if (d->authorizations)
	    SaveServerAuthorizations (d, d->authorizations, d->authNum);
    }
    if (!nofork_session)
	pid = fork ();
    else
	pid = 0;
    switch (pid)
    {
    case 0:
	if (!nofork_session) {
	    CleanUpChild ();
	    (void) Signal (SIGPIPE, SIG_IGN);
	}
#ifdef USE_SYSLOG
	openlog("xdm", LOG_PID, LOG_AUTHPRIV);
#endif
	LoadSessionResources (d);
	SetAuthorization (d);
	if (!WaitForServer (d))
	    exit (OPENFAILED_DISPLAY);
	SetWindowPath(d);
#ifdef XDMCP
	if (d->useChooser)
	    RunChooser (d);
	else
#endif
	    ManageSession (d);
	exit (REMANAGE_DISPLAY);
    case -1:
	break;
    default:
	Debug ("pid: %d\n", pid);
	d->pid = pid;
	d->status = running;
	break;
    }
}

static void
TerminateProcess (pid_t pid, int signal)
{
    kill (pid, signal);
#ifdef SIGCONT
    kill (pid, SIGCONT);
#endif
}

/*
 * transition from running to zombie or deleted
 */

void
StopDisplay (struct display *d)
{
    if (d->serverPid != -1)
	d->status = zombie; /* be careful about race conditions */
    if (d->pid != -1)
	TerminateProcess (d->pid, SIGTERM);
    if (d->serverPid != -1)
	TerminateProcess (d->serverPid, d->termSignal);
    else
	RemoveDisplay (d);
}

/*
 * transition from running to phoenix or notRunning
 */

static void
RestartDisplay (struct display *d, int forceReserver)
{
    if (d->serverPid != -1 && (forceReserver || d->terminateServer))
    {
	TerminateProcess (d->serverPid, d->termSignal);
	d->status = phoenix;
    }
    else
    {
	d->status = notRunning;
    }
}

static FD_TYPE	CloseMask;
static int	max;

void
RegisterCloseOnFork (int fd)
{
    FD_SET (fd, &CloseMask);
    if (fd > max)
	max = fd;
}

void
ClearCloseOnFork (int fd)
{
    FD_CLR (fd, &CloseMask);
    if (fd == max) {
	while (--fd >= 0)
	    if (FD_ISSET (fd, &CloseMask))
		break;
	max = fd;
    }
}

void
CloseOnFork (void)
{
    int	fd;

    for (fd = 0; fd <= max; fd++)
	if (FD_ISSET (fd, &CloseMask))
	{
	    close (fd);
        }
    FD_ZERO (&CloseMask);
    max = 0;
}

static int  pidFd;
static FILE *pidFilePtr;

/*
 * Create and populate file storing xdm's process ID.
 */
static long
StorePid (void)
{
    long	oldpid;
    char	pidstr[11]; /* enough space for a 32-bit pid plus \0 */
    size_t	pidstrlen;

    if (pidFile[0] != '\0')
    {
	Debug ("storing process ID in %s\n", pidFile);
	pidFd = open (pidFile, O_WRONLY|O_CREAT|O_EXCL, 0666);
	if (pidFd == -1 && errno == ENOENT)
	{
	    /* Make sure directory exists if needed
	       Allows setting pidDir to /var/run/xdm
	     */
	    char *pidDir = strdup(pidFile);

	    if (pidDir != NULL)
	    {
		char *p = strrchr(pidDir, '/');
		int r;

		if ((p != NULL) && (p != pidDir)) {
		    *p = '\0';
		}
		r = mkdir(pidDir, 0755);
		if ( (r < 0) && (errno != EEXIST) ) {
		     LogError ("process-id directory %s cannot be created\n",
			       pidDir);
		}
	    }

	    pidFd = open (pidFile, O_WRONLY|O_CREAT|O_EXCL, 0666);
	}
	if (pidFd == -1)
	{
	    if (errno == EEXIST)
	    {
		/* pidFile already exists; see if we can open it */
		pidFilePtr = fopen (pidFile, "r");
		if (pidFilePtr == NULL)
		{
		    LogError ("cannot open process ID file %s for reading: "
			      "%s\n", pidFile, _SysErrorMsg (errno));
		    return -1;
		}
		if (fscanf (pidFilePtr, "%ld\n", &oldpid) != 1)
		{
		    LogError ("existing process ID file %s empty or contains "
			      "garbage\n", pidFile);
		    oldpid = -1;
		}
		fclose (pidFilePtr);
		return oldpid;
	    }
		else
	    {
		LogError ("cannot fdopen process ID file %s for writing: "
			  "%s\n", pidFile, _SysErrorMsg (errno));
		return -1;
	    }
	}
	if ((pidFilePtr = fdopen (pidFd, "w")) == NULL)
	{
	    LogError ("cannot open process ID file %s for writing: %s\n",
		      pidFile, _SysErrorMsg (errno));
	    return -1;
	}
	(void) snprintf (pidstr, 11, "%ld", (long) getpid ());
	pidstrlen = strlen (pidstr);
	if (fprintf (pidFilePtr, "%s\n", pidstr) != ( pidstrlen + 1))
	{
	    LogError ("cannot write to process ID file %s: %s\n", pidFile,
		      _SysErrorMsg (errno));
	    return -1;
	}
	(void) fflush (pidFilePtr);
	(void) fclose (pidFilePtr);
    }
    return 0;
}

/*
 * Remove process ID file.  This function is registered with atexit().
 */
static void
RemovePid (void)
{
    if (parent_pid != getpid())
	return;

    Debug ("unlinking process ID file %s\n", pidFile);
    if (unlink (pidFile))
	if (errno != ENOENT)
	    LogError ("cannot remove process ID file %s: %s\n", pidFile,
		      _SysErrorMsg (errno));
}

#if 0
void
UnlockPidFile (void)
{
    if (lockPidFile)
# ifdef F_SETLK
    {
	struct flock lock_data;
	lock_data.l_type = F_UNLCK;
	lock_data.l_whence = SEEK_SET;
	lock_data.l_start = lock_data.l_len = 0;
	(void) fcntl(pidFd, F_SETLK, &lock_data);
    }
# else
#  ifdef F_ULOCK
	lockf (pidFd, F_ULOCK, 0);
#  else
	flock (pidFd, LOCK_UN);
#  endif
# endif
    close (pidFd);
    fclose (pidFilePtr);
}
#endif

#ifndef HAVE_SETPROCTITLE
void SetTitle (char *name, ...)
{
# ifndef NOXDMTITLE
    char	*p = Title;
    int	left = TitleLen;
    char	*s;
    va_list	args;

    va_start(args,name);
    *p++ = '-';
    --left;
    s = name;
    while (s)
    {
	while (*s && left > 0)
	{
	    *p++ = *s++;
	    left--;
	}
	s = va_arg (args, char *);
    }
    while (left > 0)
    {
	*p++ = ' ';
	--left;
    }
    va_end(args);
# endif
}
#endif


text:
package com.zupcat.sample;

import com.zupcat.model.DataObject;

/**
 * Subobjects don't have own state. They should delegate its state to DataObject, just like this example
 */
public final class Address extends DataObject {

    public String getStreet() {
        return getString("s");
    }

    public void setStreet(final String street) {
        put("s", street);
    }

    public String getNumber() {
        return getString("n");
    }

    public void setNumber(final String number) {
        put("n", number);
    }

    public int getOrder() {
        return getInt("o");
    }

    public void setOrder(final int order) {
        put("o", order);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.ohdsi.webapi.check.validator.common;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import org.ohdsi.webapi.check.validator.Context;
import org.ohdsi.webapi.check.validator.Path;
import org.ohdsi.webapi.check.validator.Validator;
import org.ohdsi.webapi.check.warning.WarningSeverity;

public class NotNullNotEmptyValidator<T> extends Validator<T> {
    private static final String NULL_OR_EMPTY = "null or empty";

    public NotNullNotEmptyValidator(Path path,  WarningSeverity severity, String errorMessage) {

        super(path, severity, errorMessage);
    }

    @Override
    public boolean validate(T value, Context context) {

        boolean isValid = true;
        if (Objects.isNull(value)) {
            isValid = false;
        } else {
            if (value instanceof Collection) {
                isValid = ((Collection) value).size() > 0;
            } else if (value instanceof String) {
                isValid = !((String) value).isEmpty();
            } else if (value.getClass().isArray()) {
                isValid = Array.getLength(value) > 0;
            } else if (value instanceof Map) {
                isValid = ((Map) value).size() > 0;
            }
        }
        if (!isValid) {
            context.addWarning(getSeverity(), getErrorMessage(value), path);
        }
        return isValid;
    }

    protected String getDefaultErrorMessage() {

        return NULL_OR_EMPTY;
    }
}


text:
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {isPresent} from 'angular2/src/facade/lang';
import {DirectiveMetadata} from 'angular2/src/render/api';

/**
 * Converts a [DirectiveMetadata] to a map representation. This creates a copy,
 * that is, subsequent changes to `meta` will not be mirrored in the map.
 */
export function directiveMetadataToMap(meta: DirectiveMetadata): Map<string, any> {
  return MapWrapper.createFromPairs([
    ['id', meta.id],
    ['selector', meta.selector],
    ['compileChildren', meta.compileChildren],
    ['hostListeners', _cloneIfPresent(meta.hostListeners)],
    ['hostProperties', _cloneIfPresent(meta.hostProperties)],
    ['hostAttributes', _cloneIfPresent(meta.hostAttributes)],
    ['hostActions', _cloneIfPresent(meta.hostActions)],
    ['properties', _cloneIfPresent(meta.properties)],
    ['readAttributes', _cloneIfPresent(meta.readAttributes)],
    ['type', meta.type],
    ['version', 1]
  ]);
}

/**
 * Converts a map representation of [DirectiveMetadata] into a
 * [DirectiveMetadata] object. This creates a copy, that is, subsequent changes
 * to `map` will not be mirrored in the [DirectiveMetadata] object.
 */
export function directiveMetadataFromMap(map: Map<string, any>): DirectiveMetadata {
  return new DirectiveMetadata({
    id:<string>MapWrapper.get(map, 'id'),
    selector:<string>MapWrapper.get(map, 'selector'),
    compileChildren:<boolean>MapWrapper.get(map, 'compileChildren'),
    hostListeners:<Map<string, string>>_cloneIfPresent(MapWrapper.get(map, 'hostListeners')),
    hostProperties:<Map<string, string>>_cloneIfPresent(MapWrapper.get(map, 'hostProperties')),
    hostActions:<Map<string, string>>_cloneIfPresent(MapWrapper.get(map, 'hostActions')),
    hostAttributes:<Map<string, string>>_cloneIfPresent(MapWrapper.get(map, 'hostAttributes')),
    properties:<Map<string, string>>_cloneIfPresent(MapWrapper.get(map, 'properties')),
    readAttributes:<List<string>>_cloneIfPresent(MapWrapper.get(map, 'readAttributes')),
    type:<number>MapWrapper.get(map, 'type')
  });
}

/**
 * Clones the [List] or [Map] `o` if it is present.
 */
function _cloneIfPresent(o) {
  if (!isPresent(o)) return null;
  return ListWrapper.isList(o) ? ListWrapper.clone(o) : MapWrapper.clone(o);
}


text:
package com.btcashier.utils;

public final class BtcTestConstants {

    public static final String BTC_URL = "http://btcuser:123456@127.0.0.1:8337/";

    private BtcTestConstants() {
        // Left empty intentionally
    }

}


text:
<?php

namespace Cubanacan\WSBundle\WSClass;

use JMS\Serializer\Annotation\Type;
/**
 * Description of Object
 *
 * @author obretau
 */
class OptionalService extends EntityName{

    /**
     * @var String $price
     * @Type("double")
     */
    protected $price;

    public function getPrice() {
        return $this->price;
    }

    public function setPrice($price) {
        $this->price = $price;
        return $this;
    }
}


text:
package com.opengamma.bbg.normalization;

import java.util.Collections;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.bbg.loader.BloombergEquityScaleResolver;
import com.opengamma.bbg.loader.BloombergFXForwardScaleResolver;
import com.opengamma.bbg.loader.BloombergSecurityTypeResolver;
import com.opengamma.bbg.loader.SecurityType;
import com.opengamma.bbg.loader.SecurityTypeResolver;
import com.opengamma.bbg.referencedata.ReferenceDataProvider;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ExternalScheme;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ehcache.EHCacheUtils;

/**
 * Classifies Bloomberg rates based on the security type to determine the necessary normalization factor.
 */
public class BloombergRateClassifier {

  /** Logger. */
  private static final Logger s_logger = LoggerFactory.getLogger(BloombergRateClassifier.class);

  private static final String CACHE_KEY = "bbg-classifier-cache";

  private final SecurityTypeResolver _securityTypeResolver;
  private final BloombergFXForwardScaleResolver _fwdScaleResolver;
  private final Cache _cache;
  private final ExternalScheme _bbgScheme;

  private final BloombergEquityScaleResolver _equityScaleResolver;

  /**
   * Constructs an instance.
   *
   * @param referenceDataProvider  the underlying reference data provider, not null
   * @param cacheManager  the cache manager, not null
   * @param bbgScheme the scheme that should be used to subscribe, not null
   */
  public BloombergRateClassifier(ReferenceDataProvider referenceDataProvider, CacheManager cacheManager, ExternalScheme bbgScheme) {
    ArgumentChecker.notNull(referenceDataProvider, "referenceDataProvider");
    ArgumentChecker.notNull(cacheManager, "cacheManager");
    ArgumentChecker.notNull(bbgScheme, "bbgScheme");
    _securityTypeResolver = new BloombergSecurityTypeResolver(referenceDataProvider);
    _fwdScaleResolver = new BloombergFXForwardScaleResolver(referenceDataProvider, bbgScheme);
    _equityScaleResolver = new BloombergEquityScaleResolver(referenceDataProvider, bbgScheme);
    EHCacheUtils.addCache(cacheManager, CACHE_KEY);
    _cache = EHCacheUtils.getCacheFromManager(cacheManager, CACHE_KEY);
    _bbgScheme = bbgScheme;
  }

  /**
   * Gets the normalization factor for a given security: 1, 100 or 10000.
   * <p>
   * The normalization factor is the multiple by which the market data is greater than the normalized value.
   *
   * @param buid  the BUID value of the security, not null
   * @return the normalization factor, or null if the security cannot be classified
   */
  public Integer getNormalizationFactor(String buid) {
    ArgumentChecker.notNull(buid, "buid");
    Element e = _cache.get(buid);
    if (e != null) {
      s_logger.debug("Obtained normalization factor for security " + buid + " from cache");
      return (Integer) e.getObjectValue();
    }
    try {
      Integer normalizationFactor = getNormalizationFactorCore(buid);
      s_logger.debug("Generated normalization factor {} for security {}", normalizationFactor, buid);
      e = new Element(buid, normalizationFactor);
      _cache.put(e);
      return normalizationFactor;
    } catch (Exception ex) {
      s_logger.warn("Error obtaining normalization factor for security " + buid, ex);
      throw new OpenGammaRuntimeException("Error obtaining normalization factor for security " + buid, ex);
    }
  }

  private Integer getNormalizationFactorCore(String buid) {
    ExternalIdBundle buidBundle = ExternalIdBundle.of(_bbgScheme, buid);
    SecurityType securityType = _securityTypeResolver.getSecurityType(Collections.singleton(buidBundle)).get(buidBundle);
    if (securityType == null) {
      s_logger.warn("Unable to determine security type for BUID " + buid);
      return null;
    }
    switch (securityType) {
      case BASIS_SWAP:
        return 10000;
      case FORWARD_CROSS:
      case FX_FORWARD:
        Integer bbgFwdScale = _fwdScaleResolver.getBloombergFXForwardScale(Collections.singleton(buidBundle)).get(buidBundle);
        return getForwardScale(bbgFwdScale);
      case BILL:
      case BOND:
      case CASH:
      case CREDIT_DEFAULT_SWAP:
      case FRA:
      case INTEREST_RATE_FUTURE:
      case BOND_FUTURE:
      case IR_FUTURE_OPTION:
      case BOND_FUTURE_OPTION:
      case RATE:
      case INDEX:
      case SWAP:
      case VOLATILITY_QUOTE:
      case CD:
      case INFLATION_SWAP:
        return 100;
      case EQUITY_FUTURE:
        return 1;
      case INDEX_FUTURE:
        return 1;
      case EQUITY:
        Integer equityScale = _equityScaleResolver.getBloombergEquityScale(Collections.singleton(buidBundle)).get(buidBundle);
        return equityScale;
      default:
        return 1;
    }
  }

  private Integer getForwardScale(int bbgFwdScale) {
    switch(bbgFwdScale) {
      case 0:
        return 1;
      case 1:
        return 10;
      case 2:
        return 100;
      case 3:
        return 1000;
      case 4:
        return 10000;
      default:
        s_logger.warn("Unable to handle forward scale {}", bbgFwdScale);
        return null;
    }
  }
}


text:
require 'dalli/client'

module Dalli
  class Client
    ##
    # Get the value and CAS ID associated with the key.  If a block is provided,
    # value and CAS will be passed to the block.
    def get_cas(key)
      (value, cas) = perform(:cas, key)
      value = (!value || value == 'Not found') ? nil : value
      if block_given?
        yield value, cas
      else
        [value, cas]
      end
    end

    ##
    # Fetch multiple keys efficiently, including available metadata such as CAS.
    # If a block is given, yields key/data pairs one a time.  Data is an array:
    # [value, cas_id]
    # If no block is given, returns a hash of
    #   { 'key' => [value, cas_id] }
    def get_multi_cas(*keys)
      if block_given?
        get_multi_yielder(keys) {|*args| yield(*args)}
      else
        Hash.new.tap do |hash|
          get_multi_yielder(keys) {|k, data| hash[k] = data}
        end
      end
    end

    ##
    # Set the key-value pair, verifying existing CAS.
    # Returns the resulting CAS value if succeeded, and falsy otherwise.
    def set_cas(key, value, cas, ttl=nil, options=nil)
      ttl ||= @options[:expires_in].to_i
      perform(:set, key, value, ttl, cas, options)
    end

    ##
    # Conditionally add a key/value pair, verifying existing CAS, only if the
    # key already exists on the server.  Returns the new CAS value if the
    # operation succeeded, or falsy otherwise.
    def replace_cas(key, value, cas, ttl=nil, options=nil)
      ttl ||= @options[:expires_in].to_i
      perform(:replace, key, value, ttl, cas, options)
    end

    # Delete a key/value pair, verifying existing CAS.
    # Returns true if succeeded, and falsy otherwise.
    def delete_cas(key, cas=0)
      perform(:delete, key, cas)
    end

  end
end


text:
package gov.nih.nci.cagrid.gts.service.db;

import gov.nih.nci.cagrid.gts.common.Database;

/**
 * @author Stephen Langella
 * @author Scott Oster
 * @author Shannon Hastings
 * @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella
 *          Exp $
 */
public interface DBManager {
	public AuthorityTable getAuthorityTable();

	public TrustedAuthorityTable getTrustedAuthorityTable();

	public TrustedAuthorityTrustLevelsTable getTrustedAuthorityTrustLevelsTable();

	public TrustLevelTable getTrustLevelTable();

	public PermissionsTable getPermissionsTable();

	public Database getDatabase();
}


text:
/*++
  This file contains an 'Intel UEFI Application' and is
  licensed for Intel CPUs and chipsets under the terms of your
  license agreement with Intel or your vendor.  This file may
  be modified by the user, subject to additional terms of the
  license agreement
--*/
/*++

Copyright (c)  2011 Intel Corporation. All rights reserved
This software and associated documentation (if any) is furnished
under a license and may only be used or copied in accordance
with the terms of the license. Except as permitted by such
license, no part of this software or documentation may be
reproduced, stored in a retrieval system, or transmitted in any
form or by any means without the express written consent of
Intel Corporation.

--*/

/** @file
  This is a simple shell application

  This should be executed with "/Param2 Val1" and "/Param1" as the 2 command line options!

**/

#include <WebServer.h>

DT_WEB_SERVER mWebServer;   ///<  Web server's control structure

/**
  Add a port to the list of ports to be polled.

  @param [in] pWebServer    The web server control structure address.

  @param [in] SocketFD      The socket's file descriptor to add to the list.

  @retval EFI_SUCCESS       The port was successfully added
  @retval EFI_NO_RESOURCES  Insufficient memory to add the port

**/
EFI_STATUS
PortAdd (
  IN DT_WEB_SERVER * pWebServer,
  IN int SocketFD
  )
{
  nfds_t Index;
  size_t LengthInBytes;
  nfds_t MaxEntries;
  nfds_t MaxEntriesNew;
  struct pollfd * pFdList;
  struct pollfd * pFdListNew;
  WSDT_PORT ** ppPortListNew;
  WSDT_PORT * pPort;
  EFI_STATUS Status;

  DBG_ENTER ( );

  //
  //  Use for/break instead of goto
  //
  for ( ; ; ) {
    //
    //  Assume success
    //
    Status = EFI_SUCCESS;

    //
    //  Create a new list if necessary
    //
    pFdList = pWebServer->pFdList;
    MaxEntries = pWebServer->MaxEntries;
    if ( pWebServer->Entries >= MaxEntries ) {
      MaxEntriesNew = 16 + MaxEntries;

      //
      //  The current FD list is full
      //  Allocate a new FD list
      //
      LengthInBytes = sizeof ( *pFdList ) * MaxEntriesNew;
      Status = gBS->AllocatePool ( EfiRuntimeServicesData,
                                   LengthInBytes,
                                   (VOID **)&pFdListNew );
      if ( EFI_ERROR ( Status )) {
        DEBUG (( DEBUG_ERROR | DEBUG_POOL,
                  "ERROR - Failed to allocate the FD list, Status: %r\r\n",
                  Status ));
        break;
      }

      //
      //  Allocate a new port list
      //
      LengthInBytes = sizeof ( *ppPortListNew ) * MaxEntriesNew;
      Status = gBS->AllocatePool ( EfiRuntimeServicesData,
                                   LengthInBytes,
                                   (VOID **) &ppPortListNew );
      if ( EFI_ERROR ( Status )) {
        DEBUG (( DEBUG_ERROR | DEBUG_POOL,
                  "ERROR - Failed to allocate the port list, Status: %r\r\n",
                  Status ));

        //
        //  Free the new FD list
        //
        gBS->FreePool ( pFdListNew );
        break;
      }

      //
      //  Duplicate the FD list
      //
      Index = MaxEntries;
      if ( NULL != pFdList ) {
        CopyMem ( pFdListNew,
                  pFdList,
                  Index * sizeof ( *pFdList ));
      }

      //
      //  Initialize the new entries in the FD list
      //
      for ( ; MaxEntriesNew > Index; Index++ ) {
        pFdListNew[ Index ].fd = -1;
        pFdListNew[ Index ].events = 0;
        pFdListNew[ Index ].revents = 0;
      }

      //
      //  Free the old FD list
      //
      if ( NULL != pFdList ) {
        gBS->FreePool ( pFdList );
      }

      //
      //  Switch to the new FD list
      //
      pWebServer->pFdList = pFdListNew;
      pFdList = pWebServer->pFdList;

      //
      //  Duplicate the port list
      //
      Index = MaxEntries;
      if ( NULL != pWebServer->ppPortList ) {
        CopyMem ( ppPortListNew,
                  pWebServer->ppPortList,
                  Index * sizeof ( *ppPortListNew ));
      }

      //
      //  Initialize the new entries in the port list
      //
      for ( ; MaxEntriesNew > Index; Index++ ) {
        ppPortListNew[ Index ] = NULL;
      }

      //
      //  Free the old port list
      //
      if ( NULL != pWebServer->ppPortList ) {
        gBS->FreePool ( pWebServer->ppPortList );
      }

      //
      //  Switch to the new port list
      //
      pWebServer->ppPortList = ppPortListNew;

      //
      //  Update the list size
      //
      pWebServer->MaxEntries = MaxEntriesNew;
    }

    //
    //  Allocate a new port
    //
    LengthInBytes = sizeof ( *pPort );
    Status = gBS->AllocatePool ( EfiRuntimeServicesData,
                                 LengthInBytes,
                                 (VOID **)&pPort );
    if ( EFI_ERROR ( Status )) {
      DEBUG (( DEBUG_ERROR | DEBUG_POOL,
                "ERROR - Failed to allocate the port, Status: %r\r\n",
                Status ));
      break;
    }

    //
    //  Initialize the port
    //
    pPort->RequestLength = 0;
    pPort->TxBytes = 0;

    //
    //  Add the socket to the FD list
    //
    pFdList[ pWebServer->Entries ].fd = SocketFD;
    pFdList[ pWebServer->Entries ].events = POLLRDNORM
                                             | POLLHUP;
    pFdList[ pWebServer->Entries ].revents = 0;

    //
    //  Add the port to the port list
    //
    pWebServer->ppPortList[ pWebServer->Entries ] = pPort;

    //
    //  Account for the new entry
    //
    pWebServer->Entries += 1;
    DEBUG (( DEBUG_PORT_WORK | DEBUG_INFO,
              "WebServer handling %d ports\r\n",
              pWebServer->Entries ));

    //
    //  All done
    //
    break;
  }

  //
  //  Return the operation status
  //
  DBG_EXIT_STATUS ( Status );
  return Status;
}

/**
  Remove a port from the list of ports to be polled.

  @param [in] pWebServer    The web server control structure address.

  @param [in] SocketFD      The socket's file descriptor to add to the list.

**/
VOID
PortRemove (
  IN DT_WEB_SERVER * pWebServer,
  IN int SocketFD
  )
{
  nfds_t Entries;
  nfds_t Index;
  struct pollfd * pFdList;
  WSDT_PORT ** ppPortList;

  DBG_ENTER ( );

  //
  //  Attempt to remove the entry from the list
  //
  Entries = pWebServer->Entries;
  pFdList = pWebServer->pFdList;
  ppPortList = pWebServer->ppPortList;
  for ( Index = 0; Entries > Index; Index++ ) {
    //
    //  Locate the specified socket file descriptor
    //
    if ( SocketFD == pFdList[ Index ].fd ) {
      //
      //  Determine if this is the listen port
      //
      if ( SocketFD == pWebServer->HttpListenPort ) {
        pWebServer->HttpListenPort = -1;
      }

      //
      //  Close the socket
      //
      close ( SocketFD );

      //
      //  Free the port structure
      //
      gBS->FreePool ( ppPortList[ Index ]);

      //
      //  Remove this port from the list by copying
      //  the rest of the list down one entry
      //
      Entries -= 1;
      for ( ; Entries > Index; Index++ ) {
        pFdList[ Index ] = pFdList[ Index + 1 ];
        ppPortList[ Index ] = ppPortList[ Index + 1 ];
      }
      pFdList[ Index ].fd = -1;
      pFdList[ Index ].events = 0;
      pFdList[ Index ].revents = 0;
      ppPortList[ Index ] = NULL;

      //
      //  Update the number of entries in the list
      //
      pWebServer->Entries = Entries;
      DEBUG (( DEBUG_PORT_WORK | DEBUG_INFO,
                "WebServer handling %d ports\r\n",
                pWebServer->Entries ));
      break;
    }
  }

  DBG_EXIT ( );
}

/**
  Process the work for the sockets.

  @param [in] pWebServer    The web server control structure address.

  @param [in] SocketFD      The socket's file descriptor to add to the list.

  @param [in] events        everts is a bitmask of the work to be done

  @param [in] pPort         The address of a WSDT_PORT structure

  @retval EFI_SUCCESS       The operation was successful
  @retval EFI_DEVICE_ERROR  Error, close the port

**/
EFI_STATUS
PortWork (
  IN DT_WEB_SERVER * pWebServer,
  IN int SocketFD,
  IN INTN events,
  IN WSDT_PORT * pPort
  )
{
  BOOLEAN bDone;
  size_t LengthInBytes;
  int NewSocket;
  EFI_STATUS OpStatus;
  struct sockaddr RemoteAddress;
  socklen_t RemoteAddressLength;
  EFI_STATUS Status;

  DEBUG (( DEBUG_PORT_WORK, "Entering PortWork\r\n" ));

  //
  //  Assume success
  //
  OpStatus = EFI_SUCCESS;

  //
  //  Handle input events
  //
  if ( 0 != ( events & POLLRDNORM )) {
    //
    //  Determine if this is a connection attempt
    //
    if ( SocketFD == pWebServer->HttpListenPort ) {
      //
      //  Handle connection attempts
      //  Accepts arrive as read events
      //
      RemoteAddressLength = sizeof ( RemoteAddress );
      NewSocket = accept ( SocketFD,
                           &RemoteAddress,
                           &RemoteAddressLength );
      if ( -1 != NewSocket ) {
        if ( 0 != NewSocket ) {
          //
          //  Add this port to the list monitored by the web server
          //
          Status = PortAdd ( pWebServer, NewSocket );
          if ( EFI_ERROR ( Status )) {
            DEBUG (( DEBUG_ERROR,
                      "ERROR - Failed to add the port 0x%08x, Status: %r\r\n",
                      NewSocket,
                      Status ));

            //
            //  Done with the new socket
            //
            close ( NewSocket );
          }
        }
        else {
          DEBUG (( DEBUG_ERROR,
                    "ERROR - Socket not available!\r\n" ));
        }

        //
        //  Leave the listen port open
        //
      }
      else {
        //
        //  Listen port error
        //  Close the listen port by returning error status
        //
        OpStatus = EFI_DEVICE_ERROR;
        DEBUG (( DEBUG_ERROR,
                  "ERROR - Failed to accept new connection, errno: 0x%08x\r\n",
                  errno ));
      }
    }
    else {
      //
      //  Handle the data received event
      //
      if ( 0 == pPort->RequestLength ) {
        //
        //  Receive the page request
        //
        pPort->RequestLength = recv ( SocketFD,
                                      &pPort->Request[0],
                                      DIM ( pPort->Request ),
                                      0 );
        if ( -1 == pPort->RequestLength ) {
          //
          //  Receive error detected
          //  Close the port
          //
          OpStatus = EFI_DEVICE_ERROR;
        }
        else {
          DEBUG (( DEBUG_REQUEST,
                    "0x%08x: Socket - Received %d bytes of HTTP request\r\n",
                    SocketFD,
                    pPort->RequestLength ));

          //
          //  Process the request
          //
          OpStatus = HttpRequest ( SocketFD, pPort, &bDone );
          if ( bDone ) {
            //
            //  Notify the upper layer to close the socket
            //
            OpStatus = EFI_DEVICE_ERROR;
          }
        }
      }
      else {
        //
        //  Receive the file data
        //
        LengthInBytes = recv ( SocketFD,
                               &pPort->RxBuffer[0],
                               DIM ( pPort->RxBuffer ),
                               0 );
        if ( -1 == LengthInBytes ) {
          //
          //  Receive error detected
          //  Close the port
          //
          OpStatus = EFI_DEVICE_ERROR;
        }
        else {
          DEBUG (( DEBUG_REQUEST,
                    "0x%08x: Socket - Received %d bytes of file data\r\n",
                    SocketFD,
                    LengthInBytes ));

          //
          // TODO: Process the file data
          //
        }
      }
    }
  }

  //
  //  Handle the close event
  //
  if ( 0 != ( events & POLLHUP )) {
    //
    //  Close the port
    //
    OpStatus = EFI_DEVICE_ERROR;
  }

  //
  //  Return the operation status
  //
  DEBUG (( DEBUG_PORT_WORK,
            "Exiting PortWork, Status: %r\r\n",
            OpStatus ));
  return OpStatus;
}

/**
  Scan the list of sockets and process any pending work

  @param [in] pWebServer    The web server control structure address.

**/
VOID
SocketPoll (
  IN DT_WEB_SERVER * pWebServer
  )
{
  int FDCount;
  struct pollfd * pPoll;
  WSDT_PORT ** ppPort;
  EFI_STATUS Status;

  DEBUG (( DEBUG_SOCKET_POLL, "Entering SocketPoll\r\n" ));

  //
  //  Determine if any ports are active
  //
  FDCount = poll ( pWebServer->pFdList,
                   pWebServer->Entries,
                   CLIENT_POLL_DELAY );
  if ( -1 == FDCount ) {
    DEBUG (( DEBUG_ERROR | DEBUG_SOCKET_POLL,
              "ERROR - errno: %d\r\n",
              errno ));
  }

  pPoll = pWebServer->pFdList;
  ppPort = pWebServer->ppPortList;
  while ( 0 < FDCount ) {
    //
    //  Walk the list of ports to determine what work needs to be done
    //
    if ( 0 != pPoll->revents ) {
      //
      //  Process this port
      //
      Status = PortWork ( pWebServer,
                          pPoll->fd,
                          pPoll->revents,
                          *ppPort );
      pPoll->revents = 0;

      //
      //  Close the port if necessary
      //
      if ( EFI_ERROR ( Status )) {
        PortRemove ( pWebServer, pPoll->fd );
        pPoll -= 1;
        ppPort -= 1;
      }

      //
      //  Account for this file descriptor
      //
      FDCount -= 1;
    }

    //
    //  Set the next port
    //
    pPoll += 1;
    ppPort += 1;
  }

  DEBUG (( DEBUG_SOCKET_POLL, "Exiting SocketPoll\r\n" ));
}

/**
  Create the HTTP port for the web server

  This routine polls the network layer to create the HTTP port for the
  web server.  More than one attempt may be necessary since it may take
  some time to get the IP address and initialize the upper layers of
  the network stack.

  After the HTTP port is created, the socket layer will manage the
  coming and going of the network connections until the last network
  connection is broken.

  @param [in] pWebServer  The web server control structure address.

**/
VOID
WebServerTimer (
  IN DT_WEB_SERVER * pWebServer
  )
{
  UINT16 HttpPort;
  struct sockaddr_in WebServerAddress;
  int SocketStatus;
  EFI_STATUS Status;

  DEBUG (( DEBUG_SERVER_TIMER, "Entering WebServerTimer\r\n" ));

  //
  //  Open the HTTP port on the server
  //
  do {
    do {
      //
      //  Complete the client operations
      //
      SocketPoll ( pWebServer );

      //
      //  Wait for a while
      //
      Status = gBS->CheckEvent ( pWebServer->TimerEvent );
    } while ( EFI_SUCCESS != Status );

    //
    //  Attempt to create the socket for the web server
    //
    pWebServer->HttpListenPort = socket ( AF_INET,
                                          SOCK_STREAM,
                                          IPPROTO_TCP );
    if ( -1 != pWebServer->HttpListenPort ) {
      //
      //  Set the socket address
      //
      ZeroMem ( &WebServerAddress, sizeof ( WebServerAddress ));
      HttpPort = PcdGet16 ( WebServer_HttpPort );
      DEBUG (( DEBUG_HTTP_PORT,
                "HTTP Port: %d\r\n",
                HttpPort ));
      WebServerAddress.sin_len = sizeof ( WebServerAddress );
      WebServerAddress.sin_family = AF_INET;
      WebServerAddress.sin_addr.s_addr = INADDR_ANY;
      WebServerAddress.sin_port = htons ( HttpPort );

      //
      //  Bind the socket to the HTTP port
      //
      SocketStatus = bind ( pWebServer->HttpListenPort,
                            (struct sockaddr *) &WebServerAddress,
                            WebServerAddress.sin_len );
      if ( -1 != SocketStatus ) {
        //
        //  Enable connections to the HTTP port
        //
        SocketStatus = listen ( pWebServer->HttpListenPort,
                                SOMAXCONN );
      }

      //
      //  Release the socket if necessary
      //
      if ( -1 == SocketStatus ) {
        close ( pWebServer->HttpListenPort );
        pWebServer->HttpListenPort = -1;
      }
    }

    //
    //  Wait until the socket is open
    //
  }while ( -1 == pWebServer->HttpListenPort );

  DEBUG (( DEBUG_SERVER_TIMER, "Exiting WebServerTimer\r\n" ));
}

/**
  Start the web server port creation timer

  @param [in] pWebServer  The web server control structure address.

  @retval EFI_SUCCESS         The timer was successfully started.
  @retval EFI_ALREADY_STARTED The timer is already running.
  @retval Other               The timer failed to start.

**/
EFI_STATUS
WebServerTimerStart (
  IN DT_WEB_SERVER * pWebServer
  )
{
  EFI_STATUS Status;
  UINT64 TriggerTime;

  DBG_ENTER ( );

  //
  //  Assume the timer is already running
  //
  Status = EFI_ALREADY_STARTED;
  if ( !pWebServer->bTimerRunning ) {
    //
    //  Compute the poll interval
    //
    TriggerTime = HTTP_PORT_POLL_DELAY * ( 1000 * 10 );
    Status = gBS->SetTimer ( pWebServer->TimerEvent,
                             TimerPeriodic,
                             TriggerTime );
    if ( !EFI_ERROR ( Status )) {
      DEBUG (( DEBUG_HTTP_PORT, "HTTP port timer started\r\n" ));

      //
      //  Mark the timer running
      //
      pWebServer->bTimerRunning = TRUE;
    }
    else {
      DEBUG (( DEBUG_ERROR | DEBUG_HTTP_PORT,
                "ERROR - Failed to start HTTP port timer, Status: %r\r\n",
                Status ));
    }
  }

  //
  //  Return the operation status
  //
  DBG_EXIT_STATUS ( Status );
  return Status;
}

/**
  Stop the web server port creation timer

  @param [in] pWebServer  The web server control structure address.

  @retval EFI_SUCCESS   The HTTP port timer is stopped
  @retval Other         Failed to stop the HTTP port timer

**/
EFI_STATUS
WebServerTimerStop (
  IN DT_WEB_SERVER * pWebServer
  )
{
  EFI_STATUS Status;

  DBG_ENTER ( );

  //
  //  Assume the timer is stopped
  //
  Status = EFI_SUCCESS;
  if ( pWebServer->bTimerRunning ) {
    //
    //  Stop the port creation polling
    //
    Status = gBS->SetTimer ( pWebServer->TimerEvent,
                             TimerCancel,
                             0 );
    if ( !EFI_ERROR ( Status )) {
      DEBUG (( DEBUG_HTTP_PORT, "HTTP port timer stopped\r\n" ));

      //
      //  Mark the timer stopped
      //
      pWebServer->bTimerRunning = FALSE;
    }
    else {
      DEBUG (( DEBUG_ERROR | DEBUG_HTTP_PORT,
                "ERROR - Failed to stop HTTP port timer, Status: %r\r\n",
                Status ));
    }
  }

  //
  //  Return the operation status
  //
  DBG_EXIT_STATUS ( Status );
  return Status;
}

/**
  Entry point for the web server application.

  @param [in] Argc  The number of arguments
  @param [in] Argv  The argument value array

  @retval  0        The application exited normally.
  @retval  Other    An error occurred.
**/
int
main (
  IN int Argc,
  IN char **Argv
  )
{
  DT_WEB_SERVER * pWebServer;
  EFI_STATUS Status;

  //
  //  Create a timer event to start HTTP port
  //
  pWebServer = &mWebServer;
  Status = gBS->CreateEvent ( EVT_TIMER,
                              TPL_WEB_SERVER,
                              NULL,
                              NULL,
                              &pWebServer->TimerEvent );
  if ( !EFI_ERROR ( Status )) {
    Status = WebServerTimerStart ( pWebServer );
    if ( !EFI_ERROR ( Status )) {
      //
      //  Run the web server forever
      //
      for ( ; ; ) {
        //
        //  Poll the network layer to create the HTTP port
        //  for the web server.  More than one attempt may
        //  be necessary since it may take some time to get
        //  the IP address and initialize the upper layers
        //  of the network stack.
        //
        WebServerTimer ( pWebServer );

        //
        //  Add the HTTP port to the list of ports
        //
        Status = PortAdd ( pWebServer, pWebServer->HttpListenPort );
        if ( !EFI_ERROR ( Status )) {
          //
          //  Poll the sockets for activity
          //
          do {
            SocketPoll ( pWebServer );
          } while ( -1 != pWebServer->HttpListenPort );

          //
          //  The HTTP port failed the accept and was closed
          //
        }

        //
        //  Close the HTTP port if necessary
        //
        if ( -1 != pWebServer->HttpListenPort ) {
          close ( pWebServer->HttpListenPort );
          pWebServer->HttpListenPort = -1;
        }
//
// TODO: Remove the following test code
//  Exit when the network connection is broken
//
break;
      }

      //
      //  Done with the timer event
      //
      WebServerTimerStop ( pWebServer );
      Status = gBS->CloseEvent ( pWebServer->TimerEvent );
    }
  }

  //
  //  Return the final status
  //
  DBG_EXIT_STATUS ( Status );
  return Status;
}


text:
:- module(man_word_index,
          [ pce_make_manual_index/0,
            pce_make_manual_index/1,    % +File
            pce_make_manual_index/2     % +File, -Reference
          ]).
:- use_module(user:library(pce)).       % HACK: needed for build process
:- use_module(library(pce)).
:- use_module(library(pce_manual)).
:- require([ atomic_list_concat/2
           ]).

:- dynamic
    use_gui/0,
    quiet/0.

quiet.

:- pce_begin_class(man_index_manager, object,
                   "Dummy object to exploit XPCE autoloader").

make_index(_IM, IndexFile:name, Index:chain_table) :<-
    asserta(use_gui),
    pce_make_manual_index(IndexFile, Index).

:- pce_end_class.

%       make_manual_index([+File, [-Reference]])
%
%       Creates a word index for the manual system.  This index is a
%       chain_table mapping all words that appear in the manual onto
%       a chain of card identifiers.
%
%       At the moment only all class-related cards (classes, variables,
%       methods and class-variables are processed.

pce_ifhostproperty(prolog(quintus),
(   access_file(File, Mode) :-
        can_open_file(File, Mode))).

pce_make_manual_index :-
    absolute_file_name(pce('man/reference/index.obj'), File),
    pce_make_manual_index(File).
pce_make_manual_index(File, @man_tmp_index) :-
    pce_make_manual_index(File).
pce_make_manual_index(File) :-
    prepare_manual,
    access_file(File, write),      % just make sure!
    !,
    new(Ch, chain),                 % gather all built-in classes
    send(@man_tmp_view, format, 'Collecting built-in classes ... '),
    send(@man_tmp_view, synchronise),
    send(@classes, for_all,
         if(@arg2?creator == built_in,
            message(Ch, append, @arg2))),
    send(Ch, sort, ?(@arg1?name, compare, @arg2?name)),
    send(@man_tmp_view, format, '%d classes.\n', Ch?size),
    send(@man_tmp_view, synchronise),
    send(Ch, for_all, message(@prolog, make_class_index, @arg1)),
    make_module_index,
    send(@man_tmp_view, format, '\n\nCleaning index table'),
    send(@man_tmp_view, synchronise),
    clean_index(@man_tmp_index),
    send(@man_tmp_view, format, 'Cleaning done\n\n'),
    send(@man_tmp_view, format, 'Saving index table to %s ... ', File),
    send(@man_tmp_view, synchronise),
    send(@man_tmp_index, save_in_file, File),
    send(@man_tmp_view, format, '%d bytes. Finished.\n', file(File)?size),
    send(@man_tmp_view, synchronise),
    (   get(@man_tmp_view?frame, member, dialog, D),
        get(D, member, quit, Quit),
        get(D, member, abort, Abort)
    ->  send(Quit, active, @on),
        send(Abort, active, @off)
    ;   true
    ).
pce_make_manual_index(File) :-
    send(file(File), report, error, 'Cannot write %s', File),
    fail.

make_class_index(Class) :-
    get(Class, name, Name),
    (   get(@man_tmp_view, column, C),
        C > 64
    ->  send(@man_tmp_view, newline)
    ;   true
    ),
    send(@man_tmp_view, format, '(%s', Name),
    send(@man_tmp_view, synchronise),
    new(Objs, chain),
    send(Objs, merge, Class?send_methods),
    send(Objs, merge, Class?get_methods),
    send(Objs, for_all,
         if(message(@arg1?message, instance_of, c_pointer),
            message(Objs, delete, @arg1))),
    send(Class?instance_variables, for_all,
         message(Objs, append, @arg1)),
    send(Objs, merge, Class?class_variables),
    send(Objs, append, Class),
    send(Objs, for_all,
         message(@prolog, make_card_index, @arg1)),
    send(Objs, done),
    send(@man_tmp_view, format, ') ', Name),
    send(@man_tmp_view, synchronise).

make_card_index(Card) :-
    get(Card, man_id, Id),
    (   get(Card, man_summary, Summary)
    ->  word_index(Summary, Id)
    ;   true
    ),
    (   get(Card, man_description, Description)
    ->  word_index(Description, Id)
    ;   true
    ).

:- pce_global(@man_tmp_view, make_man_tmp_view).
:- pce_global(@man_tmp_index, new(chain_table)).
:- pce_global(@man_tmp_index_regex, make_index_regex).

make_index_regex(R) :-
    new(R, regex('@?[a-zA-Z]\\w+')),
    send(R, compile, @on).

make_man_tmp_view(V) :-
    use_gui,
    !,
    new(V, view('Build PCE manual index')),
    send(new(D, dialog), below, V),
    send(D, append, new(Quit, button(quit, message(D, destroy)))),
    send(Quit, active, @off),
    send(D, append,
         button(abort,
                and(message(@display, confirm,
                            'Abort generation of search index?'),
                    message(@prolog, halt)))),
    send(D, append, label(reporter), right),
    send(V, open),
    send(V, wait),
    send(V, format, 'Building PCE manual index.\n'),
    send(V, format, 'This process will take several minutes.\n\n').
make_man_tmp_view(V) :-
    new(V, man_index_output).

word_index(Text, Id) :-
    send(@man_tmp_index_regex, for_all, Text,
         message(@man_tmp_index, append,
                 ?(@arg1, register_value, @arg2, 0, name)?downcase, Id)).

:- pce_begin_class(man_index_output, object,
                   "Dummy drain to catch feedback in non-gui mode").

synchronise(_) :->
    true.

column(_, C) :<-
    C = 0.

format(_, Fmt:char_array, Args:any ...) :->
    (   quiet
    ->  true
    ;   Msg =.. [format, Fmt | Args],
        send(@pce, Msg),
        flush
    ).

frame(_, _) :<-
    fail.

:- pce_end_class.

                 /*******************************
                 *             MANUAL           *
                 *******************************/

prepare_manual :-
    use_gui,
    !,
    manpce.
prepare_manual :-
    new(Directory, directory('$PCEHOME/man/reference')),
    new(@man_space, man_space(reference, Directory)),
    send(@pce, send_method,         % make it silent
         send_method(report, vector('any ...'), new(and))).

                 /*******************************
                 *        NON-CLASS CARDS       *
                 *******************************/

non_class_module(predicates).
non_class_module(objects).
non_class_module(tools).

make_module_index :-
    send(@man_tmp_view, format, '\n\n'),
    non_class_module(Module),
    send(@man_tmp_view, format, '%s index ... ', Module),
    send(@man_tmp_view, synchronise),
    make_module_index(Module),
    send(@man_tmp_view, format, 'done.\n'),
    send(@man_tmp_view, synchronise),
    fail.
make_module_index.

make_module_index(ModuleName) :-
    (   object(@manual)
    ->  get(@manual, space, ManSpace)
    ;   ManSpace = @man_space       % non-gui building
    ),
    get(ManSpace, module, ModuleName, @on, Module),
    send(Module?id_table, for_all,
         message(@prolog, index_card, ModuleName, @arg1, @arg2)).

index_card(Module, CardId, Card) :-
    send(@man_tmp_view, synchronise),
    atomic_list_concat([$, Module, $, CardId], Id),
    (   get(Card, man_summary, Summary)
    ->  word_index(Summary, Id)
    ;   true
    ),
    (   get(Card, man_description, Description)
    ->  word_index(Description, Id)
    ;   true
    ).

                 /*******************************
                 *             CLEAN            *
                 *******************************/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
These words appear in more then 500 cards and probably have little value
in specifying search  options.   Deleting   them  significantly  reduces
memory and saves time with loading and processing the index.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

noindex(and).
noindex(will).
noindex(was).
noindex(using).
noindex(is).
noindex(or).
noindex(not).
noindex(the).
noindex(a).
noindex(an).
noindex(class).
noindex(object).
noindex(method).
noindex(that).
noindex(also).
noindex(see).
noindex(it).
noindex(to).
noindex(used).
noindex(when).
noindex(by).
noindex(of).
noindex(with).
noindex(from).
noindex(if).
noindex(in).
noindex(are).
noindex(be).
noindex(this).

clean_index(Table) :-
    noindex(Word),
    get(Table, member, Word, Chain),
    get(Chain, size, Size),
    send(@man_tmp_view, format, 'Deleted "%s", %d entries\n', Word, Size),
    send(@man_tmp_view, synchronise),
    send(Table, delete, Word),
    fail.
clean_index(Table) :-
    send(Table, for_all, message(@arg2, unique)).


text:
comments: true
date: 2010-07-18 10:03:13
layout: post
slug: who-makes-those-videos
title: Who Makes Those Videos?
wordpress_id: 400
categories:
- business
- Humour
tags:
- pragprog
- viral videos
---

> Sometimes bad can be good. YouTube came out with a new video editor and [got the brilliant Yeshmin Blechin to explain it](http://www.youtube.com/watch?v=1VbMLOcbK74). I'll go so far as to say that that may be one of the best video product demos I've ever seen. And that's pretty far. One thing that the video demonstrates clearly is that YouTube is not Microsoft.

...

Microsoft is better known for atrociously bad commercials and demo videos—and PowerPoint presentations and sales meeting pep talks by Steve Ballmer channeling that gorilla in the suitcase commercial—than for performance art catastrophes, but it's pretty hard to top [Bill Gates releasing a horde of live, hungry mosquitos on the audience](http://www.foxnews.com/story/0,2933,488348,00.html) at a TED conference. Angelina Jolie was among the victims. Yep, she of the bee-stung lips left TED with a mosquito-bit something. I can't be more specific because the particular part of her anatomy that got bit was left out of the story. What passes for journalism today.

via [The Pragmatic Bookshelf](http://pragprog.com/magazines/2010-07/shady-illuminations).

Introduced me to some great publicity I missed. Very entertaining to watch the videos.

And don't miss the successful [Old Spice videos](http://www.youtube.com/user/oldspice?feature=chclk), if you haven't seen them already.


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class API_model extends MY_Model {

  /**
   * Array of strings for views, filenames, etc.
   *
   * @var array
   */
  public $strings = array();

  /**
   * Array of tables used.
   *
   * @var array
   */
  public $tables = array();

  /**
   * Array of variables to be used with API queries.
   *
   * @var array
   */
  public $api_vars = array();

  public function __construct() {
    parent::__construct();
    $this->load->config('variation_database');

    // initialize common strings
    $this->strings = $this->config->item('strings');
    // initialize db tables data
    $this->tables = $this->config->item('tables');
    // initialize search validation values
    $this->api_vars = $this->config->item('api');
  }

  /**
   * Sanitize, validate inputs and perform search
   *
   * @author Nikhil Anand
   * @param string $get_variables
   *    The $_GET array
   * @return void
   */
  public function api_bootstrap($get_variables) {
    $validation_message = '';

    /* Sanitization */

    $format  = @trim(strip_tags($get_variables["format"]));
    $type    = @trim(strip_tags($get_variables["type"]));
    $method  = @trim(strip_tags($get_variables["method"]));
    $version = @trim(strip_tags($get_variables["version"]));
    // Make sure we trim every search term and that there are no null terms
    $terms   = @explode(",", trim(strip_tags($get_variables["terms"])));
    for ($i=0; $i < count($terms); $i++) {
      $terms[$i] = trim(strip_tags($terms[$i]));
      if ($terms[$i] == "") {
        unset($terms[$i]);
      }
    }

    /* Validation */

    // Format
    if ($format && !in_array($format, $this->api_vars['format'])) {
      $validation_message = "Invalid format specified";
    }
    else if (!$format) {
      $format = $this->api_vars['format'][0]; // default
    }

    // Type of search
    if ($type && !in_array($type, $this->api_vars['type'])) {
      $validation_message = "Invalid search type specified";
    }
    else if (!$type) {
      $type = $this->api_vars['type'][0]; // default
    }

    // Download method
    if ($method && !in_array($method, $this->api_vars['method'])) {
      $validation_message = "Invalid download method specified";
    }
    else if (!$method) {
      $method = $this->api_vars['method'][0]; // default
    }

    // Database version
    if ($version) {
      $versions_results = $this->variations_model->get_all_db_version_info();
      $versions = array();
      foreach ($versions_results as $versions_result) {
        $versions[] = $versions_result->version; // get all version numbers
      }
      if ( ! in_array($version, $versions)) {
        $validation_message = "Invalid version number. Please see the API page for a list of versions.";
      }
    }
    else if ( ! $version) {
      $version = $this->version; // default
    }

    // Search terms (validation method depends on type of search)
    if ( ! $this->_api_validate_terms($type, $terms)) {
      $validation_message = "One or more of your search terms is malformed for the type of search specified.";
    }

    if ($validation_message != '') {
      header("Content-type: text/plain");
      print $validation_message;
      exit;
    }
    else {
      $search_results = $this->_api_search($type, $terms, $version);
      if(strcmp(get_class($search_results),'CI_DB_mysql_driver')==0){
      		$prog_load = TRUE;
      }
      return $this->_api_result($search_results, $format, $type, $terms, $method, $prog_load);
    }
  }

  /**
   * Validate search terms by invoking the appropriate method for each search type
   *
   * @author Nikhil Anand
   * @param string $type
   *    Type of search (e.g. variant, PubMed ID, etc)
   * @param string $terms
   *    An array of search terms for the type of search
   * @return void
   */
  public function _api_validate_terms($type, $terms) {

    // Check if we have any search terms
    if (!empty($terms)) {
      switch ($type) {
        case 'position':
          return $this->_api_validate_terms_variant($terms);
          break;

        case 'gene':
          return $this->_api_validate_terms_gene($terms);
          break;

        default:
          return $this->_api_validate_terms_variant($terms);
          break;
      }
    }
    else if ($type == 'genelist') { // Special case for gene list
     return true;
    }
    else if ($type == 'variantlist') { // Special case for variant list
     return true;
    }
    else {
      header("Content-type: text/plain");
      print "You need to specify some search terms.";
      exit;
    }

  }

  /**
   * Helper to search term validation method
   * Validate genes (e.g. gjb6, GJB6)
   *
   * @author Nikhil Anand
   * @param string $terms
   *    An array of variants
   * @return void
   */
  public function _api_validate_terms_gene($terms) {
    $valid = TRUE;

    foreach ($terms as $term) {
      if (!preg_match('/[a-zA-Z]{2,}[0-9]{0,2}/', $term)) {
        print "\"$term\" is malformed for a gene search.\r\n";
        $valid = FALSE;
      }
    }

    return $valid;
  }

  /**
   * Helper to search term validation method
   * Validate variants (e.g. chr7:128917)
   *
   * @author Nikhil Anand
   * @param string $terms
   *    An array of variants
   * @return void
   */
  public function _api_validate_terms_variant($terms) {
    $valid = TRUE;

    foreach ($terms as $term) {
      if (!preg_match('/chr\d{1,2}+:\d+/', $term)) {
        print "\"$term\" is malformed for a variant search.\r\n";
        $valid = FALSE;
      }
    }

    return $valid;
  }

  /**
   * Perform the actual search
   *
   * @author Nikhil Anand
   * @param string $format
   *    Output format (CSV, tab-delimited, JSON or XML)
   * @param string $type
   *    Type of search
   * @param string $terms
   *    An array of (validated) search terms
   * @param string $version
   *    Version of the database to search
   * @return void
   */
  public function _api_search($type = 'position', $terms, $version) {
    $search_results = array();

    // Gene list
    if ($type == 'genelist') {
      $fields = implode(',', $this->api_vars['genelist']);
      $query = $this->db->select($fields)
                        ->get($this->tables['variant_count']);
      foreach ($query->result_array() as $row) {
        $search_results[] = $row;
      }
    }

    // Variant list
    else if ($type == 'variantlist') {
      $fields = implode(',', $this->api_vars['variantlist']);
      $query = $this->db->select($fields)
                        ->where('variation IS NOT NULL', NULL, FALSE)
                        ->order_by('variation', 'asc')
                        ->get($this->tables['vd_live']);
      foreach ($query->result_array() as $row) {
        $search_results[] = $row;
      }
    }

    // Variants of a gene
    else if ($type == 'gene') {

    		//estimate memory consumption incase it is exhorbitant
    		$prog_load = FALSE;
    		$est_result_size = 0;
    		foreach ($terms as $term){
    			$est_result_size += $this->variations_model->count_variants_by_gene(strtoupper($term));
    		}

    		if($est_result_size >= 1000){ //1Kb in bytes, TODO: for implementation, set this value in config
    			//progressive loading needed
    			$prog_load = TRUE;
    		}

    		foreach ($terms as $term) {
    			$search_results = $this->variations_model->get_variants_by_gene(strtoupper($term),NULL,$prog_load);
    		}

    }

    // Variant position or exact position
    else {
      if ($type == 'exactposition') {
        // 'exactposition' uses exact search
        $fuzzy_search = FALSE;
      }
      else {
        // 'position' uses fuzzy search
        $fuzzy_search = TRUE;
      }
      // For each search term, build a query statement and execute
      foreach ($terms as $term) {
        $query_results = $this->variations_model->get_variants_by_position($term, $this->tables['vd_live'], $fuzzy_search);
        if (empty($query_results)) {
          // this term produced no results
          $search_results[$term] = NULL;
        }
        else {
          // this term produced results, now gather all results
          foreach ($query_results as $query_result) {
            $search_results[$query_result->variation] = (array) $query_result;
          }
        }
      } // End foreach
    } // End else

    return $search_results;
  }

  /**
   * Pass search results to the appropriate helper public functions for display or download
   *
   * @author Nikhil Anand
   * @param string $search_results
   *    The array of search results
   * @param string $format
   *    Output format (CSV, tab-delimited, JSON, XML)
   * @param string $type
   *    Type of search
   * @param string $terms
   *    An array of (validated) search terms
   * @param string $method
   *    Download/display method
   * @return void
   */
  public function _api_result($search_results, $format, $type, $terms, $method, $prog_load=FALSE) {
    switch ($format) {
      case 'tab':
//         return $this->_api_result_text($search_results, $method, $type, "\t");
			return $this->_api_result_text_dload($search_results, $terms, $method, $type, ".tsv", "\t", $prog_load);
        break;

      case 'csv':
//         return $this->_api_result_text($search_results, $method, $type, ",");
      	return $this->_api_result_text_dload($search_results, $terms, $method, $type, ".csv", ",", $prog_load);
        break;

      case 'json':
//         return $this->_api_result_json($search_results, $method);
      	return $this->_api_result_json_dload($search_results, $terms, $method, $type);
        break;

      case 'xml':
//         return $this->_api_result_xml($search_results, $method);
      	return $this->_api_result_xml_dload($search_results, $terms, $method, $type);
        break;

      case 'vcf':
        if ($type == 'variantlist') {
//           return $this->_api_result_vcf($search_results, $method);
          return $this->_api_result_vcf_dload($search_results, $terms, $method, $type);
          break;
        } else {
          header("Content-type: text/plain");
          print "VCF output is only valid for query of type 'variantlist'";
          exit;
        }

      default:
        return $this->_api_result_text_dload($search_results, $terms, $method, $type, 'tab', "\t", $prog_load);
        break;
    }
  }

  /**
   * _api_result_text_dload
   * forces a download of text data in a delimited way
   *
   * @author Rob Marini
   * @param CI_DB_MYSQL Object $search_results
   * 	contains the query and results and connecting information
   * @param string $terms
   *    An array of (validated) search terms (used as a WHERE clause of MYSQL statement)
   * @param string $method
   *    Download/display method
   * @param string $type
   *    Type of search
   * @param string $suffix
   * 	the file extension
   * @param string $delimiter
   * 	the delemitting character
   * @return void
   */
  public function _api_result_text_dload($search_results, $terms, $method, $type, $suffix, $delimiter, $prog_load=FALSE){

  	if(strcmp(strtolower($method), 'plain') == 0){

  		return $this->_api_result_text($search_results, $method, $type, $suffix, $delimiter);

  	} else { //default is to download

  		if($prog_load){

  			$this->load->helper('download');

  			$filename = "";
  			foreach($terms as $term){
  				$filename .= $term;
  			}
  			$filename .= "_variants_list" . $suffix;
  			$num_rows_per_chunk = ceil($this->config->item('chunk_load_limit') / $this->config->item('mem_per_row_ratio'));
			$upperbound = get_query_result_size(clone($search_results))[0];
  			$bounds = [1,$upperbound]; //1 for all items
  			$newline = "\r\n";
  			force_prog_dload($search_results, $num_rows_per_chunk, $bounds, $filename, $delimiter, $newline);

  		} else{ // get all results and hold in memory to then download

  			$this->load->dbutil();
  			$this->load->helper('file');
  			$this->load->helper('download');
  			$newline = "\r\n";
  			$data = $this->dbutil->csv_from_result($search_results, $delimiter, $newline);

  			$filename = "";
  			foreach($terms as $term){
  				$filename .= $term;
  			}
  			$filename .= "_variants_list" . $suffix;

  			force_download($filename,$data); //automatically exits
  		}

  	}

  }

  /**
   *
   * Helper function that provides plain text data for file streaming
   *
   * @author Nikhil Anand
   * @author Sean Ephraim
   * @author Rob Marini
   * @param string $search_results
   *    The array of search results
   * @param string
   * @param string
   * @param string $delimiter
   *    Any delimiter with which to separate results
   * @return string
   */
  public function _api_result_text_4stream($search_results, $delimiter = ",", $newline = "\r\n", $col_headers = TRUE) {

  	if($col_headers){
  		$output = '#';

	  	// Special case for genelist query
	  	if ($type == 'genelist') {
	  		$output .= implode($delimiter, $this->api_vars['genelist']) . $newline;
	  	}

	  	// Special case for variation list
	  	else if ($type == 'variantlist') {
	  		$output .= implode($delimiter, $this->api_vars['variantlist']) . $newline;
	  	}

	  	// Add column headers for all others
	  	else {
	  		$output .= implode($delimiter, $this->variations_model->get_variant_fields()) . $newline;
	  	}
  	} else {

	  	// Using 'implode' would have been neater, but we need to specify NULL for missing values
	  	foreach ($search_results as $result => $columns) {
	  		if (is_array($columns)) {
	  			foreach ($columns as $column) {
	  				if (trim($column) == '') {
	  					$output .= "NULL";
	  				} else {
	  					$output .= $column;
	  				}
	  				$output .= $delimiter;
	  			}
	  		}

	  		// Remove the last delimiter and add a newline
	  		$output = substr($output, 0, -1);
	  		$output .= $newline;
	  	}
  	}

  	return($output);
  }

  /**
   * _api_result_xml_dload
   * forces a download of text data in xml format
   *
   * @author Rob Marini
   * @param CI_DB_MYSQL Object $search_results
   * 	contains the query and results and connecting information
   * @param string $terms
   *    An array of (validated) search terms (used as a WHERE clause of MYSQL statement)
   * @param string $method
   *    Download/display method
   * @param string $type
   *    Type of search
   * @return void
   */
  public function _api_result_xml_dload($search_results, $terms, $method, $type){

  	if(strcmp(strtolower($method), 'plain') == 0){

  		return $this->_api_result_xml($search_results, $method);

  	} else { //default is to download
	  	$this->load->dbutil();
	  	$this->load->helper('file');
	  	$this->load->helper('download');

	  	$config = array(
	  			'root'		=>	'root',
	  			'element'	=>	'element',
	  			'newline'	=>	"\n",
	  			'tab'		=>	"\t"
	  			);

	  	$data = $this->dbutil->xml_from_result($search_results, $config);

	  	$filename = "";
	  	foreach($terms as $term){
	  		$filename .= $term;
	  	}
	  	$filename .= "_variants_list" . ".xml";

	  	force_download($filename,$data);

  	}

  }

  /**
   * _api_result_json_dload
   * forces a download of text data in a json format
   *
   * @author Nikhil Anand
   * @author Sean Ephraim
   * @author Rob Marini
   * @param CI_DB_MYSQL Object $search_results
   * 	contains the query and results and connecting information
   * @param string $terms
   *    An array of (validated) search terms (used as a WHERE clause of MYSQL statement)
   * @param string $method
   *    Download/display method
   * @param string $type
   *    Type of search
   * @return void
   */
  public function _api_result_json_dload($search_results, $terms, $method, $type){

  	// this is needed in order to modify headers
  	ob_end_clean();

  	//Send headers depending on download method
  	if ($method == "download") {
  		header('Content-type: application/json');
  		header("Content-Disposition: attachment; filename=" . $this->strings['site_short_name'] . "-data." . $this->_api_iso_date() . ".json");
  		header("Pragma: no-cache");
  		header("Expires: 0"); //DANGEROUS AND MUST BE CHANGED
  	} else {
  		header('Content-type: text/plain');
  	}

  	if(strcmp(strtolower($method), 'plain') == 0){

  		print json_encode($search_results);

  	} else { //default is to download

  		$this->load->helper('file');
  		$this->load->helper('download');
  		$data = json_encode($search_results->result());

  		$filename = "";
  		foreach($terms as $term){
  			$filename .= $term;
  		}
  		$filename .= "_variants_list" . ".json";

  		force_download($filename,$data);

  	}

  }

  /**
   * Return variant list in VCF format. Will be used in Galaxy
   *
   * NOTE: This is only valid for "type=variantlist".
   *
   * @author Nikhil Anand
   * @author Sean Ephraim
   * @author Rob Marini
   * @param CI_DB_MYSQL Object $search_results
   * 	contains the query and results and connecting information
   * @param string $terms
   *    An array of (validated) search terms (used as a WHERE clause of MYSQL statement)
   * @param string $method
   *    Download/display method
   * @param string $type
   *    Type of search
   * @return void
   */
  public function _api_result_vcf_dload($search_results, $terms, $method, $type) {
  	// this is needed in order to modify headers
  	ob_end_clean();

  	//Send headers depending on download method
  	if ($method == "download") {
  		$prefix = strtolower($this->strings['site_full_name']);
  		$prefix = str_replace(array(' ', '.'), '-', $prefix);
  		header('Content-type: application/vcf');
  		header("Pragma: no-cache");
  		header("Expires: 0"); //DANGEROUS AND MUST BE CHANGED
  		header('Content-Disposition: attachment; filename="' . $prefix . '-' . $this->_api_iso_date() . '.vcf"');
  	} else {
  		header('Content-type: text/plain');
  	}

  	// Standard VCF headers
  	$fields = $this->api_vars['variantlist'];
  	$output = "##fileformat=VCFv4.1\r\n";
  	foreach ($fields as $field) {
  		if ($field === "disease") {
  			$output .= "##INFO=<ID=$field,Number=.,Type=String,Description=\"\">";
  		}
  		else if ($field === "id") {
  			$output .= "##INFO=<ID=$field,Number=1,Type=Flag,Description=\"Variant ID, internal use only\">";
  		}
  		else {
  			$output .= "##INFO=<ID=$field,Number=1,Type=Flag,Description=\"\">";
  		}
  		$output .= "\r\n";
  	}
  	$output .= "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\r\n";
  	print $output;

  	// Iteratively build array and write to output
  	foreach ($search_results as $result) {

  		preg_match('/(chr.*):(\d+)\:(\D{1})>(\D{1})/', $result["variation"], $variant_info);

  		$vcf_id = $result["dbsnp"];
  		if (trim($result["dbsnp"]) == '')
  		{
  			$vcf_id = ".";
  		}

  		// Fill in '.' (VCF standard) if no values exist for field
  		foreach ($result as $key => $value) {
  			if (trim($value) == '') {
  				$result[$key] = '.';
  			}
  		}
  		$info_string = "";
  		foreach ($fields as $field) {
  			$info_string .= "$field=" . $result[$field];
  			if ($field !== end($fields)) {
  				$info_string .= ";";
  			}
  		}

  		$write_array = array(
  				$variant_info[1],
  				$variant_info[2],
  				$vcf_id,
  				$variant_info[3],
  				$variant_info[4],
  				".", // QUAL
  				".", // FILTER
  				$info_string
  		);

  		if(strcmp(strtolower($method), 'plain') == 0){

  			print implode($write_array, "\t") . "\n";

  		} else { //default is to download

  			$data = implode($write_array, "\t") . "\n";

	  		$filename = "";
	  		foreach($terms as $term){
	  			$filename .= $term;
	  		}
	  		$filename .= "_variants_list" . ".vcf";

	  		force_download($filename,$data);
  		}

  	}
  }

  /**
   * ------ For Plain print to screen results ------ 3/29/2018
   * Helper public function to display search results
   * Shows CSV or tab-delimited results
   *
   * @author Nikhil Anand
   * @author Sean Ephraim
   * @param string $search_results
   *    The array of search results
   * @param string $method
   *    Download/display method
   * @param string $type
   *    Type of search
   * @param string $delimiter
   *    Any delimiter with which to separate results
   * @return void
   */
  public function _api_result_text($search_results, $method, $type, $delimiter) {
    // this is needed in order to modify headers
    ob_end_clean();

    //Send download headers depending on download method
    if ($method == "download") {
      if ($delimiter == ',') {
        $extension = ".csv";
      }
      else {
        $extension = ".txt";
      }
      $filename = $this->strings['site_short_name'] . "-data." . $this->_api_iso_date() . $extension;
      header("Content-Disposition: attachment; filename=$filename");
      header("Pragma: no-cache");
      $epoc1 = new DateTime('1970-01-01 12:00:00',new DateTimezone(date_default_timezone_get()));
      $expire_str = $epoc1->format('D, d M Y H:i:s');
      header("Expires: " . $expire_str);
    } else {
      header("Content-type: text/plain");
    }

    $output = '#';

    // Special case for genelist query
    if ($type == 'genelist') {
      $output .= implode($delimiter, $this->api_vars['genelist'])."\r\n";
    }

    // Special case for variation list
    else if ($type == 'variantlist') {
      $output .= implode($delimiter, $this->api_vars['variantlist'])."\r\n";
    }

    // Add column headers for all others
    else {
      $output .= implode($delimiter, $this->variations_model->get_variant_fields()) . "\r\n";
    }

    // Using 'implode' would have been neater, but we need to specify NULL for missing values
    foreach ($search_results as $result => $columns) {
      if (is_array($columns)) {
        foreach ($columns as $column) {
          if (trim($column) == '') {
            $output .= "NULL";
          } else {
            $output .= $column;
          }
          $output .= $delimiter;
        }
      }

      // Remove the last delimiter and add a newline
      $output = substr($output, 0, -1);
      $output .= "\r\n";
    }

    print $output;
  }

  /**
   * ------ For Plain print to screen results ------ 3/29/2018
   * Helper public function to display search results
   * Shows XML-formatted results
   *
   * @author Sean Ephraim
   * @author Nikhil Anand
   * @param string $search_results
   *    The array of search results
   * @param string $method
   *    Download/display method
   * @return void
   */
  public function _api_result_xml($search_results, $method) {
    // this is needed in order to modify headers
    ob_end_clean();

    //Send headers depending on download method
    if ($method == "download") {
      header('Content-type: application/xml');
      header("Pragma: no-cache");
      header("Expires: 0");
    } else {
      header('Content-type: text/plain');
    }

    // Create a new DOM object
    $output = new DOMDocument();
    $output->formatOutput = true;

    // Create the root element
    $root = $output->createElement("results");
    $output->appendChild($root);

    // Iterate through results; create children
    // http://css.dzone.com/news/creating-xml-documents-php
    foreach ($search_results as $search_value => $columns) {

      $result = $root->appendChild($output->createElement("result"));
      $result->appendChild($output->createAttribute("value"))->appendChild($output->createTextNode($search_value));

      if (is_array($columns)) {
        foreach ($columns as $column => $value) {
          $result->appendChild($output->createElement($column, $value));
        }
      }
    }

    echo $output->saveXML();
  }

  /**
   * Get the ISO8601-formatted date
   *
   * @author Nikhil Anand
   * @param string $time
   *    If specified, this timestamp is ISO8601-formatted.
   *    If not, current time is returned
   * @return void
   */
  public function _api_iso_date($time=false) {
      if(!$time) $time=time();
      return date("Y-m-d", $time) . 'T' . date("H:i:s", $time);
  }
}

/* End of file api_model.php */
/* Location: ./application/models/api_model.php */


text:
SELECT
    benanntesgebiet.t_id AS tid,
    benanntesgebiet.benanntesgebiet_von,
    benanntesgebiet.flaeche,
    cast(benanntesgebiet.t_datasetname AS INT) AS gem_bfs,
    0 AS los,
    aimport.importdate AS lieferdatum
FROM
    agi_dm01avso24.gebaeudeadressen_benanntesgebiet AS benanntesgebiet
    LEFT JOIN agi_dm01avso24.t_ili2db_basket AS basket
        ON benanntesgebiet.t_basket = basket.t_id
    LEFT JOIN
    (
        SELECT
            max(importdate) AS importdate,
            dataset
        FROM
            agi_dm01avso24.t_ili2db_import
        GROUP BY
            dataset
    ) AS  aimport
        ON basket.dataset = aimport.dataset
;


text:
package com.egonny.facepunch.views;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.egonny.facepunch.FPApplication;
import com.egonny.facepunch.R;
import com.egonny.facepunch.util.ImageLoaderHelper;
import com.egonny.facepunch.util.Keys;
import org.json.JSONException;
import org.json.JSONObject;

public class SoundcloudView extends MediaView {

	String mUrl;

	public SoundcloudView(Context context) {
		super(context);

		mButton.setImageResource(R.drawable.soundcloud_icon);
	}

	@Override
	protected void onClick() {
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl));
		getContext().startActivity(intent);
	}

	public void load(String url) {
		FPApplication.getInstance().addToRequestQueue(new JsonObjectRequest("http://api.soundcloud.com/resolve.json?url="+ url + "&client_id=" + Keys.soundcloudClientId,
				null,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject jsonObject) {
						parse(jsonObject);
					}
				},
				new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						showErrorScreen();
					}
				}));
		mUrl = url;
	}

	private void parse(JSONObject object) {
		try {
			mTitle.setText(object.getString("title"));
			mAuthor.setText(object.getJSONObject("user").getString("username"));
			String artwork = object.getString("artwork_url");
			if (!artwork.equals("null")) {
				artwork = artwork.replace("large", "t500x500");
				ImageLoaderHelper.getInstance().getBitmap(artwork, new ImageLoaderHelper.ImageCallback() {
					@Override
					public void onResult(boolean success, Bitmap bitmap) {
						if (success && bitmap != null) mBackground.setImageBitmap(bitmap);
					}
				});
			}
		} catch (JSONException e) {
			showErrorScreen();
		}

	}
}


text:
/**
 * Loads a tiered set of scripts asynchronously. Includes the option to load fallback scripts as well.
 * @param scriptsToLoad An array of arrays of scripts to load.
 * @param onLoaded a callback that is called once ALL scripts have finished loading.
 */
function scriptLoader(scriptsToLoad, onLoaded) {
	//Prevents duplicate requests since the onerror event fires twice.
	var requests = {};

	var importScript = function (src, onSuccess, onError) {
		if (!!requests[src]) {
			return;
		}

		var scriptElement   = document.createElement('script');
		scriptElement.src   = src;
		scriptElement.async = false;

		if (onError) {
			scriptElement.onerror = onError;
		}

		if (onSuccess) {
			scriptElement.onload = onSuccess;
		}

		document.head.appendChild(scriptElement);
		requests[src]       = true;

		return scriptElement;
	};

	var importStylesheet = function (src, onSuccess, onError) {
		if (!!requests[src]) {
			return;
		}

		var styleElement   = document.createElement('link');
		styleElement.rel   = 'stylesheet';
		styleElement.href  = src;
		styleElement.type  = 'text/css';

		if (onError) {
			styleElement.onerror = onError;
		}

		if (onSuccess) {
			//IE Doesn't Support onerror, only onload.
			styleElement.onload = function(event) {
				if(styleElement.sheet) {
					onError();
				} else {
					onSuccess();
				}
			};
		}

		document.head.appendChild(styleElement);
		requests[src]       = true;

		return styleElement;
	};

	var importItem = function(src, onSuccess, onError) {
		if(src.match(/(\.css)$/)) {
			importStylesheet(src, onSuccess, onError);
		} else if(src.match(/(\.js)$/)) {
			importScript(src, onSuccess, onError);
		}
	};

	var loadAsync = function (asyncScripts, callback) {
		var scriptsProxy = asyncScripts;
		if (!Array.isArray(scriptsProxy)) {
			scriptsProxy = [scriptsProxy];
		}

		var counter = scriptsProxy.length;
		scriptsProxy.forEach(function (scriptObject) {
			var proxy = scriptObject;

			if (typeof proxy === "string") {
				proxy = {
					primaryUrl: scriptObject
				};
			}

			importItem(proxy.primaryUrl, function (event) {
				counter--;
			}, function () {
				if (!!proxy.secondaryUrl) {
					importItem(proxy.secondaryUrl, function () {
						counter--;
					}, function () {
						counter--;
					});
				} else {
					counter--;
				}
			});
		});

		(function loop() {
			setTimeout(function () {
				if (counter > 0) {
					loop();
				} else {
					callback();
				}
			});
		})();
	};

	var loadSync = function (syncScripts, callback) {
		var previousFunction = callback;
		for (var j = (syncScripts.length - 1); j >= 0; j--) {

			var asyncScripts = syncScripts[j];
			previousFunction = (function (item, prevFunction) {
				return function () {
					loadAsync(item, function () {
						prevFunction();
					});
				};
			})(asyncScripts, previousFunction);
		}

		previousFunction();
	};

	loadSync(scriptsToLoad, onLoaded);
}


text:
package io.cert.manager.models;

import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;

/**
 * The name of the secret containing the TSIG value. If ``tsigKeyName`` is
 * defined, this field is required.
 */
@ApiModel(
    description =
        "The name of the secret containing the TSIG value. If ``tsigKeyName`` is defined, this field is required.")
@javax.annotation.Generated(
    value = "org.openapitools.codegen.languages.JavaClientCodegen",
    date = "2020-08-18T19:55:23.947Z[Etc/UTC]")
public class V1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef {
  public static final String SERIALIZED_NAME_KEY = "key";

  @SerializedName(SERIALIZED_NAME_KEY)
  private String key;

  public static final String SERIALIZED_NAME_NAME = "name";

  @SerializedName(SERIALIZED_NAME_NAME)
  private String name;

  public V1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef key(String key) {

    this.key = key;
    return this;
  }

  /**
   * The key of the entry in the Secret resource's `data` field to be used. Some
   * instances of this field may be defaulted, in others it may be required.
   *
   * @return key
   */
  @javax.annotation.Nullable
  @ApiModelProperty(
      value =
          "The key of the entry in the Secret resource's `data` field to be used. Some instances of this field may be defaulted, in others it may be required.")
  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public V1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef name(String name) {

    this.name = name;
    return this;
  }

  /**
   * Name of the resource being referred to. More info:
   * https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
   *
   * @return name
   */
  @ApiModelProperty(
      required = true,
      value =
          "Name of the resource being referred to. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names")
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    V1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef
        v1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef =
            (V1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef) o;
    return Objects.equals(this.key, v1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef.key)
        && Objects.equals(this.name, v1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef.name);
  }

  @Override
  public int hashCode() {
    return Objects.hash(key, name);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class V1alpha2IssuerSpecAcmeDns01Rfc2136TsigSecretSecretRef {\n");
    sb.append("    key: ").append(toIndentedString(key)).append("\n");
    sb.append("    name: ").append(toIndentedString(name)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/virgin-islands-british/land/" />
</head></html>