text:
@interface PlaceTableViewCell() <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

    @property (weak, nonatomic) IBOutlet UILabel *placeName;
    @property (weak, nonatomic) IBOutlet UICollectionView *avatarsCollection;

    @property (strong) UIImageView* backgroundImageView;

    @property (strong) NSString* placeID;
    @property (strong) NSDictionary* placeInfo;
    @property (strong) CLLocation* placeLocation;
    @property double placeRadius;
    @property (strong) NSArray* avatarsData;//array of UserData*
@end

@implementation PlaceTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(NSString*)getBackgroundImageName {
    int idx = (int)self.tag;
    NSArray* allImages = @[@"place_01.jpg", @"place_02.jpg", @"place_03.jpg", @"place_04.jpg", @"place_05.jpg", @"place_06.jpg", @"place_07.jpg", @"place_08.jpg", @"place_09.jpg"];
    idx = idx%allImages.count;
    return allImages[idx];
}

-(void)prepareBackgroundImageView {
    if (self.backgroundImageView) {
        return;
    }
    UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellTapped:)];
    tapGesture.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tapGesture];

    CGRect f = self.contentView.frame;
    f.size.width = 320;
    self.backgroundImageView = [[UIImageView alloc] initWithFrame:f];

    UIImage* im = [UIImage imageNamed:[self getBackgroundImageName]];

    self.backgroundImageView.image = im;
    [self.contentView addSubview:self.backgroundImageView];

    UIImageView* blackGradient = [[UIImageView alloc] initWithFrame:f];
    im = [UIImage imageNamed:@"blackgradient"];
    blackGradient.image = im;
    [self.contentView addSubview:blackGradient];

    UIImageView* whiteGradient = [[UIImageView alloc] initWithFrame:f];
    im = [UIImage imageNamed:@"whitegradient"];
    whiteGradient.image = im;
    [self.contentView addSubview:whiteGradient];

    [self.contentView sendSubviewToBack:whiteGradient];
    [self.contentView sendSubviewToBack:blackGradient];
    [self.contentView sendSubviewToBack:self.backgroundImageView];

}

-(void)cellTapped:(UITapGestureRecognizer*)tap {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PlacesViewPlaceCellTapped" object:nil userInfo:@{@"placeID" : self.placeID}];
}

-(void)prepareForPlace:(NSString*)placeID {
    self.placeID = placeID;
    NSDictionary* places = [LocalStorage getPlaces];
    self.placeInfo = places[placeID];
    self.placeName.text = self.placeInfo[@"name"];
    self.placeRadius = [self.placeInfo[@"rad"] doubleValue];

    self.avatarsCollection.dataSource = self;
    self.avatarsCollection.delegate = self;

    [self recalculateWhoIsInPlace];
    [self prepareBackgroundImageView];

    [self.avatarsCollection reloadData];
}

-(CLLocation*)getPlaceLocation {
    NSString* sLat = self.placeInfo[@"lat"];
    NSString* sLon = self.placeInfo[@"lon"];
    double lat = [sLat doubleValue];
    double lon = [sLon doubleValue];
    CLLocation* loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
    return loc;
}

-(void)recalculateWhoIsInPlace {
    self.avatarsData = @[];
    self.placeLocation = [self getPlaceLocation];
    Users* u = [[Users alloc] init];
    NSArray* users = [u getUsersIncludingMyself:YES excludingOnesIDontWantToSee:YES];

    for(UserData* user in users) {
        if ([self isUserInPlace:user]) {
            self.avatarsData = [self.avatarsData arrayByAddingObject:user];
        }
    }

//    self.avatarsData = @[@"defaultAvatar", @"defaultAvatar", @"defaultAvatar"];

}

-(BOOL)isUserInPlace:(UserData*)user {
    CLLocation* loc = [[CLLocation alloc] initWithLatitude:user.coord.latitude longitude:user.coord.longitude];
    if ([self.placeLocation distanceFromLocation:loc] <= self.placeRadius) {
        return YES;
    }
    return NO;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = self.avatarsData.count;
    return count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //int row = indexPath.row;
    AvatarInPlacesCollectionViewCell *cell = (AvatarInPlacesCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"AvatarCell" forIndexPath:indexPath];

    [cell prepareForUserID:self.avatarsData[indexPath.row]];

    return cell;

}

-(float)currentAvatarSize {
    CGRect f = self.avatarsCollection.frame;
    float d = 5;//distance between items
    float w = f.size.width;//full container width
    float n = self.avatarsData.count;//amount of items
    if (n == 0) {
        return AVATAR_WIDTH;
    }
    float x = (w - d*n + d)/n - 1;
    if (x > AVATAR_WIDTH + AVATAR_BORDER_WIDTH*2) {
        return AVATAR_WIDTH + AVATAR_BORDER_WIDTH*2;
    }
    return x;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    float avatarSize = [self currentAvatarSize];
    return CGSizeMake(avatarSize, avatarSize);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    float avatarSize = [self currentAvatarSize];
    CGRect f = collectionView.frame;
    CGFloat leftInset = (f.size.width - (avatarSize + 10)*self.avatarsData.count)/2;//5 is for distance between objects
    CGFloat topInset = (f.size.height/2 - avatarSize/2);
    if (leftInset < 1) {
        leftInset = 1;
    }
    if (topInset < 1) {
        topInset = 1;
    }

    //leftInset = 0;
    //topInset = 0;
    return UIEdgeInsetsMake(topInset, leftInset, 0, 0);
}

@end


text:
namespace cucumber
{
    partial class FormGymnastic
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormGymnastic));
            this.label1 = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.sec = new System.Windows.Forms.Label();
            this.doubledot = new System.Windows.Forms.Label();
            this.min = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Showcard Gothic", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(78, 39);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(444, 40);
            this.label1.TabIndex = 0;
            this.label1.Text = "It\'s time to do gymnastic";
            //
            // pictureBox1
            //
            this.pictureBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.BackgroundImage")));
            this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.pictureBox1.Location = new System.Drawing.Point(81, 92);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(437, 311);
            this.pictureBox1.TabIndex = 1;
            this.pictureBox1.TabStop = false;
            //
            // timer1
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // sec
            //
            this.sec.AutoSize = true;
            this.sec.Font = new System.Drawing.Font("Showcard Gothic", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.sec.Location = new System.Drawing.Point(290, 408);
            this.sec.Name = "sec";
            this.sec.Size = new System.Drawing.Size(44, 33);
            this.sec.TabIndex = 9;
            this.sec.Text = "59";
            //
            // doubledot
            //
            this.doubledot.AutoSize = true;
            this.doubledot.Font = new System.Drawing.Font("Showcard Gothic", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.doubledot.Location = new System.Drawing.Point(275, 407);
            this.doubledot.Name = "doubledot";
            this.doubledot.Size = new System.Drawing.Size(24, 33);
            this.doubledot.TabIndex = 8;
            this.doubledot.Text = ":";
            //
            // min
            //
            this.min.AutoSize = true;
            this.min.Font = new System.Drawing.Font("Showcard Gothic", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.min.Location = new System.Drawing.Point(250, 408);
            this.min.Name = "min";
            this.min.Size = new System.Drawing.Size(30, 33);
            this.min.TabIndex = 7;
            this.min.Text = "4";
            //
            // FormGymnastic
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.SpringGreen;
            this.ClientSize = new System.Drawing.Size(600, 450);
            this.Controls.Add(this.sec);
            this.Controls.Add(this.doubledot);
            this.Controls.Add(this.min);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "FormGymnastic";
            this.Text = "FormGymnastic";
            this.TopMost = true;
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.FormGymnastic_Paint);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Label sec;
        private System.Windows.Forms.Label doubledot;
        private System.Windows.Forms.Label min;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _PASSENGER_SPAWNING_KIT_SMART_SPAWNER_H_
#define _PASSENGER_SPAWNING_KIT_SMART_SPAWNER_H_

#include <oxt/thread.hpp>
#include <oxt/system_calls.hpp>
#include <boost/bind/bind.hpp>
#include <boost/make_shared.hpp>
#include <string>
#include <vector>
#include <map>
#include <stdexcept>
#include <dirent.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h>
#include <cstring>
#include <cassert>

#include <adhoc_lve.h>

#include <LoggingKit/Logging.h>
#include <Constants.h>
#include <Exceptions.h>
#include <DataStructures/StringKeyTable.h>
#include <ProcessManagement/Utils.h>
#include <SystemTools/ProcessMetricsCollector.h>
#include <SystemTools/SystemTime.h>
#include <FileTools/FileManip.h>
#include <IOTools/BufferedIO.h>
#include <JsonTools/JsonUtils.h>
#include <Utils/ScopeGuard.h>
#include <Utils/AsyncSignalSafeUtils.h>
#include <LveLoggingDecorator.h>
#include <Core/SpawningKit/Spawner.h>
#include <Core/SpawningKit/Exceptions.h>
#include <Core/SpawningKit/PipeWatcher.h>
#include <Core/SpawningKit/Handshake/Session.h>
#include <Core/SpawningKit/Handshake/Prepare.h>
#include <Core/SpawningKit/Handshake/Perform.h>
#include <Core/SpawningKit/Handshake/BackgroundIOCapturer.h>

namespace Passenger {
namespace SpawningKit {

using namespace std;
using namespace boost;
using namespace oxt;

class SmartSpawner: public Spawner {
private:
	const string preloaderCommandString;
	string preloaderEnvvars;
	string preloaderUserInfo;
	string preloaderUlimits;
	StringKeyTable<string> preloaderAnnotations;
	AppPoolOptions options;

	// Protects m_lastUsed and pid.
	mutable boost::mutex simpleFieldSyncher;
	// Protects everything else.
	mutable boost::mutex syncher;

	// Preloader information.
	pid_t pid;
	FileDescriptor preloaderStdin;
	string socketAddress;
	unsigned long long m_lastUsed;

	/**
	 * Behaves like <tt>waitpid(pid, status, WNOHANG)</tt>, but waits at most
	 * timeout miliseconds for the process to exit.
	 */
	static int timedWaitpid(pid_t pid, int *status, unsigned long long timeout) {
		Timer<SystemTime::GRAN_10MSEC> timer;
		int ret;

		do {
			ret = syscalls::waitpid(pid, status, WNOHANG);
			if (ret > 0 || ret == -1) {
				return ret;
			} else {
				syscalls::usleep(10000);
			}
		} while (timer.elapsed() < timeout);
		return 0; // timed out
	}

	static bool osProcessExists(pid_t pid) {
		if (syscalls::kill(pid, 0) == 0) {
			/* On some environments, e.g. Heroku, the init process does
			 * not properly reap adopted zombie processes, which can interfere
			 * with our process existance check. To work around this, we
			 * explicitly check whether or not the process has become a zombie.
			 */
			return !isZombie(pid);
		} else {
			return errno != ESRCH;
		}
	}

	static bool isZombie(pid_t pid) {
		string filename = "/proc/" + toString(pid) + "/status";
		FILE *f = fopen(filename.c_str(), "r");
		if (f == NULL) {
			// Don't know.
			return false;
		}

		bool result = false;
		while (!feof(f)) {
			char buf[512];
			const char *line;

			line = fgets(buf, sizeof(buf), f);
			if (line == NULL) {
				break;
			}
			if (strcmp(line, "State:	Z (zombie)\n") == 0) {
				// Is a zombie.
				result = true;
				break;
			}
		}
		fclose(f);
		return result;
	}

	static string createCommandString(const vector<string> &command) {
		string result;
		vector<string>::const_iterator it;
		vector<string>::const_iterator begin = command.begin();
		vector<string>::const_iterator end = command.end();

		for (it = begin; it != end; it++) {
			if (it != begin) {
				result.append(1, ' ');
			}
			result.append(escapeShell(*it));
		}

		return result;
	}

	void setConfigFromAppPoolOptions(Config *config, Json::Value &extraArgs,
		const AppPoolOptions &options)
	{
		Spawner::setConfigFromAppPoolOptions(config, extraArgs, options);
		config->spawnMethod = P_STATIC_STRING("smart");
	}

	struct StdChannelsAsyncOpenState {
		const int workDirFd;

		oxt::thread *stdinOpenThread;
		FileDescriptor stdinFd;
		int stdinOpenErrno;

		oxt::thread *stdoutAndErrOpenThread;
		FileDescriptor stdoutAndErrFd;
		int stdoutAndErrOpenErrno;

		BackgroundIOCapturerPtr stdoutAndErrCapturer;

		StdChannelsAsyncOpenState(int _workDirFd)
			: workDirFd(_workDirFd),
			  stdinOpenThread(NULL),
			  stdoutAndErrOpenThread(NULL)
			{ }

		~StdChannelsAsyncOpenState() {
			boost::this_thread::disable_interruption di;
			boost::this_thread::disable_syscall_interruption dsi;
			if (stdinOpenThread != NULL) {
				stdinOpenThread->interrupt_and_join();
				delete stdinOpenThread;
			}
			if (stdoutAndErrOpenThread != NULL) {
				stdoutAndErrOpenThread->interrupt_and_join();
				delete stdoutAndErrOpenThread;
			}
		}
	};

	typedef boost::shared_ptr<StdChannelsAsyncOpenState> StdChannelsAsyncOpenStatePtr;

	StdChannelsAsyncOpenStatePtr openStdChannelsFifosAsynchronously(
		HandshakeSession &session)
	{
		StdChannelsAsyncOpenStatePtr state = boost::make_shared<StdChannelsAsyncOpenState>(
			session.workDirFd);
		state->stdinOpenThread = new oxt::thread(boost::bind(
			openStdinChannel, state, session.workDir->getPath()),
			"FIFO opener: " + session.workDir->getPath() + "/stdin", 1024 * 128);
		state->stdoutAndErrOpenThread = new oxt::thread(boost::bind(
			openStdoutAndErrChannel, state, session.workDir->getPath()),
			"FIFO opener: " + session.workDir->getPath() + "/stdout_and_err", 1024 * 128);
		return state;
	}

	void waitForStdChannelFifosToBeOpenedByPeer(const StdChannelsAsyncOpenStatePtr &state,
		HandshakeSession &session, pid_t pid)
	{
		TRACE_POINT();
		MonotonicTimeUsec startTime = SystemTime::getMonotonicUsec();
		ScopeGuard guard(boost::bind(adjustTimeout, startTime, &session.timeoutUsec));

		try {
			if (state->stdinOpenThread->try_join_for(
				boost::chrono::microseconds(session.timeoutUsec)))
			{
				delete state->stdinOpenThread;
				state->stdinOpenThread = NULL;
				if (state->stdinFd == -1) {
					throw SystemException("Error opening FIFO "
						+ session.workDir->getPath() + "/stdin",
						state->stdinOpenErrno);
				} else {
					P_LOG_FILE_DESCRIPTOR_PURPOSE(state->stdinFd,
						"App " << pid << " (" << options.appRoot
						<< ") stdin");
					adjustTimeout(startTime, &session.timeoutUsec);
					startTime = SystemTime::getMonotonicUsec();
				}
			} else {
				throw TimeoutException("Timeout opening FIFO "
					+ session.workDir->getPath() + "/stdin");
			}

			UPDATE_TRACE_POINT();
			if (state->stdoutAndErrOpenThread->try_join_for(
				boost::chrono::microseconds(session.timeoutUsec)))
			{
				delete state->stdoutAndErrOpenThread;
				state->stdoutAndErrOpenThread = NULL;
				if (state->stdoutAndErrFd == -1) {
					throw SystemException("Error opening FIFO "
						+ session.workDir->getPath() + "/stdout_and_err",
						state->stdoutAndErrOpenErrno);
				} else {
					P_LOG_FILE_DESCRIPTOR_PURPOSE(state->stdoutAndErrFd,
						"App " << pid << " (" << options.appRoot
						<< ") stdoutAndErr");
				}
			} else {
				throw TimeoutException("Timeout opening FIFO "
					+ session.workDir->getPath() + "/stdout_and_err");
			}

			state->stdoutAndErrCapturer = boost::make_shared<BackgroundIOCapturer>(
				state->stdoutAndErrFd, pid, session.config->appGroupName,
				session.config->logFile);
			state->stdoutAndErrCapturer->start();
		} catch (const boost::system::system_error &e) {
			throw SystemException(e.what(), e.code().value());
		}
	}

	static void openStdinChannel(StdChannelsAsyncOpenStatePtr state,
		const string &workDir)
	{
		int fd = syscalls::openat(state->workDirFd, "stdin", O_WRONLY | O_APPEND | O_NOFOLLOW);
		int e = errno;
		state->stdinFd.assign(fd, __FILE__, __LINE__);
		state->stdinOpenErrno = e;
	}

	static void openStdoutAndErrChannel(StdChannelsAsyncOpenStatePtr state,
		const string &workDir)
	{
		int fd = syscalls::openat(state->workDirFd, "stdout_and_err", O_RDONLY | O_NOFOLLOW);
		int e = errno;
		state->stdoutAndErrFd.assign(fd, __FILE__, __LINE__);
		state->stdoutAndErrOpenErrno = e;
	}

	bool preloaderStarted() const {
		return pid != -1;
	}

	void startPreloader() {
		TRACE_POINT();
		boost::this_thread::disable_interruption di;
		boost::this_thread::disable_syscall_interruption dsi;
		assert(!preloaderStarted());
		P_DEBUG("Spawning new preloader: appRoot=" << options.appRoot);

		Config config;
		Json::Value extraArgs;
		try {
			setConfigFromAppPoolOptions(&config, extraArgs, options);
			config.startCommand = preloaderCommandString;
		} catch (const std::exception &originalException) {
			Journey journey(SPAWN_THROUGH_PRELOADER, true);
			journey.setStepErrored(SPAWNING_KIT_PREPARATION, true);
			throw SpawnException(originalException, journey,
				&config).finalize();
		}

		HandshakeSession session(*context, config, START_PRELOADER);
		session.journey.setStepInProgress(SPAWNING_KIT_PREPARATION);

		try {
			internalStartPreloader(config, session, extraArgs);
		} catch (const SpawnException &) {
			throw;
		} catch (const std::exception &originalException) {
			session.journey.setStepErrored(SPAWNING_KIT_PREPARATION);
			throw SpawnException(originalException, session.journey,
				&config).finalize();
		}
	}

	void internalStartPreloader(Config &config, HandshakeSession &session,
		const Json::Value &extraArgs)
	{
		TRACE_POINT();
		HandshakePrepare(session, extraArgs).execute();
		Pipe stdinChannel = createPipe(__FILE__, __LINE__);
		Pipe stdoutAndErrChannel = createPipe(__FILE__, __LINE__);
		adhoc_lve::LveEnter scopedLveEnter(LveLoggingDecorator::lveInitOnce(),
			session.uid,
			config.lveMinUid,
			LveLoggingDecorator::lveExitCallback);
		LveLoggingDecorator::logLveEnter(scopedLveEnter,
			session.uid,
			config.lveMinUid);
		string agentFilename = context->resourceLocator
			->findSupportBinary(AGENT_EXE);

		session.journey.setStepPerformed(SPAWNING_KIT_PREPARATION);
		session.journey.setStepInProgress(SPAWNING_KIT_FORK_SUBPROCESS);
		session.journey.setStepInProgress(SUBPROCESS_BEFORE_FIRST_EXEC);

		pid_t pid = syscalls::fork();
		if (pid == 0) {
			int e;
			char buf[1024];
			const char *end = buf + sizeof(buf);
			namespace ASSU = AsyncSignalSafeUtils;

			resetSignalHandlersAndMask();
			disableMallocDebugging();
			int stdinCopy = dup2(stdinChannel.first, 3);
			int stdoutAndErrCopy = dup2(stdoutAndErrChannel.second, 4);
			dup2(stdinCopy, 0);
			dup2(stdoutAndErrCopy, 1);
			dup2(stdoutAndErrCopy, 2);
			closeAllFileDescriptors(2);

			execlp(agentFilename.c_str(),
				agentFilename.c_str(),
				"spawn-env-setupper",
				session.workDir->getPath().c_str(),
				"--before",
				(char *) 0);

			char *pos = buf;
			e = errno;
			pos = ASSU::appendData(pos, end, "Cannot execute \"");
			pos = ASSU::appendData(pos, end, agentFilename.data(), agentFilename.size());
			pos = ASSU::appendData(pos, end, "\": ");
			pos = ASSU::appendData(pos, end, ASSU::limitedStrerror(e));
			pos = ASSU::appendData(pos, end, " (errno=");
			pos = ASSU::appendInteger<int, 10>(pos, end, e);
			pos = ASSU::appendData(pos, end, ")\n");
			ASSU::printError(buf, pos - buf);
			_exit(1);

		} else if (pid == -1) {
			int e = errno;
			UPDATE_TRACE_POINT();
			session.journey.setStepErrored(SPAWNING_KIT_FORK_SUBPROCESS);
			SpawnException ex(OPERATING_SYSTEM_ERROR, session.journey, &config);
			ex.setSummary(StaticString("Cannot fork a new process: ") + strerror(e)
				+ " (errno=" + toString(e) + ")");
			ex.setAdvancedProblemDetails(StaticString("Cannot fork a new process: ")
				+ strerror(e) + " (errno=" + toString(e) + ")");
			throw ex.finalize();

		} else {
			UPDATE_TRACE_POINT();
			session.journey.setStepPerformed(SPAWNING_KIT_FORK_SUBPROCESS);
			session.journey.setStepInProgress(SPAWNING_KIT_HANDSHAKE_PERFORM);

			scopedLveEnter.exit();

			P_LOG_FILE_DESCRIPTOR_PURPOSE(stdinChannel.second,
				"Preloader " << pid << " (" << options.appRoot << ") stdin");
			P_LOG_FILE_DESCRIPTOR_PURPOSE(stdoutAndErrChannel.first,
				"Preloader " << pid << " (" << options.appRoot << ") stdoutAndErr");

			UPDATE_TRACE_POINT();
			ScopeGuard guard(boost::bind(nonInterruptableKillAndWaitpid, pid));
			P_DEBUG("Preloader process forked for appRoot=" << options.appRoot
				<< ": PID " << pid);
			stdinChannel.first.close();
			stdoutAndErrChannel.second.close();

			HandshakePerform(session, pid, stdinChannel.second,
				stdoutAndErrChannel.first).execute();
			string envvars, userInfo, ulimits;
			// If a new output variable was added to this function,
			// then don't forget to also update these locations:
			// - the critical section below
			// - bottom of stopPreloader()
			// - addPreloaderEnvDumps()
			HandshakePerform::loadBasicInfoFromEnvDumpDir(session.envDumpDir,
				session.envDumpDirFd, envvars, userInfo, ulimits);
			string socketAddress = findPreloaderCommandSocketAddress(session);

			{
				boost::lock_guard<boost::mutex> l(simpleFieldSyncher);
				this->pid = pid;
				this->socketAddress = socketAddress;
				this->preloaderStdin = stdinChannel.second;
				this->preloaderEnvvars = envvars;
				this->preloaderUserInfo = userInfo;
				this->preloaderUlimits = ulimits;
				this->preloaderAnnotations = loadAnnotationsFromEnvDumpDir(
					session.envDumpDir, session.envDumpAnnotationsDirFd);
			}

			PipeWatcherPtr watcher = boost::make_shared<PipeWatcher>(
				stdoutAndErrChannel.first, "output", config.appGroupName,
				config.logFile, pid);
			watcher->initialize();
			watcher->start();

			UPDATE_TRACE_POINT();
			guard.clear();
			session.journey.setStepPerformed(SPAWNING_KIT_HANDSHAKE_PERFORM);
			P_INFO("Preloader for " << options.appRoot <<
				" started on PID " << pid <<
				", listening on " << socketAddress);
		}
	}

	void stopPreloader() {
		TRACE_POINT();
		boost::this_thread::disable_interruption di;
		boost::this_thread::disable_syscall_interruption dsi;

		if (!preloaderStarted()) {
			return;
		}

		preloaderStdin.close(false);

		if (timedWaitpid(pid, NULL, 5000) == 0) {
			P_DEBUG("Preloader did not exit in time, killing it...");
			syscalls::kill(pid, SIGKILL);
			syscalls::waitpid(pid, NULL, 0);
		}

		// Delete socket after the process has exited so that it
		// doesn't crash upon deleting a nonexistant file.
		if (getSocketAddressType(socketAddress) == SAT_UNIX) {
			string filename = parseUnixSocketAddress(socketAddress);
			syscalls::unlink(filename.c_str());
		}

		{
			boost::lock_guard<boost::mutex> l(simpleFieldSyncher);
			pid = -1;
			socketAddress.clear();
			preloaderEnvvars.clear();
			preloaderUserInfo.clear();
			preloaderUlimits.clear();
			preloaderAnnotations.clear();
		}
	}

	FileDescriptor connectToPreloader(HandshakeSession &session) {
		TRACE_POINT();
		FileDescriptor fd(connectToServer(socketAddress, __FILE__, __LINE__), NULL, 0);
		P_LOG_FILE_DESCRIPTOR_PURPOSE(fd, "Preloader " << pid
			<< " (" << session.config->appRoot << ") connection");
		return fd;
	}

	struct ForkResult {
		pid_t pid;
		FileDescriptor stdinFd;
		FileDescriptor stdoutAndErrFd;
		string alreadyReadStdoutAndErrData;

		ForkResult()
			: pid(-1)
			{ }

		ForkResult(pid_t _pid, const FileDescriptor &_stdinFd,
			const FileDescriptor &_stdoutAndErrFd,
			const string &_alreadyReadStdoutAndErrData)
			: pid(_pid),
			  stdinFd(_stdinFd),
			  stdoutAndErrFd(_stdoutAndErrFd),
			  alreadyReadStdoutAndErrData(_alreadyReadStdoutAndErrData)
			{ }
	};

	struct PreloaderCrashed {
		SystemException *systemException;
		IOException *ioException;

		PreloaderCrashed(const SystemException &e)
			: systemException(new SystemException(e)),
			  ioException(NULL)
			{ }

		PreloaderCrashed(const IOException &e)
			: systemException(NULL),
			  ioException(new IOException(e))
			{ }

		~PreloaderCrashed() {
			delete systemException;
			delete ioException;
		}

		const oxt::tracable_exception &getException() const {
			if (systemException != NULL) {
				return *systemException;
			} else {
				return *ioException;
			}
		}
	};

	ForkResult invokeForkCommand(HandshakeSession &session, JourneyStep &stepToMarkAsErrored) {
		TRACE_POINT();

		P_ASSERT_EQ(session.journey.getStepInfo(SPAWNING_KIT_PREPARATION).state,
			STEP_PERFORMED);

		try {
			StdChannelsAsyncOpenStatePtr stdChannelsAsyncOpenState =
				openStdChannelsFifosAsynchronously(session);
			return internalInvokeForkCommand(session, stdChannelsAsyncOpenState,
				stepToMarkAsErrored);
		} catch (const PreloaderCrashed &crashException1) {
			UPDATE_TRACE_POINT();
			P_WARN("An error occurred while spawning an application process: "
				<< crashException1.getException().what());
			P_WARN("The application preloader seems to have crashed,"
				" restarting it and trying again...");

			session.journey.reset();

			try {
				stopPreloader();
			} catch (const SpawnException &) {
				throw;
			} catch (const std::exception &originalException) {
				session.journey.setStepErrored(SPAWNING_KIT_PREPARATION, true);

				SpawnException e(originalException, session.journey, session.config);
				e.setSummary(StaticString("Error stopping a crashed preloader: ")
					+ originalException.what());
				e.setProblemDescriptionHTML(
					"
The " PROGRAM_NAME " application server tried"
					" to start the web application by communicating with a"
					" helper process that we call a \"preloader\". However,"
					" this helper process crashed unexpectedly. "
					SHORT_PROGRAM_NAME " then tried to restart it, but"
					" encountered the following error while trying to"
					" stop the preloader:
"
					"
" + escapeHTML(originalException.what()) + "
");
				throw e.finalize();
			}

			UPDATE_TRACE_POINT();
			startPreloader();
			session.journey.reset();
			session.journey.setStepPerformed(SPAWNING_KIT_PREPARATION, true);

			UPDATE_TRACE_POINT();
			try {
				StdChannelsAsyncOpenStatePtr stdChannelsAsyncOpenState =
					openStdChannelsFifosAsynchronously(session);
				return internalInvokeForkCommand(session, stdChannelsAsyncOpenState,
					stepToMarkAsErrored);
			} catch (const PreloaderCrashed &crashException2) {
				UPDATE_TRACE_POINT();

				session.journey.reset();
				session.journey.setStepErrored(SPAWNING_KIT_PREPARATION, true);

				try {
					stopPreloader();
				} catch (const SpawnException &) {
					throw;
				} catch (const std::exception &originalException) {
					SpawnException e(originalException, session.journey, session.config);
					e.setSummary(StaticString("Error stopping a crashed preloader: ")
						+ originalException.what());
					e.setProblemDescriptionHTML(
						"
The " PROGRAM_NAME " application server tried"
						" to start the web application by communicating with a"
						" helper process that we call a \"preloader\". However,"
						" this helper process crashed unexpectedly. "
						SHORT_PROGRAM_NAME " then tried to restart it, but"
						" encountered the following error while trying to"
						" stop the preloader:
"
						"
" + escapeHTML(originalException.what()) + "
");
					throw e.finalize();
				}

				SpawnException e(crashException2.getException(),
					session.journey, session.config);
				e.setSummary(StaticString("An application preloader crashed: ") +
					crashException2.getException().what());
				e.setProblemDescriptionHTML(
					"
The " PROGRAM_NAME " application server tried"
					" to start the web application by communicating with a"
					" helper process that we call a \"preloader\". However,"
					" this helper process crashed unexpectedly:
"
					"
" + escapeHTML(crashException2.getException().what())
					+ "
");
				throw e.finalize();
			}
		}
	}

	ForkResult internalInvokeForkCommand(HandshakeSession &session,
		const StdChannelsAsyncOpenStatePtr &stdChannelsAsyncOpenState,
		JourneyStep &stepToMarkAsErrored)
	{
		TRACE_POINT();

		P_ASSERT_EQ(session.journey.getStepInfo(SPAWNING_KIT_PREPARATION).state,
			STEP_PERFORMED);

		session.journey.setStepInProgress(SPAWNING_KIT_CONNECT_TO_PRELOADER);
		stepToMarkAsErrored = SPAWNING_KIT_CONNECT_TO_PRELOADER;
		FileDescriptor fd;
		string line;
		Json::Value doc;
		try {
			fd = connectToPreloader(session);
		} catch (const SystemException &e) {
			throw PreloaderCrashed(e);
		} catch (const IOException &e) {
			throw PreloaderCrashed(e);
		}

		session.journey.setStepPerformed(SPAWNING_KIT_CONNECT_TO_PRELOADER);
		session.journey.setStepInProgress(SPAWNING_KIT_SEND_COMMAND_TO_PRELOADER);
		stepToMarkAsErrored = SPAWNING_KIT_SEND_COMMAND_TO_PRELOADER;
		try {
			sendForkCommand(session, fd);
		} catch (const SystemException &e) {
			throw PreloaderCrashed(e);
		} catch (const IOException &e) {
			throw PreloaderCrashed(e);
		}

		session.journey.setStepPerformed(SPAWNING_KIT_SEND_COMMAND_TO_PRELOADER);
		session.journey.setStepInProgress(SPAWNING_KIT_READ_RESPONSE_FROM_PRELOADER);
		stepToMarkAsErrored = SPAWNING_KIT_READ_RESPONSE_FROM_PRELOADER;
		try {
			line = readForkCommandResponse(session, fd);
		} catch (const SystemException &e) {
			throw PreloaderCrashed(e);
		} catch (const IOException &e) {
			throw PreloaderCrashed(e);
		}

		session.journey.setStepPerformed(SPAWNING_KIT_READ_RESPONSE_FROM_PRELOADER);
		session.journey.setStepInProgress(SPAWNING_KIT_PARSE_RESPONSE_FROM_PRELOADER);
		stepToMarkAsErrored = SPAWNING_KIT_PARSE_RESPONSE_FROM_PRELOADER;
		doc = parseForkCommandResponse(session, line);

		session.journey.setStepPerformed(SPAWNING_KIT_PARSE_RESPONSE_FROM_PRELOADER);
		session.journey.setStepInProgress(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);
		stepToMarkAsErrored = SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER;
		return handleForkCommandResponse(session, stdChannelsAsyncOpenState, doc);
	}

	void sendForkCommand(HandshakeSession &session, const FileDescriptor &fd) {
		TRACE_POINT();
		Json::Value doc;

		doc["command"] = "spawn";
		doc["work_dir"] = session.workDir->getPath();

		writeExact(fd, Json::FastWriter().write(doc), &session.timeoutUsec);
	}

	string readForkCommandResponse(HandshakeSession &session, const FileDescriptor &fd) {
		TRACE_POINT();
		BufferedIO io(fd);

		try {
			return io.readLine(10240, &session.timeoutUsec);
		} catch (const SecurityException &) {
			session.journey.setStepErrored(SPAWNING_KIT_READ_RESPONSE_FROM_PRELOADER);

			SpawnException e(INTERNAL_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("The preloader process sent a response that exceeds the maximum size limit.");
			e.setProblemDescriptionHTML(
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application by communicating with a"
				" helper process that we call a \"preloader\". However,"
				" this helper process sent a response that exceeded the"
				" internally-defined maximum size limit.
");
			e.setSolutionDescriptionHTML(
				"
"
				"This is probably a bug in the preloader process. Please "
				""
				"report this bug."
				"
");
			throw e.finalize();
		}
	}

	Json::Value parseForkCommandResponse(HandshakeSession &session, const string &data) {
		TRACE_POINT();
		Json::Value doc;
		Json::Reader reader;

		if (!reader.parse(data, doc)) {
			session.journey.setStepErrored(SPAWNING_KIT_PARSE_RESPONSE_FROM_PRELOADER);

			SpawnException e(INTERNAL_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("The preloader process sent an unparseable response: " + data);
			e.setProblemDescriptionHTML(
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application by communicating with a"
				" helper process that we call a \"preloader\". However,"
				" this helper process sent a response that looks like"
				" gibberish.
"
				"
The response is as follows:
"
				"
" + escapeHTML(data) + "
");
			e.setSolutionDescriptionHTML(
				"
"
				"This is probably a bug in the preloader process. Please "
				""
				"report this bug."
				"
");
			throw e.finalize();
		}

		UPDATE_TRACE_POINT();
		if (!validateForkCommandResponse(doc)) {
			session.journey.setStepErrored(SPAWNING_KIT_PARSE_RESPONSE_FROM_PRELOADER);

			SpawnException e(INTERNAL_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("The preloader process sent a response that does not"
				" match the expected structure: " + stringifyJson(doc));
			e.setProblemDescriptionHTML(
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application by communicating with a"
				" helper process that we call a \"preloader\". However,"
				" this helper process sent a response that does not match"
				" the structure that " SHORT_PROGRAM_NAME " expects.
"
				"
The response is as follows:
"
				"
" + escapeHTML(doc.toStyledString()) + "
");
			e.setSolutionDescriptionHTML(
				"
"
				"This is probably a bug in the preloader process. Please "
				""
				"report this bug."
				"
");
			throw e.finalize();
		}

		return doc;
	}

	bool validateForkCommandResponse(const Json::Value &doc) const {
		if (!doc.isObject()) {
			return false;
		}
		if (!doc.isMember("result") || !doc["result"].isString()) {
			return false;
		}
		if (doc["result"].asString() == "ok") {
			if (!doc.isMember("pid") || !doc["pid"].isInt()) {
				return false;
			}
			return true;
		} else if (doc["result"].asString() == "error") {
			if (!doc.isMember("message") || !doc["message"].isString()) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	ForkResult handleForkCommandResponse(HandshakeSession &session,
		const StdChannelsAsyncOpenStatePtr &stdChannelsAsyncOpenState,
		const Json::Value &doc)
	{
		TRACE_POINT();
		if (doc["result"].asString() == "ok") {
			return handleForkCommandResponseSuccess(session, stdChannelsAsyncOpenState,
				doc);
		} else {
			P_ASSERT_EQ(doc["result"].asString(), "error");
			return handleForkCommandResponseError(session, doc);
		}
	}

	ForkResult handleForkCommandResponseSuccess(HandshakeSession &session,
		const StdChannelsAsyncOpenStatePtr &stdChannelsAsyncOpenState, const Json::Value &doc)
	{
		TRACE_POINT();
		pid_t spawnedPid = doc["pid"].asInt();

		// How do we know the preloader actually forked a process
		// instead of reporting the PID of a random other existing process?
		// For security reasons we perform a bunch of sanity checks,
		// including checking the PID's UID.

		if (spawnedPid < 1) {
			UPDATE_TRACE_POINT();
			session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

			SpawnException e(INTERNAL_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("The the preloader said it spawned a process with PID "
				+ toString(spawnedPid) + ", which is not allowed.");
			e.setSubprocessPid(spawnedPid);
			e.setStdoutAndErrData(getBackgroundIOCapturerData(
				stdChannelsAsyncOpenState->stdoutAndErrCapturer));
			e.setProblemDescriptionHTML(
				"
Application process has unexpected PID
"
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application by communicating with a"
				" helper process that we call a \"preloader\". However,"
				" the preloader reported that it started a process with"
				" a PID of " + toString(spawnedPid) + ", which is not"
				" allowed.
");
			if (!session.config->genericApp && session.config->startsUsingWrapper
				&& session.config->wrapperSuppliedByThirdParty)
			{
				e.setSolutionDescriptionHTML(
					"
Please report this bug
"
					"
"
					"This is probably a bug in the preloader process. The preloader "
					"wrapper program is not written by the " PROGRAM_NAME " authors, "
					"but by a third party. Please report this bug to the author of "
					"the preloader wrapper program."
					"
");
			} else {
				e.setSolutionDescriptionHTML(
					"
Please report this bug
"
					"
"
					"This is probably a bug in the preloader process. The preloader "
					"is an internal tool part of " PROGRAM_NAME ". Please "
					""
					"report this bug."
					"
");
			}
			throw e.finalize();
		}

		UPDATE_TRACE_POINT();
		uid_t spawnedUid = getProcessUid(session, spawnedPid,
			stdChannelsAsyncOpenState->stdoutAndErrCapturer);
		if (spawnedUid != session.uid) {
			UPDATE_TRACE_POINT();
			session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

			SpawnException e(INTERNAL_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("The process that the preloader said it spawned, PID "
				+ toString(spawnedPid) + ", has UID " + toString(spawnedUid)
				+ ", but the expected UID is " + toString(session.uid));
			e.setSubprocessPid(spawnedPid);
			e.setStdoutAndErrData(getBackgroundIOCapturerData(
				stdChannelsAsyncOpenState->stdoutAndErrCapturer));
			e.setProblemDescriptionHTML(
				"
Application process has unexpected UID
"
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application by communicating with a"
				" helper process that we call a \"preloader\". However,"
				" the web application process that the preloader started"
				" belongs to the wrong user. The UID of the web"
				" application process should be " + toString(session.uid)
				+ ", but is actually " + toString(session.uid) + ".
");
			if (!session.config->genericApp && session.config->startsUsingWrapper
				&& session.config->wrapperSuppliedByThirdParty)
			{
				e.setSolutionDescriptionHTML(
					"
Please report this bug
"
					"
"
					"This is probably a bug in the preloader process. The preloader "
					"wrapper program is not written by the " PROGRAM_NAME " authors, "
					"but by a third party. Please report this bug to the author of "
					"the preloader wrapper program."
					"
");
			} else {
				e.setSolutionDescriptionHTML(
					"
Please report this bug
"
					"
"
					"This is probably a bug in the preloader process. The preloader "
					"is an internal tool part of " PROGRAM_NAME ". Please "
					""
					"report this bug."
					"
");
			}
			throw e.finalize();
		}

		UPDATE_TRACE_POINT();
		ScopeGuard guard(boost::bind(nonInterruptableKillAndWaitpid, spawnedPid));
		waitForStdChannelFifosToBeOpenedByPeer(stdChannelsAsyncOpenState,
			session, spawnedPid);

		UPDATE_TRACE_POINT();
		string alreadyReadStdoutAndErrData;
		if (stdChannelsAsyncOpenState->stdoutAndErrCapturer != NULL) {
			stdChannelsAsyncOpenState->stdoutAndErrCapturer->stop();
			alreadyReadStdoutAndErrData = stdChannelsAsyncOpenState->stdoutAndErrCapturer->getData();
		}
		guard.clear();
		return ForkResult(spawnedPid, stdChannelsAsyncOpenState->stdinFd,
			stdChannelsAsyncOpenState->stdoutAndErrFd,
			alreadyReadStdoutAndErrData);
	}

	ForkResult handleForkCommandResponseError(HandshakeSession &session,
		const Json::Value &doc)
	{
		session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

		SpawnException e(INTERNAL_ERROR, session.journey, session.config);
		addPreloaderEnvDumps(e);
		e.setSummary("An error occured while starting the web application: "
			+ doc["message"].asString());
		e.setProblemDescriptionHTML(
			"
The " PROGRAM_NAME " application server tried to"
			" start the web application by communicating with a"
			" helper process that we call a \"preloader\". However, "
			" this helper process reported an error:
"
			"
" + escapeHTML(doc["message"].asString()) + "
");
		e.setSolutionDescriptionHTML(
			"
"
			"Please try troubleshooting the problem by studying the"
			" error message and the"
			" diagnostics reports. You can also"
			" consult the " SHORT_PROGRAM_NAME
			" support resources for help.
");
		throw e.finalize();
	}

	void createStdChannelFifos(const HandshakeSession &session) {
		const string &workDir = session.workDir->getPath();
		createFifo(session, workDir + "/stdin");
		createFifo(session, workDir + "/stdout_and_err");
	}

	void createFifo(const HandshakeSession &session, const string &path) {
		int ret;

		do {
			ret = mkfifo(path.c_str(), 0600);
		} while (ret == -1 && errno == EAGAIN);
		if (ret == -1) {
			int e = errno;
			throw FileSystemException("Cannot create FIFO file " + path,
				e, path);
		}

		ret = syscalls::chown(path.c_str(), session.uid, session.gid);
		if (ret == -1) {
			int e = errno;
			throw FileSystemException("Cannot change owner and group on FIFO file " + path,
				e, path);
		}
	}

	string getBackgroundIOCapturerData(const BackgroundIOCapturerPtr &capturer) const {
		if (capturer != NULL) {
			// Sleep shortly to allow the child process to finish writing logs.
			syscalls::usleep(50000);
			return capturer->getData();
		} else {
			return string();
		}
	}

	uid_t getProcessUid(HandshakeSession &session, pid_t pid,
		const BackgroundIOCapturerPtr &stdoutAndErrCapturer)
	{
		TRACE_POINT();
		uid_t uid = (uid_t) -1;

		try {
			vector<pid_t> pids;
			pids.push_back(pid);
			ProcessMetricMap result = ProcessMetricsCollector().collect(pids);
			uid = result[pid].uid;
		} catch (const ParseException &) {
			HandshakePerform::loadJourneyStateFromResponseDir(session, pid, stdoutAndErrCapturer);
			session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

			SpawnException e(INTERNAL_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("Unable to query the UID of spawned application process "
				+ toString(pid) + ": error parsing 'ps' output");
			e.setSubprocessPid(pid);
			e.setProblemDescriptionHTML(
				"
Unable to use 'ps' to query PID " + toString(pid) + "
"
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application. As part of the starting"
				" procedure, " SHORT_PROGRAM_NAME " also tried to query"
				" the system user ID of the web application process"
				" using the operating system's \"ps\" tool. However,"
				" this tool returned output that " SHORT_PROGRAM_NAME
				" could not understand.
");
			e.setSolutionDescriptionHTML(
				createSolutionDescriptionForProcessMetricsCollectionError());
			throw e.finalize();
		} catch (const SystemException &originalException) {
			HandshakePerform::loadJourneyStateFromResponseDir(session, pid, stdoutAndErrCapturer);
			session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

			SpawnException e(OPERATING_SYSTEM_ERROR, session.journey, session.config);
			addPreloaderEnvDumps(e);
			e.setSummary("Unable to query the UID of spawned application process "
				+ toString(pid) + "; error capturing 'ps' output: "
				+ originalException.what());
			e.setSubprocessPid(pid);
			e.setProblemDescriptionHTML(
				"
Error capturing 'ps' output for PID " + toString(pid) + "
"
				"
The " PROGRAM_NAME " application server tried"
				" to start the web application. As part of the starting"
				" procedure, " SHORT_PROGRAM_NAME " also tried to query"
				" the system user ID of the web application process."
				" This is done by using the operating system's \"ps\""
				" tool and by querying operating system APIs and special"
				" files. However, an error was encountered while doing"
				" one of those things.
"
				"
The error returned by the operating system is as follows:
"
				"
" + escapeHTML(originalException.what()) + "
");
			e.setSolutionDescriptionHTML(
				createSolutionDescriptionForProcessMetricsCollectionError());
			throw e.finalize();
		}

		UPDATE_TRACE_POINT();
		if (uid == (uid_t) -1) {
			if (osProcessExists(pid)) {
				HandshakePerform::loadJourneyStateFromResponseDir(session, pid, stdoutAndErrCapturer);
				session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

				SpawnException e(INTERNAL_ERROR, session.journey, session.config);
				addPreloaderEnvDumps(e);
				e.setSummary("Unable to query the UID of spawned application process "
					+ toString(pid) + ": 'ps' did not report information"
					" about this process");
				e.setSubprocessPid(pid);
				e.setProblemDescriptionHTML(
					"
'ps' did not return any information about PID " + toString(pid) + "
"
					"
The " PROGRAM_NAME " application server tried"
					" to start the web application. As part of the starting"
					" procedure, " SHORT_PROGRAM_NAME " also tried to query"
					" the system user ID of the web application process"
					" using the operating system's \"ps\" tool. However,"
					" this tool did not return any information about"
					" the web application process.
");
				e.setSolutionDescriptionHTML(
					createSolutionDescriptionForProcessMetricsCollectionError());
				throw e.finalize();
			} else {
				HandshakePerform::loadJourneyStateFromResponseDir(session, pid, stdoutAndErrCapturer);
				session.journey.setStepErrored(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);

				SpawnException e(INTERNAL_ERROR, session.journey, session.config);
				addPreloaderEnvDumps(e);
				e.setSummary("The application process spawned from the preloader"
					" seems to have exited prematurely");
				e.setSubprocessPid(pid);
				e.setStdoutAndErrData(getBackgroundIOCapturerData(stdoutAndErrCapturer));
				e.setProblemDescriptionHTML(
					"
Application process exited prematurely
"
					"
The " PROGRAM_NAME " application server tried"
					" to start the web application. As part of the starting"
					" procedure, " SHORT_PROGRAM_NAME " also tried to query"
					" the system user ID of the web application process"
					" using the operating system's \"ps\" tool. However,"
					" this tool did not return any information about"
					" the web application process.
");
				e.setSolutionDescriptionHTML(
					createSolutionDescriptionForProcessMetricsCollectionError());
				throw e.finalize();
			}
		} else {
			return uid;
		}
	}

	static string createSolutionDescriptionForProcessMetricsCollectionError() {
		const char *path = getenv("PATH");
		if (path == NULL || path[0] == '\0') {
			path = "(empty)";
		}
		return "
"

			"
Check whether the \"ps\" tool is installed and accessible by "
			SHORT_PROGRAM_NAME "
"
			"
Maybe \"ps\" is not installed. Or maybe it is installed, but "
			SHORT_PROGRAM_NAME " cannot find it inside its PATH. Or"
			" maybe filesystem permissions disallow " SHORT_PROGRAM_NAME
			" from accessing \"ps\". Please check all these factors and"
			" fix them if necessary.
"
			"
" SHORT_PROGRAM_NAME "'s PATH is:
"
			"
" + escapeHTML(path) + "
"

			"
Check whether the server is low on resources
"
			"
Maybe the server is currently low on resources. This would"
			" cause the \"ps\" tool to encounter errors. Please study the"
			" error message and the diagnostics reports to"
			" verify whether this is the case. Key things to check for:
"
			"
"
			"
Excessive CPU usage
"
			"
Memory and swap
"
			"
Ulimits
"
			"
"
			"
If the server is indeed low on resources, find a way to"
			" free up some resources.
"

			"
Check whether /proc is mounted
"
			"
On many operating systems including Linux and FreeBSD, \"ps\""
			" only works if /proc is mounted. Please check this.
"

			"
Still no luck?
"
			"
Please try troubleshooting the problem by studying the"
			" diagnostics reports.
"

			"
";
	}

	static void adjustTimeout(MonotonicTimeUsec startTime, unsigned long long *timeout) {
		boost::this_thread::disable_interruption di;
		boost::this_thread::disable_syscall_interruption dsi;
		MonotonicTimeUsec now = SystemTime::getMonotonicUsec();
		assert(now >= startTime);
		MonotonicTimeUsec diff = now - startTime;
		if (*timeout >= diff) {
			*timeout -= diff;
		} else {
			*timeout = 0;
		}
	}

	static void doClosedir(DIR *dir) {
		closedir(dir);
	}

	static string findPreloaderCommandSocketAddress(const HandshakeSession &session) {
		const vector<Result::Socket> &sockets = session.result.sockets;
		vector<Result::Socket>::const_iterator it, end = sockets.end();
		for (it = sockets.begin(); it != end; it++) {
			if (it->protocol == "preloader") {
				return it->address;
			}
		}
		return string();
	}

	static StringKeyTable<string> loadAnnotationsFromEnvDumpDir(const string &envDumpDir,
		int envDumpAnnotationsDirFd)
	{
		string path = envDumpDir + "/annotations";
		DIR *dir = opendir(path.c_str());
		if (dir == NULL) {
			return StringKeyTable<string>();
		}

		ScopeGuard guard(boost::bind(doClosedir, dir));
		StringKeyTable<string> result;
		struct dirent *ent;
		while ((ent = readdir(dir)) != NULL) {
			if (ent->d_name[0] != '.') {
				result.insert(ent->d_name, strip(safeReadFile(envDumpAnnotationsDirFd,
					ent->d_name, SPAWNINGKIT_MAX_SUBPROCESS_ENVDUMP_SIZE).first), true);
			}
		}

		result.compact();

		return result;
	}

	void addPreloaderEnvDumps(SpawnException &e) const {
		e.setPreloaderPid(pid);
		e.setPreloaderEnvvars(preloaderEnvvars);
		e.setPreloaderUserInfo(preloaderUserInfo);
		e.setPreloaderUlimits(preloaderUlimits);

		if (e.getSubprocessEnvvars().empty()) {
			e.setSubprocessEnvvars(preloaderEnvvars);
		}
		if (e.getSubprocessUserInfo().empty()) {
			e.setSubprocessUserInfo(preloaderUserInfo);
		}
		if (e.getSubprocessUlimits().empty()) {
			e.setSubprocessUlimits(preloaderUlimits);
		}

		StringKeyTable<string>::ConstIterator it(preloaderAnnotations);
		while (*it != NULL) {
			e.setAnnotation(it.getKey(), it.getValue(), false);
			it.next();
		}
	}

public:
	SmartSpawner(Context *context,
		const vector<string> &preloaderCommand,
		const AppPoolOptions &_options)
		: Spawner(context),
		  preloaderCommandString(createCommandString(preloaderCommand))
	{
		if (preloaderCommand.size() < 2) {
			throw ArgumentException("preloaderCommand must have at least 2 elements");
		}

		options    = _options.copyAndPersist();
		pid        = -1;
		m_lastUsed = SystemTime::getUsec();
	}

	virtual ~SmartSpawner() {
		boost::lock_guard<boost::mutex> l(syncher);
		stopPreloader();
	}

	virtual Result spawn(const AppPoolOptions &options) {
		TRACE_POINT();
		P_ASSERT_EQ(options.appType, this->options.appType);
		P_ASSERT_EQ(options.appRoot, this->options.appRoot);

		P_DEBUG("Spawning new process: appRoot=" << options.appRoot);
		possiblyRaiseInternalError(options);

		{
			boost::lock_guard<boost::mutex> l(simpleFieldSyncher);
			m_lastUsed = SystemTime::getUsec();
		}
		UPDATE_TRACE_POINT();
		boost::lock_guard<boost::mutex> l(syncher);
		if (!preloaderStarted()) {
			UPDATE_TRACE_POINT();
			startPreloader();
		}

		UPDATE_TRACE_POINT();
		Config config;
		Json::Value extraArgs;
		try {
			setConfigFromAppPoolOptions(&config, extraArgs, options);
		} catch (const std::exception &originalException) {
			Journey journey(SPAWN_THROUGH_PRELOADER, true);
			journey.setStepErrored(SPAWNING_KIT_PREPARATION, true);
			SpawnException e(originalException, journey, &config);
			addPreloaderEnvDumps(e);
			throw e.finalize();
		}

		UPDATE_TRACE_POINT();
		HandshakeSession session(*context, config, SPAWN_THROUGH_PRELOADER);
		session.journey.setStepInProgress(SPAWNING_KIT_PREPARATION);
		JourneyStep stepToMarkAsErrored = SPAWNING_KIT_PREPARATION;

		try {
			UPDATE_TRACE_POINT();
			HandshakePrepare prepare(session, extraArgs);
			prepare.execute();
			createStdChannelFifos(session);
			prepare.finalize();
			session.journey.setStepPerformed(SPAWNING_KIT_PREPARATION, true);

			UPDATE_TRACE_POINT();
			ForkResult forkResult = invokeForkCommand(session, stepToMarkAsErrored);

			UPDATE_TRACE_POINT();
			ScopeGuard guard(boost::bind(nonInterruptableKillAndWaitpid, forkResult.pid));
			P_DEBUG("Process forked for appRoot=" << options.appRoot << ": PID " << forkResult.pid);

			UPDATE_TRACE_POINT();
			session.journey.setStepPerformed(SPAWNING_KIT_PROCESS_RESPONSE_FROM_PRELOADER);
			session.journey.setStepInProgress(PRELOADER_PREPARATION);
			session.journey.setStepInProgress(SPAWNING_KIT_HANDSHAKE_PERFORM);
			stepToMarkAsErrored = SPAWNING_KIT_HANDSHAKE_PERFORM;
			HandshakePerform(session, forkResult.pid, forkResult.stdinFd,
				forkResult.stdoutAndErrFd, forkResult.alreadyReadStdoutAndErrData).
				execute();
			guard.clear();
			session.journey.setStepPerformed(SPAWNING_KIT_HANDSHAKE_PERFORM);
			P_DEBUG("Process spawning done: appRoot=" << options.appRoot <<
				", pid=" << forkResult.pid);
			return session.result;
		} catch (SpawnException &e) {
			addPreloaderEnvDumps(e);
			throw e;
		} catch (const std::exception &originalException) {
			session.journey.setStepErrored(stepToMarkAsErrored, true);
			SpawnException e(originalException, session.journey,
				&config);
			addPreloaderEnvDumps(e);
			throw e.finalize();
		}
	}

	virtual bool cleanable() const {
		return true;
	}

	virtual void cleanup() {
		TRACE_POINT();
		{
			boost::lock_guard<boost::mutex> l(simpleFieldSyncher);
			m_lastUsed = SystemTime::getUsec();
		}
		boost::lock_guard<boost::mutex> lock(syncher);
		stopPreloader();
	}

	virtual unsigned long long lastUsed() const {
		boost::lock_guard<boost::mutex> lock(simpleFieldSyncher);
		return m_lastUsed;
	}

	pid_t getPreloaderPid() const {
		boost::lock_guard<boost::mutex> lock(simpleFieldSyncher);
		return pid;
	}
};

} // namespace SpawningKit
} // namespace Passenger

#endif /* _PASSENGER_SPAWNING_KIT_SMART_SPAWNER_H_ */


text:
Overview
========

PHP API Library for FAA Api
http://services.faa.gov/

Airport Service
Description

Serves airport status and delay information from the Air Traffic Control System Command Center (ATCSCC) as displayed on http://fly.faa.gov/.

Usage
=====

<pre>

// Base API Class
require 'APIBaseClass.php';

require 'faaApi.php';

$new = new faaApi();
$new->airport_status('IAD');
$new->airport_status('xml');

// Debug information
die(print_r($new).print_r(get_object_vars($new)).print_r(get_class_methods(get_class($new))));

</pre>

Output
======


text:
//Copyright 2012 Cameron Wengert

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

Class.create("Resizable", {

        initialize: function(elm) {
            /*
                Method:initialize

                Create a new resizable object

                Parameters:
                    elm - The Element to make resizable
                    options - Additional optional arguments available to be passed in as an object
            */

            var defaults = {
                onStart: null,
                onEnd: null,
                'default_style':true,
                'class_name':'resizableHandle'
            };

            this.options = Object.extend(defaults, arguments[1] || {});

            if (this.options.onStart) {
                this.onStart = this.options.onStart;
            }

            if (this.options.onEnd) {
                this.onEnd = this.options.onEnd;
            }

            //Container
            this.c = elm;
            if(!this.c.getStyle('position')) {
                this.c.setStyle({'position':'relative'});
            }

            //Resizer Element
            this.resizer = new Element('div', {'class':this.options['class_name']});
            if (this.options['default_style']) {
                this.resizer.writeAttribute({
                    'style':'width:10px; height:10px; position:absolute; background-color:grey;'
                });
            }

            // Hide and place the resizer to get its dimensions
            this.resizer.toggle();
            this.c.insert(this.resizer);

            this.setResizer();

            this.start_count = 0;

            // Setup Events
            this.resizer.observe('mousedown', function(ev) {
                    if (this.onStart && this.start_count < 1) {
                        this.onStart();
                    }
                this.c.observe('resizer:mousemove', function(ev) {
                    this.resizing(ev.memo);
                }.bind(this));

                this.c.observe('resizer:mouseup', function(ev) {
                    this.start_count = 0;
                    if (this.onEnd) {
                        this.onEnd();
                    }
                    this.c.stopObserving('resizer:mousemove');
                    this.c.stopObserving('resizer:mouseup');
                }.bind(this));

                var p = Event.pointer(ev);
                this.start_x = p.x;
                this.start_y = p.y;

                document.observe('mousemove', function(ev) {
                    this.c.fire('resizer:mousemove', ev);
                }.bind(this));

                document.observe('mouseup', function(ev) {
                    this.c.fire('resizer:mouseup', ev);
                }.bind(this));
            }.bind(this));

            // Disable ondragstart
            this.resizer.ondragstart = function() { return false; };
            // Show resizer now that it's ready
            this.resizer.toggle();
        },

        setResizer: function() {
            /*
                Method:setResizer

                Position the resizer element in the bottom right hand corner
                of the container element.
            */

            var r_layout = this.resizer.getLayout();
            var c_layout = this.c.getLayout();

            Element.setStyle(this.resizer,{
                'position':'absolute',
                'left':c_layout.get('padding-box-width') - r_layout.get('padding-box-width') + 'px',
                'top':c_layout.get('padding-box-height') - r_layout.get('padding-box-width') + 'px'
            });
        },

        resizing: function(ev) {
            /*
                Method:resizing

                Change the dimension of the the container based on the ev argument.

                Parameters:
                    ev - The event memo data (mouse coords) that triggered the resizing

            */
            var p = Event.pointer(ev);
            var xdiff = p.x - this.start_x;
            var ydiff = p.y - this.start_y;

            var c_layout = this.c.getLayout();

            this.c.setStyle({'width': c_layout.get('width') + xdiff + 'px'});
            this.c.setStyle({'height': c_layout.get('height') + ydiff + 'px' });

            this.start_x = p.x;
            this.start_y = p.y;

            // We moved the container so lets set the resizer to match
            this.setResizer();
        }

    });


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="DaemonCodeAnalyzer">
    <disable_hints />
  </component>
  <component name="EntryPointsManager">
    <entry_points version="2.0" />
  </component>
  <component name="FrameworkDetectionExcludesConfiguration">
    <file type="web" url="file://$PROJECT_DIR$" />
  </component>
  <component name="IdProvider" IDEtalkID="703AEF91EFDF85845A20E39447646940" />
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>Abstraction issues</id>
          </State>
          <State>
            <id>ActionScript specificJavaScript</id>
          </State>
          <State>
            <id>Android Lint</id>
          </State>
          <State>
            <id>Assignment issues</id>
          </State>
          <State>
            <id>Assignment issuesGroovy</id>
          </State>
          <State>
            <id>Assignment issuesJavaScript</id>
          </State>
          <State>
            <id>CSS</id>
          </State>
          <State>
            <id>Class structure</id>
          </State>
          <State>
            <id>Cloning issues</id>
          </State>
          <State>
            <id>Code maturity issues</id>
          </State>
          <State>
            <id>Code style issues</id>
          </State>
          <State>
            <id>Control FlowGroovy</id>
          </State>
          <State>
            <id>Control flow issues</id>
          </State>
          <State>
            <id>Control flow issuesJavaScript</id>
          </State>
          <State>
            <id>Data flow issues</id>
          </State>
          <State>
            <id>Error handling</id>
          </State>
          <State>
            <id>GPath inspectionsGroovy</id>
          </State>
          <State>
            <id>General</id>
          </State>
          <State>
            <id>Google Web Toolkit issues</id>
          </State>
          <State>
            <id>Gradle</id>
          </State>
          <State>
            <id>Groovy</id>
          </State>
          <State>
            <id>HTML</id>
          </State>
          <State>
            <id>Inheritance issues</id>
          </State>
          <State>
            <id>Internationalization issues</id>
          </State>
          <State>
            <id>J2ME issues</id>
          </State>
          <State>
            <id>JUnit issues</id>
          </State>
          <State>
            <id>Java language level migration aids</id>
          </State>
          <State>
            <id>JavaScript</id>
          </State>
          <State>
            <id>JavaScript validity issuesJavaScript</id>
          </State>
          <State>
            <id>Javadoc issues</id>
          </State>
          <State>
            <id>Memory issues</id>
          </State>
          <State>
            <id>Numeric issues</id>
          </State>
          <State>
            <id>Performance issues</id>
          </State>
          <State>
            <id>Portability issues</id>
          </State>
          <State>
            <id>Potentially confusing code constructsGroovy</id>
          </State>
          <State>
            <id>Potentially confusing code constructsJavaScript</id>
          </State>
          <State>
            <id>Probable bugs</id>
          </State>
          <State>
            <id>Probable bugsGradle</id>
          </State>
          <State>
            <id>Probable bugsGroovy</id>
          </State>
          <State>
            <id>Resource management issues</id>
          </State>
          <State>
            <id>Security issues</id>
          </State>
          <State>
            <id>Serialization issues</id>
          </State>
          <State>
            <id>Spring Model</id>
          </State>
          <State>
            <id>Struts</id>
          </State>
          <State>
            <id>Struts 2Struts</id>
          </State>
          <State>
            <id>TestNG</id>
          </State>
          <State>
            <id>Threading issues</id>
          </State>
          <State>
            <id>Web Services</id>
          </State>
          <State>
            <id>WebSocket issues</id>
          </State>
        </expanded-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/build/classes" />
  </component>
  <component name="RunManager">
    <configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" factoryName="Plugin">
      <module name="" />
      <option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m -ea" />
      <option name="PROGRAM_PARAMETERS" />
      <method />
    </configuration>
    <configuration default="true" type="Remote" factoryName="Remote">
      <option name="USE_SOCKET_TRANSPORT" value="true" />
      <option name="SERVER_MODE" value="false" />
      <option name="SHMEM_ADDRESS" value="javadebug" />
      <option name="HOST" value="localhost" />
      <option name="PORT" value="5005" />
      <method />
    </configuration>
    <configuration default="true" type="Applet" factoryName="Applet">
      <module name="" />
      <option name="MAIN_CLASS_NAME" />
      <option name="HTML_FILE_NAME" />
      <option name="HTML_USED" value="false" />
      <option name="WIDTH" value="400" />
      <option name="HEIGHT" value="300" />
      <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
      <option name="VM_PARAMETERS" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <method />
    </configuration>
    <configuration default="true" type="TestNG" factoryName="TestNG">
      <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
      <module name="" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="SUITE_NAME" />
      <option name="PACKAGE_NAME" />
      <option name="MAIN_CLASS_NAME" />
      <option name="METHOD_NAME" />
      <option name="GROUP_NAME" />
      <option name="TEST_OBJECT" value="CLASS" />
      <option name="VM_PARAMETERS" value="-ea" />
      <option name="PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="OUTPUT_DIRECTORY" />
      <option name="ANNOTATION_TYPE" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <option name="TEST_SEARCH_SCOPE">
        <value defaultName="moduleWithDependencies" />
      </option>
      <option name="USE_DEFAULT_REPORTERS" value="false" />
      <option name="PROPERTIES_FILE" />
      <envs />
      <properties />
      <listeners />
      <method />
    </configuration>
    <configuration default="true" type="Application" factoryName="Application">
      <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
      <option name="MAIN_CLASS_NAME" />
      <option name="VM_PARAMETERS" />
      <option name="PROGRAM_PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="ENABLE_SWING_INSPECTOR" value="false" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <module name="" />
      <envs />
      <method />
    </configuration>
    <configuration default="true" type="JUnit" factoryName="JUnit">
      <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
      <module name="" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="PACKAGE_NAME" />
      <option name="MAIN_CLASS_NAME" />
      <option name="METHOD_NAME" />
      <option name="TEST_OBJECT" value="class" />
      <option name="VM_PARAMETERS" value="-ea" />
      <option name="PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <option name="TEST_SEARCH_SCOPE">
        <value defaultName="moduleWithDependencies" />
      </option>
      <envs />
      <patterns />
      <method />
    </configuration>
    <list size="0" />
    <configuration name="<template>" type="WebApp" default="true" selected="false">
      <Host>localhost</Host>
      <Port>5050</Port>
    </configuration>
  </component>
</project>


text:
ruhoh-theme-bootstrap3
======================

A basic ruhoh theme using Twitter's Bootstrap v3. I used
[theme-bootstrap-2](https://github.com/ruhoh/theme-bootstrap-2) as a starting
point and updated it to use bootstrap v3's HTML markup and CSS classes.

Comments and patches welcome! If you end up using this theme, please consider
linking back and do let me know so I may include it here :)


text:
require 'multi_json'
require 'net/http'

module BestBuy
  # Represents an unfulfilled request to the BestBuy API. Fullfillment of the
  # request can be triggered by invoking Request#call. Request also provides
  # methods to inspect the request that will be made to the BestBuy API
  class Request
    # Endpoints that are supported by this API client
    VALID_ENDPOINTS = [
      'products',
    ]
    # @param api_key[String] The API key required by the BestBuy API
    # @param endpoint[String] The endpoint of the API that this request will be made against. Must be one of VALID_ENDPOINTS
    # @param filters[Array<String>] Filters that will be applied to the particular resource being requested.
    def initialize(api_key:, endpoint:, affiliate_tracking_id: nil, filters: [])
      unless VALID_ENDPOINTS.include? endpoint
        fail APIError, "The endpoint \"#{endpoint}\" is currently unsupported. Supported endpoints are: #{VALID_ENDPOINTS.join(", ")}"
      end
      @endpoint = endpoint
      @filters = filters
      @affiliate_tracking_id = affiliate_tracking_id
      @api_key = api_key
      @show_params = []
    end

    # @returns [String] The URL that will be used for this Request
    def to_s
      "https://api.bestbuy.com/v1/#{@endpoint}(#{@filters.join('|')})?#{query_string}"
    end

    # Converts the request into a cURL request for debugging purposes
    #
    # @returns [String] An eval-able string that will make a request using cURL to the BestBuy API
    def to_curl
      "curl #{to_s}"
    end

    # Sets the request to only return the specified fields from the API
    #
    # @example Pluck attributes
    #   bby = BestBuy::Client.new(api_key: '12345')
    #   bby.products(upc: '004815162342').pluck(:name).call
    #   #=> [{:name => "MegaProduct 5000"}]
    # @param requested_fields [Array<Symbol>] The requested fields that should be included in product results
    # @return BestBuy::Request The augmented request
    def pluck(*requested_fields)
      @show_params = requested_fields.map(&:to_s)
      self
    end

    # Synchronously executes a request to the BestBuy API. This will block until results are ready and have been parsed
    #
    # @return Array<Hash> The results returned from the API.
    def call
      resp = ::Net::HTTP.get URI(to_s)
      ::MultiJson.decode(resp)['products']
    end

    # Returns the query string that will be used for this request. Query string parameters are returned in alphabetical order.
    #
    # @return String The query string for this request
    def query_string
      [
        api_key_param,
        format_param,
        show_param,
        affiliate_param,
      ].compact.sort.join("&")
    end

    private

    # Inserts the query string parameter responsible for crediting affiliate links
    def affiliate_param
      if @affiliate_tracking_id
        "LID=#{@affiliate_tracking_id}"
      end
    end

    # Controls the apiKey query string parameter
    def api_key_param
      "apiKey=#{@api_key}"
    end

    # Changes the response format. The API accepts XML, but this gem requres JSON
    def format_param
      "format=json"
    end

    # Controls the fields returned for API response items. Corresponsds to the "show" query parameter
    def show_param
      if @show_params && @show_params.length > 0
        "show=#{@show_params.join(",")}"
      else
        nil
      end
    end
  end
end


text: <button id="hotword-start" i18n-content="introStart"></button>


text:
package helper;

import controller.SimulationSettings;
import java.util.Collection;
import java.util.Random;

/**
 * A simple helper class that has method I need more than once
 *
 * @author Kareem Horstink
 */
public class StupidHelper {

    /**
     * Randomly chooses a item of a collection
     *
     * @param c The things to choose from
     * @return A random object from that collection
     */
    public static Object getRandom(Collection c) {
        if(c.isEmpty()){
            return null;
        }
Random r = SimulationSettings.getInstance().getRandom();
        return c.toArray()[r.nextInt(c.size())];
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Tranzschel & Serebrianikow, Mycotheca rossica, Fascicle <b>6 & 7</b> 7 (1912)

#### Original name
Stegonsporium bubakianum Serebrian.

### Remarks
null


text:
module Fog
  module Compute
    class Vsphere
      class Real

        def add_vm_interface(vmid, options = {})
          raise ArgumentError, "instance id is a required parameter" unless vmid

          interface = get_interface_from_options(vmid, options.merge(:server_id => vmid))
          vm_reconfig_hardware('instance_uuid' => vmid, 'hardware_spec' => {'deviceChange'=>[create_interface(interface)]})
        end

        def destroy_vm_interface(vmid, options = {})
          raise ArgumentError, "instance id is a required parameter" unless vmid

          interface = get_interface_from_options(vmid, options.merge(:server_id => vmid))
          vm_reconfig_hardware('instance_uuid' => vmid, 'hardware_spec' => {'deviceChange'=>[create_interface(interface, interface.key, :remove)]})
        end

        def update_vm_interface(vmid, options = {})
          raise ArgumentError, "instance id is a required parameter" unless vmid

          interface = get_interface_from_options(vmid, options.merge(:server_id => vmid))
          vm_reconfig_hardware('instance_uuid' => vmid, 'hardware_spec' => {'deviceChange'=>[create_interface(interface, interface.key, :edit)]})
        end

        private
        def get_interface_from_options(vmid, options)
          if options and options[:interface]
            options[:interface]

          elsif options[:key] and options[:key]>0
            oldattributes = get_vm_interface(vmid, options)
            Fog::Compute::Vsphere::Interface.new(oldattributes.merge(options))

          elsif options[:type] and options[:network]
            Fog::Compute::Vsphere::Interface.new options

          else
            raise ArgumentError, "interface is a required parameter or pass options with type and network"
          end
        end

      end

      class Mock
        def add_vm_interface(vmid, options = {})
          raise ArgumentError, "instance id is a required parameter" unless vmid
          raise ArgumentError, "interface is a required parameter" unless options and options[:interface]
          true
        end

        def destroy_vm_interface(vmid, options = {})
          raise ArgumentError, "instance id is a required parameter" unless vmid
          raise ArgumentError, "interface is a required parameter" unless options and options[:interface]
          true
        end
      end
    end
  end
end


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\AssessmentMatrixQuestion\Integration\Chamilo\Core\Repository\ContentObject\Assessment\Package;

class Activator extends \Chamilo\Configuration\Package\Action\Activator
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:res="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal">

    <androidx.cardview.widget.CardView
        style="@style/LimitedWidthView"
        android:layout_height="wrap_content"
        res:cardCornerRadius="@dimen/corner_radius"
        res:cardPreventCornerOverlap="true"
        res:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:ellipsize="end"
                android:focusable="true"
                android:foreground="?attr/selectableItemBackground"
                android:includeFontPadding="false"
                android:maxLines="2"
                android:paddingLeft="16dp"
                android:paddingTop="16dp"
                android:paddingRight="16dp"
                android:textSize="20sp" />

            <LinearLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="16dp"
                android:orientation="vertical"
                android:paddingLeft="16dp"
                android:paddingTop="8dp"
                android:paddingRight="16dp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>


text:
This is a command line interface to the
[eros library](https://github.com/pharpend/eros).

# Usage - v.0.5.0.0

This is a usage guide for version 0.5.0.0. There will be more up-to-date usage
guides as more versions come, hopefully.

To install, run `cabal install eros-client-0.5.0.0`.

The only way to interact with the library, for the time being is through the
client I built, `erosc`. It accepts input in Javascript Object Notation (JSON)
through `stdin`.

Here is the schema for the input:

```json
{
  "name": "erosc-input",
  "type": "object",
  "description": "The schema for the input to erosc.",
  "properties": {
    "text": {
      "type": "string",
      "description": "The text you want to be checked against the phraselists.",
      "required": true
    },
    "eros-lists": {
      "type": "array",
      "description": "The phraselists provided by eros you want \"text\" to be checked against.",
      "required": true,
      "items": {
        "type": "string"
      }
    },
    "options": {
      "type": "object",
      "description": "Extraneous options for erosc.",
      "required": false,
      "properties": {
        "pretty": {
          "type": "boolean",
          "description": "Whether to pretty-print the output. Defaults to `true'.",
          "required": false
        },
        "quiet": {
          "type": "boolean",
          "description": "Suppress output to stdout. Defauts to `false'.",
          "required": false
        },
        "output-files": {
          "type": "array",
          "description": "A list of output file paths. Will overwrite existing files",
          "required": false,
          "items": {
            "type": "string"
          }
        }
      }
    }
  }
}
```

That is the up-to-date schema, as of version 0.5.0.0 . It is liable to
change. If the version you downloaded is greater than 0.5.0.0, make sure to
check the schema (it is distributed with the package) to make sure it is up to
date. The schema is located in `res/schemata/erosc-input.json`.

`erosc` will take that input, and send back output in JSON, in accordance with
the schema found in `res/schemata/erosc-output.json`.

```json
{
  "name": "erosc-output",
  "type": "array",
  "description": "The output of erosc.",
  "items": {
    "type": "object",
    "description": "The phraselist name, along with the score for that phraselist.",
    "properties": {
      "eros-list": {
        "type": "string",
        "description": "The name of the phraselist corresponding to this object."
      },
      "score": {
        "type": "number",
        "description": "The score corresponding to this phraselist."
      }
    }
  }
}
```

## Example

This is the example input from `res/erosc-dummy-inputs/input0.json`.

```json
{
  "text": "Fuck you, you fucking fuck! Fucking bitch tits milf sex sluts!",
  "eros-lists": [
    "gambling",
    "pornography"
  ]
}
```

Running `erosc < res/erosc-dummy-inputs/input0.json` yields

```json
[
  {
    "score": 0,
    "eros-list": "gambling"
  },
  {
    "score": 11394,
    "eros-list": "pornography"
  }
]
```

# Contributing

I would love if people would contribute. This client is BSD-licensed, so you can
pretty much do whatever you want with it.

If you have any ideas, don't hesitate to contact me.

## Planned features

I need to add more filtering options, such as phraselist-specific thresholds,
custom phraselists, and, well, just more stuff.

# Contact

The best way to contact me is via IRC. I hang out a lot on `#archlinux` and
`#haskell` on the FreeNode network. My nicks are `l0cust` and `isomorpheous`.

You can also email me at <pharpend2@gmail.com>, although I'm not great at
checking that email address.


text:
@interface ShopInformationView : UIView
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *secondView;
@property (nonatomic, strong) UIView *thirdView;
@property (nonatomic, strong) UIView *fouthView;
@property (nonatomic, strong) UISwitch *stateSwitch;//开关
@property (nonatomic, strong) UITextField *shopNameTF;
@property (nonatomic, strong) UIImageView *shopHeadImageView;//商铺头像
@property (nonatomic, strong) UIImageView *shopListImageView;//列表展示图
@property (nonatomic, strong) UIImageView *shopBannerImageView;//横幅展示图

@property (nonatomic, strong) UIButton *headImageViewBtn;//头像
@property (nonatomic, strong) UITextView *detailAddressTV;//详细地址
@property (nonatomic, strong) UILabel *shopStateLabel;//店铺状态
@property (nonatomic, strong) UILabel *chooseCategoryLabel;//店铺分类
@property (nonatomic, strong) UIImageView *categoryImage;
@property (nonatomic, strong) UILabel *discountLabel;//折扣
@property (nonatomic, strong) UITextField *phoneTF;//电话
@property (nonatomic, strong) UIButton *chooseCategoryBtn;//选择分类
@property (nonatomic, strong) UIButton *shopBannerBtn;//横幅展示图按钮
@property (nonatomic, strong) UIButton *showListBtn;//列表展示图按钮
@property (nonatomic, strong) UIButton *showEnvironmentBtn;//环境展示图按钮

@property (nonatomic, strong) UIButton *mapBtn;

@end


text:
obj-y = main.o
obj-$(CONFIG_SOC_WATCH) += soc_watch_logger.o


text:
#include <linux/kernel.h>
#include <linux/in.h>
#include <linux/if.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/if_arp.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/module.h>

#include "rds.h"
#include "iw.h"

unsigned int fastreg_pool_size = RDS_FASTREG_POOL_SIZE;
unsigned int fastreg_message_size = RDS_FASTREG_SIZE + 1; /* +1 allows for unaligned MRs */

module_param(fastreg_pool_size, int, 0444);
MODULE_PARM_DESC(fastreg_pool_size, " Max number of fastreg MRs per device");
module_param(fastreg_message_size, int, 0444);
MODULE_PARM_DESC(fastreg_message_size, " Max size of a RDMA transfer (fastreg MRs)");

struct list_head rds_iw_devices;

/* NOTE: if also grabbing iwdev lock, grab this first */
DEFINE_SPINLOCK(iw_nodev_conns_lock);
LIST_HEAD(iw_nodev_conns);

static void rds_iw_add_one(struct ib_device *device)
{
	struct rds_iw_device *rds_iwdev;
	struct ib_device_attr *dev_attr;

	/* Only handle iwarp devices */
	if (device->node_type != RDMA_NODE_RNIC)
		return;

	dev_attr = kmalloc(sizeof *dev_attr, GFP_KERNEL);
	if (!dev_attr)
		return;

	if (ib_query_device(device, dev_attr)) {
		rdsdebug("Query device failed for %s\n", device->name);
		goto free_attr;
	}

	rds_iwdev = kmalloc(sizeof *rds_iwdev, GFP_KERNEL);
	if (!rds_iwdev)
		goto free_attr;

	spin_lock_init(&rds_iwdev->spinlock);

	rds_iwdev->dma_local_lkey = !!(dev_attr->device_cap_flags & IB_DEVICE_LOCAL_DMA_LKEY);
	rds_iwdev->max_wrs = dev_attr->max_qp_wr;
	rds_iwdev->max_sge = min(dev_attr->max_sge, RDS_IW_MAX_SGE);

	rds_iwdev->dev = device;
	rds_iwdev->pd = ib_alloc_pd(device);
	if (IS_ERR(rds_iwdev->pd))
		goto free_dev;

	if (!rds_iwdev->dma_local_lkey) {
		rds_iwdev->mr = ib_get_dma_mr(rds_iwdev->pd,
					IB_ACCESS_REMOTE_READ |
					IB_ACCESS_REMOTE_WRITE |
					IB_ACCESS_LOCAL_WRITE);
		if (IS_ERR(rds_iwdev->mr))
			goto err_pd;
	} else
		rds_iwdev->mr = NULL;

	rds_iwdev->mr_pool = rds_iw_create_mr_pool(rds_iwdev);
	if (IS_ERR(rds_iwdev->mr_pool)) {
		rds_iwdev->mr_pool = NULL;
		goto err_mr;
	}

	INIT_LIST_HEAD(&rds_iwdev->cm_id_list);
	INIT_LIST_HEAD(&rds_iwdev->conn_list);
	list_add_tail(&rds_iwdev->list, &rds_iw_devices);

	ib_set_client_data(device, &rds_iw_client, rds_iwdev);

	goto free_attr;

err_mr:
	if (rds_iwdev->mr)
		ib_dereg_mr(rds_iwdev->mr);
err_pd:
	ib_dealloc_pd(rds_iwdev->pd);
free_dev:
	kfree(rds_iwdev);
free_attr:
	kfree(dev_attr);
}

static void rds_iw_remove_one(struct ib_device *device, void *client_data)
{
	struct rds_iw_device *rds_iwdev = client_data;
	struct rds_iw_cm_id *i_cm_id, *next;

	if (!rds_iwdev)
		return;

	spin_lock_irq(&rds_iwdev->spinlock);
	list_for_each_entry_safe(i_cm_id, next, &rds_iwdev->cm_id_list, list) {
		list_del(&i_cm_id->list);
		kfree(i_cm_id);
	}
	spin_unlock_irq(&rds_iwdev->spinlock);

	rds_iw_destroy_conns(rds_iwdev);

	if (rds_iwdev->mr_pool)
		rds_iw_destroy_mr_pool(rds_iwdev->mr_pool);

	if (rds_iwdev->mr)
		ib_dereg_mr(rds_iwdev->mr);

	ib_dealloc_pd(rds_iwdev->pd);

	list_del(&rds_iwdev->list);
	kfree(rds_iwdev);
}

struct ib_client rds_iw_client = {
	.name   = "rds_iw",
	.add    = rds_iw_add_one,
	.remove = rds_iw_remove_one
};

static int rds_iw_conn_info_visitor(struct rds_connection *conn,
				    void *buffer)
{
	struct rds_info_rdma_connection *iinfo = buffer;
	struct rds_iw_connection *ic;

	/* We will only ever look at IB transports */
	if (conn->c_trans != &rds_iw_transport)
		return 0;

	iinfo->src_addr = conn->c_laddr;
	iinfo->dst_addr = conn->c_faddr;

	memset(&iinfo->src_gid, 0, sizeof(iinfo->src_gid));
	memset(&iinfo->dst_gid, 0, sizeof(iinfo->dst_gid));
	if (rds_conn_state(conn) == RDS_CONN_UP) {
		struct rds_iw_device *rds_iwdev;
		struct rdma_dev_addr *dev_addr;

		ic = conn->c_transport_data;
		dev_addr = &ic->i_cm_id->route.addr.dev_addr;

		rdma_addr_get_sgid(dev_addr, (union ib_gid *) &iinfo->src_gid);
		rdma_addr_get_dgid(dev_addr, (union ib_gid *) &iinfo->dst_gid);

		rds_iwdev = ib_get_client_data(ic->i_cm_id->device, &rds_iw_client);
		iinfo->max_send_wr = ic->i_send_ring.w_nr;
		iinfo->max_recv_wr = ic->i_recv_ring.w_nr;
		iinfo->max_send_sge = rds_iwdev->max_sge;
		rds_iw_get_mr_info(rds_iwdev, iinfo);
	}
	return 1;
}

static void rds_iw_ic_info(struct socket *sock, unsigned int len,
			   struct rds_info_iterator *iter,
			   struct rds_info_lengths *lens)
{
	rds_for_each_conn_info(sock, len, iter, lens,
				rds_iw_conn_info_visitor,
				sizeof(struct rds_info_rdma_connection));
}

/*
 * Early RDS/IB was built to only bind to an address if there is an IPoIB
 * device with that address set.
 *
 * If it were me, I'd advocate for something more flexible.  Sending and
 * receiving should be device-agnostic.  Transports would try and maintain
 * connections between peers who have messages queued.  Userspace would be
 * allowed to influence which paths have priority.  We could call userspace
 * asserting this policy "routing".
 */
static int rds_iw_laddr_check(struct net *net, __be32 addr)
{
	int ret;
	struct rdma_cm_id *cm_id;
	struct sockaddr_in sin;

	/* Create a CMA ID and try to bind it. This catches both
	 * IB and iWARP capable NICs.
	 */
	cm_id = rdma_create_id(&init_net, NULL, NULL, RDMA_PS_TCP, IB_QPT_RC);
	if (IS_ERR(cm_id))
		return PTR_ERR(cm_id);

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = addr;

	/* rdma_bind_addr will only succeed for IB & iWARP devices */
	ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);
	/* due to this, we will claim to support IB devices unless we
	   check node_type. */
	if (ret || !cm_id->device ||
	    cm_id->device->node_type != RDMA_NODE_RNIC)
		ret = -EADDRNOTAVAIL;

	rdsdebug("addr %pI4 ret %d node type %d\n",
		&addr, ret,
		cm_id->device ? cm_id->device->node_type : -1);

	rdma_destroy_id(cm_id);

	return ret;
}

void rds_iw_exit(void)
{
	rds_info_deregister_func(RDS_INFO_IWARP_CONNECTIONS, rds_iw_ic_info);
	rds_iw_destroy_nodev_conns();
	ib_unregister_client(&rds_iw_client);
	rds_iw_sysctl_exit();
	rds_iw_recv_exit();
	rds_trans_unregister(&rds_iw_transport);
}

struct rds_transport rds_iw_transport = {
	.laddr_check		= rds_iw_laddr_check,
	.xmit_complete		= rds_iw_xmit_complete,
	.xmit			= rds_iw_xmit,
	.xmit_rdma		= rds_iw_xmit_rdma,
	.recv			= rds_iw_recv,
	.conn_alloc		= rds_iw_conn_alloc,
	.conn_free		= rds_iw_conn_free,
	.conn_connect		= rds_iw_conn_connect,
	.conn_shutdown		= rds_iw_conn_shutdown,
	.inc_copy_to_user	= rds_iw_inc_copy_to_user,
	.inc_free		= rds_iw_inc_free,
	.cm_initiate_connect	= rds_iw_cm_initiate_connect,
	.cm_handle_connect	= rds_iw_cm_handle_connect,
	.cm_connect_complete	= rds_iw_cm_connect_complete,
	.stats_info_copy	= rds_iw_stats_info_copy,
	.exit			= rds_iw_exit,
	.get_mr			= rds_iw_get_mr,
	.sync_mr		= rds_iw_sync_mr,
	.free_mr		= rds_iw_free_mr,
	.flush_mrs		= rds_iw_flush_mrs,
	.t_owner		= THIS_MODULE,
	.t_name			= "iwarp",
	.t_type			= RDS_TRANS_IWARP,
	.t_prefer_loopback	= 1,
};

int rds_iw_init(void)
{
	int ret;

	INIT_LIST_HEAD(&rds_iw_devices);

	ret = ib_register_client(&rds_iw_client);
	if (ret)
		goto out;

	ret = rds_iw_sysctl_init();
	if (ret)
		goto out_ibreg;

	ret = rds_iw_recv_init();
	if (ret)
		goto out_sysctl;

	ret = rds_trans_register(&rds_iw_transport);
	if (ret)
		goto out_recv;

	rds_info_register_func(RDS_INFO_IWARP_CONNECTIONS, rds_iw_ic_info);

	goto out;

out_recv:
	rds_iw_recv_exit();
out_sysctl:
	rds_iw_sysctl_exit();
out_ibreg:
	ib_unregister_client(&rds_iw_client);
out:
	return ret;
}

MODULE_LICENSE("GPL");


text:
package com.platypii.baseline.audible.modes;

import com.platypii.baseline.Services;
import com.platypii.baseline.audible.AudibleMode;
import com.platypii.baseline.audible.AudibleSample;
import com.platypii.baseline.util.Convert;

import androidx.annotation.NonNull;

public class GlideRatioMode extends AudibleMode {

    // Have we spoken "stationary" yet?
    private boolean stationary = false;

    public GlideRatioMode() {
        super("glide_ratio", "Glide Ratio", "glide ratio", 0, 4, 1);
    }

    @Override
    public @NonNull
    AudibleSample currentSample(int precision) {
        final double glideRatio = Services.location.glideRatio();
        String glideRatioString = Convert.glide(Services.location.groundSpeed(), Services.alti.climb, precision, false);
        if (glideRatioString.equals(Convert.GLIDE_STATIONARY)) {
            if (stationary) {
                // Only say stationary once
                glideRatioString = "";
            }
            stationary = true;
        } else {
            stationary = false;
        }
        return new AudibleSample(glideRatio, glideRatioString);
    }

    @Override
    public float units() {
        return 1;
    }

    @NonNull
    @Override
    public String renderDisplay(double output, int precision) {
        return Convert.glide(output, precision, true);
    }
}


text:
#ifndef __LINUX_OF_DMA_H
#define __LINUX_OF_DMA_H

#include <linux/of.h>
#include <linux/dmaengine.h>

struct device_node;

struct of_dma {
	struct list_head	of_dma_controllers;
	struct device_node	*of_node;
	struct dma_chan		*(*of_dma_xlate)
				(struct of_phandle_args *, struct of_dma *);
	void			*(*of_dma_route_allocate)
				(struct of_phandle_args *, struct of_dma *);
	struct dma_router	*dma_router;
	void			*of_dma_data;
};

struct of_dma_filter_info {
	dma_cap_mask_t	dma_cap;
	dma_filter_fn	filter_fn;
};

#ifdef CONFIG_OF
extern int of_dma_controller_register(struct device_node *np,
		struct dma_chan *(*of_dma_xlate)
		(struct of_phandle_args *, struct of_dma *),
		void *data);
extern void of_dma_controller_free(struct device_node *np);

extern int of_dma_router_register(struct device_node *np,
		void *(*of_dma_route_allocate)
		(struct of_phandle_args *, struct of_dma *),
		struct dma_router *dma_router);
#define of_dma_router_free of_dma_controller_free

extern struct dma_chan *of_dma_request_slave_channel(struct device_node *np,
						     const char *name);
extern struct dma_chan *of_dma_simple_xlate(struct of_phandle_args *dma_spec,
		struct of_dma *ofdma);
extern struct dma_chan *of_dma_xlate_by_chan_id(struct of_phandle_args *dma_spec,
		struct of_dma *ofdma);

#else
static inline int of_dma_controller_register(struct device_node *np,
		struct dma_chan *(*of_dma_xlate)
		(struct of_phandle_args *, struct of_dma *),
		void *data)
{
	return -ENODEV;
}

static inline void of_dma_controller_free(struct device_node *np)
{
}

static inline int of_dma_router_register(struct device_node *np,
		void *(*of_dma_route_allocate)
		(struct of_phandle_args *, struct of_dma *),
		struct dma_router *dma_router)
{
	return -ENODEV;
}

#define of_dma_router_free of_dma_controller_free

static inline struct dma_chan *of_dma_request_slave_channel(struct device_node *np,
						     const char *name)
{
	return NULL;
}

static inline struct dma_chan *of_dma_simple_xlate(struct of_phandle_args *dma_spec,
		struct of_dma *ofdma)
{
	return NULL;
}

#define of_dma_xlate_by_chan_id NULL

#endif

#endif /* __LINUX_OF_DMA_H */