text:
package jenkins.plugins.iojs.tools;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

import hudson.Extension;
import hudson.FilePath;
import hudson.Functions;
import hudson.Util;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.os.PosixAPI;
import jenkins.plugins.tools.Installables;
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
import hudson.tools.DownloadFromUrlInstaller;
import hudson.tools.ToolInstallation;
import hudson.util.ArgumentListBuilder;
import hudson.util.jna.GNUCLibrary;

import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.kohsuke.stapler.DataBoundConstructor;

import javax.annotation.Nullable;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import static jenkins.plugins.iojs.tools.IojsInstaller.Preference.*;

/**
 * Install io.js from iojs.org
 */
public class IojsInstaller extends DownloadFromUrlInstaller {

    public static final String NPM_PACKAGES_RECORD_FILENAME = ".npmPackages";
    private final String npmPackages;
    private final Long npmPackagesRefreshHours;

    @DataBoundConstructor
    public IojsInstaller(String id, String npmPackages, long npmPackagesRefreshHours)    {
        super(id);
        this.npmPackages = npmPackages;
        this.npmPackagesRefreshHours = npmPackagesRefreshHours;
    }

    public static FilePath binFolderOf(IojsInstallation installation, Node node) {
        FilePath expected = _preferredLocation(installation, node);
        try {
			return Platform.of(node) == Platform.WINDOWS ? expected : expected.child("bin/");
		} catch (Exception e) {
			return expected.child("bin/");
		}
    }

    /**
     * COPY PASTER ToolInstaller.preferredLocation() in order to make it static...
     * Weird
     *
     * Convenience method to find a location to install a tool.
     * @param tool the tool being installed
     * @param node the computer on which to install the tool
     * @return {@link ToolInstallation#getHome} if specified, else a path within the local
     *         Jenkins work area named according to {@link ToolInstallation#getName}
     * @since 1.310
     */
    protected static FilePath _preferredLocation(ToolInstallation tool, Node node) {
        if (node == null) {
            throw new IllegalArgumentException("must pass non-null node");
        }
        String home = Util.fixEmptyAndTrim(tool.getHome());
        if (home == null) {
            home = sanitize(tool.getDescriptor().getId()) + File.separatorChar + sanitize(tool.getName());
        }
        FilePath root = node.getRootPath();
        if (root == null) {
            throw new IllegalArgumentException("Node " + node.getDisplayName() + " seems to be offline");
        }
        return root.child("tools").child(home);
    }

    private static String sanitize(String s) {
        return s != null ? s.replaceAll("[^A-Za-z0-9_.-]+", "_") : null;
    }

    // Overriden performInstallation() in order to provide a custom
    // url (installable.url should be platform+cpu dependant)
    // + pullUp directory impl should differ from DownloadFromUrlInstaller
    // implementation
    @Override
    public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException {
        FilePath expected = preferredLocation(tool, node);

        Installable inst = getInstallable();
        if(inst==null) {
            log.getLogger().println("Invalid tool ID "+id);
            return expected;
        }

        // Cloning the installable since we're going to update its url (not cloning it wouldn't be threadsafe)
        inst = Installables.clone(inst);

        InstallerPathResolver installerPathResolver = InstallerPathResolver.Factory.findResolverFor(inst);
        String relativeDownloadPath = createDownloadUrl(installerPathResolver, inst, node, log);
        inst.url += relativeDownloadPath;

        boolean skipIojsInstallation = isUpToDate(expected, inst);
        if(!skipIojsInstallation) {
            if(expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) {
                expected.child(".timestamp").delete(); // we don't use the timestamp
                String archiveIntermediateDirectoryName = installerPathResolver.extractArchiveIntermediateDirectoryName(relativeDownloadPath);
                this.pullUpDirectory(expected, archiveIntermediateDirectoryName);

                // leave a record for the next up-to-date check
                expected.child(".installedFrom").write(inst.url,"UTF-8");
                expected.act(new ChmodRecAPlusX());
            }
        }

        // Installing npm packages if needed
        if(this.npmPackages != null && !"".equals(this.npmPackages)){
            boolean skipNpmPackageInstallation = areNpmPackagesUpToDate(expected, this.npmPackages, this.npmPackagesRefreshHours);
            if(!skipNpmPackageInstallation){
                expected.child(NPM_PACKAGES_RECORD_FILENAME).delete();
                ArgumentListBuilder npmScriptArgs = new ArgumentListBuilder();

                FilePath npmExe = expected.child("bin/npm");
                npmScriptArgs.add(npmExe);
                npmScriptArgs.add("install");
                npmScriptArgs.add("-g");
                for(String packageName : this.npmPackages.split("\\s")){
                    npmScriptArgs.add(packageName);
                }

                hudson.Launcher launcher = node.createLauncher(log);

                int returnCode = launcher.launch().cmds(npmScriptArgs).stdout(log).join();

                if(returnCode == 0){
                    // leave a record for the next up-to-date check
                    expected.child(NPM_PACKAGES_RECORD_FILENAME).write(this.npmPackages,"UTF-8");
                    expected.child(NPM_PACKAGES_RECORD_FILENAME).act(new ChmodRecAPlusX());
                }
            }
        }

        return expected;
    }

    private static boolean areNpmPackagesUpToDate(FilePath expected, String npmPackages, long npmPackagesRefreshHours) throws IOException, InterruptedException {
        FilePath marker = expected.child(NPM_PACKAGES_RECORD_FILENAME);
        return marker.exists() && marker.readToString().equals(npmPackages) && System.currentTimeMillis() < marker.lastModified()+ TimeUnit.HOURS.toMillis(npmPackagesRefreshHours);
    }

    private void pullUpDirectory(final FilePath rootNodeHome, final String archiveIntermediateDirectoryName) throws IOException, InterruptedException {
        // Deleting every sub files/directory other than archiveIntermediateDirectoryName
        List<FilePath> subfiles = rootNodeHome.list();
        for(FilePath subfile : subfiles){
            if(!archiveIntermediateDirectoryName.equals(subfile.getName())){
                subfile.deleteRecursive();
            }
        }

        // Moving up files in archiveIntermediateDirectoryName
        FilePath archiveIntermediateDirectoryNameFP = rootNodeHome.child(archiveIntermediateDirectoryName);
        archiveIntermediateDirectoryNameFP.moveAllChildrenTo(rootNodeHome);
    }

    private String createDownloadUrl(InstallerPathResolver installerPathResolver, Installable installable, Node node, TaskListener log) throws InterruptedException, IOException {
        try {
            Platform platform = Platform.of(node);
            CPU cpu = CPU.of(node);
            return installerPathResolver.resolvePathFor(installable.id, platform, cpu);
        } catch (DetectionFailedException e) {
            throw new IOException(e);
        }
    }

    /**
     * Weird : copy/pasted from ZipExtractionInstaller since this is a package-protected class
     *
     * Sets execute permission on all files, since unzip etc. might not do this.
     * Hackish, is there a better way?
     */
    static class ChmodRecAPlusX implements FilePath.FileCallable<Void> {
        private static final long serialVersionUID = 1L;
        public Void invoke(File d, VirtualChannel channel) throws IOException {
            if(!Functions.isWindows())
                process(d);
            return null;
        }
        @IgnoreJRERequirement
        private void process(File f) {
            if (f.isFile()) {
                if(Functions.isMustangOrAbove())
                    f.setExecutable(true, false);
                else {
                    try {
                        GNUCLibrary.LIBC.chmod(f.getAbsolutePath(),0755);
                    } catch (LinkageError e) {
                        // if JNA is unavailable, fall back.
                        // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
                        PosixAPI.get().chmod(f.getAbsolutePath(),0755);
                    }
                }
            } else {
                File[] kids = f.listFiles();
                if (kids != null) {
                    for (File kid : kids) {
                        process(kid);
                    }
                }
            }
        }
    }

    public String getNpmPackages() {
        return npmPackages;
    }

    public Long getNpmPackagesRefreshHours() {
        return npmPackagesRefreshHours;
    }

    public enum Preference {
        PRIMARY, SECONDARY, UNACCEPTABLE
    }

    /**
     * Supported platform.
     */
    public enum Platform {
        LINUX("iojs"), WINDOWS("iojs.exe"), MAC("iojs");

        /**
         * Choose the file name suitable for the downloaded Node bundle.
         */
        public final String bundleFileName;

        Platform(String bundleFileName) {
            this.bundleFileName = bundleFileName;
        }

        public boolean is(String line) {
            return line.contains(name());
        }

        /**
         * Determines the platform of the given node.
         */
        public static Platform of(Node n) throws IOException,InterruptedException,DetectionFailedException {
            return n.getChannel().call(new GetCurrentPlatform());
        }

        public static Platform current() throws DetectionFailedException {
            String arch = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
            if(arch.contains("linux"))  return LINUX;
            if(arch.contains("windows"))   return WINDOWS;
            if(arch.contains("mac"))   return MAC;
            throw new DetectionFailedException("Unknown CPU name: "+arch);
        }

        static class GetCurrentPlatform implements Callable<Platform,DetectionFailedException> {
            private static final long serialVersionUID = 1L;
            public Platform call() throws DetectionFailedException {
                return current();
            }
        }

    }

    /**
     * CPU type.
     */
    public enum CPU {
        i386, amd64;

        /**
         * In JDK5u3, I see platform like "Linux AMD64", while JDK6u3 refers to "Linux x64", so
         * just use "64" for locating bits.
         */
        public Preference accept(String line) {
            switch (this) {
            // 64bit Solaris, Linux, and Windows can all run 32bit executable, so fall back to 32bit if 64bit bundle is not found
            case amd64:
                if(line.contains("SPARC") || line.contains("IA64"))  return UNACCEPTABLE;
                if(line.contains("64"))     return PRIMARY;
                return SECONDARY;
            case i386:
                if(line.contains("64") || line.contains("SPARC") || line.contains("IA64"))     return UNACCEPTABLE;
                return PRIMARY;
            }
            return UNACCEPTABLE;
        }

        /**
         * Determines the CPU of the given node.
         */
        public static CPU of(Node n) throws IOException,InterruptedException, DetectionFailedException {
            return n.getChannel().call(new GetCurrentCPU());
        }

        /**
         * Determines the CPU of the current JVM.
         *
         * http://lopica.sourceforge.net/os.html was useful in writing this code.
         */
        public static CPU current() throws DetectionFailedException {
            String arch = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH);
            if(arch.contains("amd64") || arch.contains("86_64"))    return amd64;
            if(arch.contains("86"))    return i386;
            throw new DetectionFailedException("Unknown CPU architecture: "+arch);
        }

        static class GetCurrentCPU implements Callable<CPU,DetectionFailedException> {
            private static final long serialVersionUID = 1L;
            public CPU call() throws DetectionFailedException {
                return current();
            }
        }
    }

    /**
     * Indicates the failure to detect the OS or CPU.
     */
    private static final class DetectionFailedException extends Exception {
        private DetectionFailedException(String message) {
            super(message);
        }
    }

    @Extension
    public static final class DescriptorImpl extends DownloadFromUrlInstaller.DescriptorImpl<IojsInstaller> {
        public String getDisplayName() {
            return Messages.IojsInstaller_DescriptorImpl_displayName();
        }

        @Override
        public List<? extends Installable> getInstallables() throws IOException {
            // Filtering non blacklisted installables + sorting installables by version number
            Collection<? extends Installable> filteredInstallables = Collections2.filter(super.getInstallables(),
                    new Predicate<Installable>() {
                        public boolean apply(@Nullable Installable input) {
                            return !false;
                        }
                    });
            TreeSet<Installable> sortedInstallables = new TreeSet<Installable>(new Comparator<Installable>(){
                public int compare(Installable o1, Installable o2) {
                    return IojsVersion.compare(o1.id, o2.id)*-1;
                }
            });
            sortedInstallables.addAll(filteredInstallables);
            return new ArrayList<Installable>(sortedInstallables);
        }

        @Override
        public String getId() {
            return "jenkins.plugins.iojs.tools.IojsInstaller";
        }

        @Override
        public boolean isApplicable(Class<? extends ToolInstallation> toolType) {
            return toolType == IojsInstallation.class;
        }
    }

    private static final Logger LOGGER = Logger.getLogger(IojsInstaller.class.getName());
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!-- Parent -->
    <parent>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-parent</artifactId>
        <version>3.1.3-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <!-- Model Version -->
    <modelVersion>4.0.0</modelVersion>

    <!-- Artifact Configuration -->
    <artifactId>shrinkwrap-resolver-api</artifactId>
    <name>ShrinkWrap Resolver API</name>
    <description>API to Resolve Dependencies from a Generic Backend</description>

    <!-- Dependencies -->
    <dependencies>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

redpajama_set_name: RedPajamaGithub


text:
"""Runs an optimal power flow.
"""

from sys import stdout, stderr

from os.path import dirname, join

from pypower.ppoption import ppoption
from pypower.opf import opf
from pypower.printpf import printpf
from pypower.savecase import savecase

def runopf(casedata=None, ppopt=None, fname='', solvedcase=''):
    """Runs an optimal power flow.

    @see: L{rundcopf}, L{runuopf}

    @author: Ray Zimmerman (PSERC Cornell)
    """
    ## default arguments
    if casedata is None:
        casedata = join(dirname(__file__), 'case9')
    ppopt = ppoption(ppopt)

    ##-----  run the optimal power flow  -----
    r = opf(casedata, ppopt)

    ##-----  output results  -----
    if fname:
        fd = None
        try:
            fd = open(fname, "a")
        except IOError as detail:
            stderr.write("Error opening %s: %s.\n" % (fname, detail))
        finally:
            if fd is not None:
                printpf(r, fd, ppopt)
                fd.close()

    else:
        printpf(r, stdout, ppopt)

    ## save solved case
    if solvedcase:
        savecase(solvedcase, r)

    return r

if __name__ == '__main__':
    ppopt = ppoption(OPF_ALG=580)
    runopf(None, ppopt)


text:
def get_host_role(host):
    if hasattr(host, 'role'):
        return host.role
    else:
        return host.node_group.name

def inject_remote(param_name):
    def handle(func):
        def call(self, *args, **kwargs):
            with self.instance.remote() as r:
                newkwargs = kwargs.copy()
                newkwargs[param_name] = r
                return func(self, *args, **newkwargs)

        return call
    return handle


text:
using System.Diagnostics;
using System.Threading.Tasks;
using Nest.Queryify.Abstractions.Queries;
using Nest.Queryify.Tests.Queries.Fixtures;
using Xunit;

namespace Nest.Queryify.Tests.Queries.Specs
{
    [DebuggerStepThrough]
    public abstract class QuerySpec<TResponse> : IClassFixture<ElasticClientQueryObjectTestFixture>
        where TResponse: class
    {
        protected ElasticClientQueryObjectTestFixture Fixture { get; }

        protected QuerySpec(ElasticClientQueryObjectTestFixture fixture)
        {
            Fixture = fixture;
        }

        [Fact]
        public virtual void ShouldExecute()
        {
            var query = Query();
            query.Execute(Fixture.Client, Fixture.DefaultIndex);
            AssertExpectations();
        }

        [Fact]
        public virtual async Task ShouldExecuteAsync()
        {
            var query = Query();
            await query.ExecuteAsync(Fixture.Client, Fixture.DefaultIndex);
            AssertExpectations();
        }

        protected virtual void AssertExpectations()
        {

        }

        protected abstract ElasticClientQueryObject<TResponse> Query();

    }
}


text:
@interface KSCrashReportSinkQuincy ()

@property(nonatomic, readwrite, retain) NSString* userIDKey;
@property(nonatomic, readwrite, retain) NSString* contactEmailKey;
@property(nonatomic, readwrite, retain) NSArray* crashDescriptionKeys;
@property(nonatomic,readwrite,retain) NSURL* url;
@property(nonatomic,readwrite,retain) KSReachableOperationKSCrash* reachableOperation;

@end

@implementation KSCrashReportSinkQuincy

@synthesize url = _url;
@synthesize userIDKey = _userIDKey;
@synthesize contactEmailKey = _contactEmailKey;
@synthesize crashDescriptionKeys = _crashDescriptionKeys;
@synthesize reachableOperation = _reachableOperation;
@synthesize waitUntilReachable = _waitUntilReachable;

+ (KSCrashReportSinkQuincy*) sinkWithURL:(NSURL*) url
                               userIDKey:(NSString*) userIDKey
                         contactEmailKey:(NSString*) contactEmailKey
                    crashDescriptionKeys:(NSArray*) crashDescriptionKeys
{
    return as_autorelease([[self alloc] initWithURL:url
                                          userIDKey:userIDKey
                                    contactEmailKey:contactEmailKey
                               crashDescriptionKeys:crashDescriptionKeys]);
}

- (id) initWithURL:(NSURL*) url
         userIDKey:(NSString*) userIDKey
   contactEmailKey:(NSString*) contactEmailKey
crashDescriptionKeys:(NSArray*) crashDescriptionKeys
{
    if((self = [super init]))
    {
        self.url = url;
        self.userIDKey = userIDKey;
        self.contactEmailKey = contactEmailKey;
        self.crashDescriptionKeys = crashDescriptionKeys;
        self.waitUntilReachable = YES;
    }
    return self;
}

- (void) dealloc
{
    as_release(_reachableOperation);
    as_release(_url);
    as_release(_userIDKey);
    as_release(_contactEmailKey);
    as_release(_crashDescriptionKeys);
    as_superdealloc();
}

- (id <KSCrashReportFilter>) defaultCrashReportFilterSet
{
    return [KSCrashReportFilterPipeline filterWithFilters:
            [KSCrashReportFilterCombine filterWithFiltersAndKeys:
             [KSCrashReportFilterPassthrough filter],
             kFilterKeyStandard,
             [KSCrashReportFilterAppleFmt filterWithReportStyle:KSAppleReportStyleSymbolicatedSideBySide],
             kFilterKeyApple,
             nil],
            self,
            nil];
}

- (NSString*) cdataEscaped:(NSString*) string
{
    return [string stringByReplacingOccurrencesOfString:@"]]>"
                                             withString:@"]]" @"]]><![CDATA[" @">"
                                                options:NSLiteralSearch
                                                  range:NSMakeRange(0,string.length)];
}

- (NSString*) blankForNil:(NSString*) string
{
    return string == nil ? @"" : string;
}

- (NSString*) descriptionForReport:(NSDictionary*) report keys:(NSArray*) keys
{
    NSMutableString* str = [NSMutableString string];
    NSUInteger count = [keys count];
    for(NSUInteger i = 0; i < count; i++)
    {
        NSString* stringValue = nil;
        NSString* key = [keys objectAtIndex:i];
        id value = [report objectForKeyPath:key];
        if([value isKindOfClass:[NSString class]])
        {
            stringValue = value;
        }
        else if([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]])
        {
            NSError* error = nil;
            NSData* encoded = [KSJSONCodec encode:value options:KSJSONEncodeOptionSorted | KSJSONEncodeOptionPretty error:&error];
            if(error != nil)
            {
                KSLOG_ERROR(@"Could not encode report section %@: %@", key, error);
                continue;
            }
            stringValue = as_autorelease([[NSString alloc] initWithData:encoded encoding:NSUTF8StringEncoding]);
        }
        else if(value == nil)
        {
            KSLOG_WARN(@"Report section %@ not found", key);
        }
        else
        {
            KSLOG_ERROR(@"Could not encode report section %@: Don't know how to encode class %@", key, [value class]);
        }
        if(stringValue != nil)
        {
            if(i > 0)
            {
                [str appendString:@"\n\n"];
            }
            [str appendFormat:@"%@:\n", key];
            [str appendString:stringValue];
        }
    }
    return str;
}

- (NSString*) toQuincyFormat:(NSDictionary*) reportTuple
{
    NSDictionary* report = [reportTuple objectForKey:kFilterKeyStandard];
    NSString* appleReport = [reportTuple objectForKey:kFilterKeyApple];
    NSDictionary* systemDict = [report objectForKey:@KSCrashField_System];
    NSString* userID = self.userIDKey == nil ? nil : [self blankForNil:[report objectForKeyPath:self.userIDKey]];
    NSString* contactEmail = self.contactEmailKey == nil ? nil : [self blankForNil:[report objectForKeyPath:self.contactEmailKey]];
    NSString* crashReportDescription = [self.crashDescriptionKeys count] == 0 ? nil : [self descriptionForReport:report keys:self.crashDescriptionKeys];

    NSString* result = [NSString stringWithFormat:
                        @"\n    <crash>\n"
                        @"        <applicationname>%@</applicationname>\n"
                        @"        <bundleidentifier>%@</bundleidentifier>\n"
                        @"        <systemversion>%@</systemversion>\n"
                        @"        <platform>%@</platform>\n"
                        @"        <senderversion>%@</senderversion>\n"
                        @"        <version>%@</version>\n"
                        @"        <log><![CDATA[%@]]></log>\n"
                        @"        <userid>%@</userid>\n"
                        @"        <contact>%@</contact>\n"
                        @"        <description><![CDATA[%@]]></description>\n"
                        @"    </crash>",
                        [systemDict objectForKey:@"CFBundleExecutable"],
                        [systemDict objectForKey:@"CFBundleIdentifier"],
                        [systemDict objectForKey:@"system_version"],
                        [systemDict objectForKey:@"machine"],
                        [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],
                        [systemDict objectForKey:@"CFBundleVersion"],
                        [self cdataEscaped:appleReport],
                        userID,
                        contactEmail,
                        [self cdataEscaped:crashReportDescription]];
    return result;
}

- (NSData*) toQuincyBody:(NSArray*) reports
{
    NSMutableString* xmlString = [NSMutableString stringWithString:@"<crashes>"];

    for(NSDictionary* report in reports)
    {
        NSString* reportString = [self toQuincyFormat:report];
        [xmlString appendString:reportString];
    }
    [xmlString appendString:@"</crashes>"];

    return [xmlString dataUsingEncoding:NSUTF8StringEncoding];
}

- (void) filterReports:(NSArray*) reports
              bodyName:(NSString*) bodyName
       bodyContentType:(NSString*) bodyContentType
          bodyFilename:(NSString*) bodyFilename
          onCompletion:(KSCrashReportFilterCompletion) onCompletion
{
    if(self.url == nil)
    {
        if(onCompletion != nil)
        {
            onCompletion(reports, NO, [NSError errorWithDomain:[[self class] description]
                                                          code:0
                                                   description:@"url was nil"]);
        }
        return;
    }

    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:self.url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:15];

    KSHTTPMultipartPostBody* body = [KSHTTPMultipartPostBody body];

    [body appendData:[self toQuincyBody:reports]
                name:bodyName
         contentType:bodyContentType
            filename:bodyFilename];

    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    request.timeoutInterval = 15;
    request.HTTPMethod = @"POST";
    request.HTTPBody = [body data];
    [request setValue:@"Quincy/iOS" forHTTPHeaderField:@"User-Agent"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [request setValue:body.contentType forHTTPHeaderField:@"Content-type"];

    dispatch_block_t sendOperation = ^
    {
        KSLOG_TRACE(@"Sending request to %@", request.URL);
        [[KSHTTPRequestSender sender] sendRequest:request
                                        onSuccess:^(__unused NSHTTPURLResponse* response,
                                                    __unused NSData* data)
         {
             KSLOG_DEBUG(@"Post successful");
             kscrash_i_callCompletion(onCompletion, reports, YES, nil);
         } onFailure:^(NSHTTPURLResponse* response, NSData* data)
         {
             NSString* text = as_autorelease([[NSString alloc] initWithData:data
                                                                   encoding:NSUTF8StringEncoding]);
             KSLOG_DEBUG(@"Post failed. Code %d", response.statusCode);
             KSLOG_TRACE(@"Response text:\n%@", text);
             kscrash_i_callCompletion(onCompletion, reports, NO,
                                      [NSError errorWithDomain:[[self class] description]
                                                          code:response.statusCode
                                                   description:text]);
         } onError:^(NSError* error)
         {
             KSLOG_DEBUG(@"Posting error: %@", error);
             kscrash_i_callCompletion(onCompletion, reports, NO, error);
         }];
    };

    if(self.waitUntilReachable)
    {
        KSLOG_TRACE(@"Starting reachable operation to host %@", [self.url host]);
        self.reachableOperation = [KSReachableOperationKSCrash operationWithHost:[self.url host]
                                                                       allowWWAN:YES
                                                                           block:sendOperation];
    }
    else
    {
        sendOperation();
    }
}

- (void) filterReports:(NSArray*) reports
          onCompletion:(KSCrashReportFilterCompletion) onCompletion
{
    [self filterReports:reports
               bodyName:@"xmlstring"
        bodyContentType:nil
           bodyFilename:nil
           onCompletion:onCompletion];
}

@end

@interface KSCrashReportSinkHockey ()

@property(nonatomic,readwrite,retain) NSString* appIdentifier;

@end

@implementation KSCrashReportSinkHockey

@synthesize appIdentifier = _appIdentifier;

+ (KSCrashReportSinkHockey*) sinkWithAppIdentifier:(NSString*) appIdentifier
                                         userIDKey:(NSString*) userIDKey
                                   contactEmailKey:(NSString*) contactEmailKey
                              crashDescriptionKeys:(NSArray*) crashDescriptionKeys
{
    return as_autorelease([[self alloc] initWithAppIdentifier:appIdentifier
                                                    userIDKey:userIDKey
                                              contactEmailKey:contactEmailKey
                                         crashDescriptionKeys:crashDescriptionKeys]);
}

- (id) initWithAppIdentifier:(NSString*) appIdentifier
                   userIDKey:(NSString*) userIDKey
             contactEmailKey:(NSString*) contactEmailKey
        crashDescriptionKeys:(NSArray*) crashDescriptionKeys
{
    if((self = [super initWithURL:[self urlWithAppIdentifier:appIdentifier]
                        userIDKey:userIDKey
                  contactEmailKey:contactEmailKey
             crashDescriptionKeys:crashDescriptionKeys]))
    {
        self.appIdentifier = appIdentifier;
    }
    return self;
}

- (void) dealloc
{
    as_release(_appIdentifier);
    as_superdealloc();
}

- (void) filterReports:(NSArray*) reports
          onCompletion:(KSCrashReportFilterCompletion) onCompletion
{
    if(self.appIdentifier == nil)
    {
        if(onCompletion != nil)
        {
            onCompletion(reports, NO, [NSError errorWithDomain:[[self class] description]
                                                          code:0
                                                   description:@"appIdentifier was nil"]);
        }
        return;
    }

    [self filterReports:reports
               bodyName:@"xml"
        bodyContentType:@"text/xml"
           bodyFilename:@"crash.xml"
           onCompletion:onCompletion];
}

- (NSURL*) urlWithAppIdentifier:(NSString*) appIdentifier
{
    NSString* urlString = [NSString stringWithFormat:@"https://rink.hockeyapp.net/api/2/apps/%@/crashes",
                           [self urlEscaped:appIdentifier]];
    return [NSURL URLWithString:urlString];
}

- (NSString*) urlEscaped:(NSString*) string
{
    return [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end


text:
#include "RoboticArm.h"
#include "TemplateAStar.h"
#include "GLUtil.h"
#include <string.h>

tRotation armRotations::GetRotation(int which) const
{
	switch ((rotations>>(2*which))&0x3)
	{
		case 1: return kRotateCCW;
		case 0: return kNoRotation;
		case 2: return kRotateCW;
	}
	return kNoRotation;
}

void armRotations::SetRotation(int which, tRotation dir)
{
	int value = 0;
	switch (dir)
	{
		case kRotateCW: value = 2; break;
		case kRotateCCW: value = 1; break;
		case kNoRotation: value = 0; break;
	}
	rotations = rotations&((~0x3)<<(2*which))|(value<<2*which);
}

int armAngles::GetAngle(int which) const
{
	return (angles>>(10*which))&0x3FF;
}

void armAngles::SetAngle(int which, int value)
{
	value %= 1024; if( value < 0 ) { value += 1024; }
	value -= value & 1;
	uint64_t mask = 1023ll<<(10*which);
	uint64_t val = ((uint64_t)value)<<(10*which);
	angles = (angles&~mask)|val;
}

int armAngles::GetNumArms() const
{
	return angles>>60;
}

void armAngles::SetNumArms(int count)
{
	uint64_t mask = 0xFFFFFFFFFFFFFFFull;
	uint64_t newCnt = count;
	newCnt = newCnt << 60;
	assert(count <= 6);
	angles = newCnt|(angles&mask);
}

void armAngles::SetGoal(double x, double y)
{
	uint64_t fixedDecx, fixedFracx;
	uint64_t fixedDecy, fixedFracy;
	x += 512; // avoid unsigned issues...
	y += 512;
	fixedDecx = ((uint32_t)x)&0x3FF; // 10 bits
	fixedFracx = (int)((x-(double)fixedDecx)*1024.0*1024.0); // 20 bits
	fixedDecy = ((uint32_t)y)&0x3FF; // 10 bits
	fixedFracy = (int)((y-(double)fixedDecy)*1024.0*1024.0); // 20 bits
	angles = (0xFll<<60)|(fixedDecx<<50)|(fixedFracx<<30)|(fixedDecy<<20)|fixedFracy;
}

void armAngles::GetGoal(double &x, double &y) const
{
	assert(IsGoalState());

	x = ((angles>>50)&0x3FF) + (double)((angles>>30)&0xFFFFF)/(1024.0*1024.0);
	y = ((angles>>20)&0x3FF) + (double)((angles)&0xFFFFF)/(1024.0*1024.0);
	x-= 512;
	y-= 512;
}

bool armAngles::IsGoalState() const
{
	return ((angles>>60) == 0xF);
}

RoboticArm::RoboticArm(int dof, double armlength, double fTolerance)
:DOF(dof), armLength(armlength), tolerance(fTolerance)
{
	BuildSinCosTables();
	ce = new ConfigEnvironment();
}

RoboticArm::~RoboticArm()
{
	delete ce;
}

void RoboticArm::GetTipPosition( armAngles &s, double &x, double &y )
{
	std::vector<line2d> armSegs;
	GenerateLineSegments( s, armSegs );
	recVec a = armSegs.back().end;
	x = a.x;
	y = a.y;
}

int RoboticArm::TipPositionIndex(armAngles &s,
								 const double minX, const double minY,
								 const double width )
{
	int idx;
	double x, y;
	GetTipPosition(s, x, y);
	// if we had a guarantee that width was a multiple of
	// tolerance, we could do a bunch of simplification
	idx = (int)floor( ( y - minY ) / GetTolerance() );
	idx *= (int)floor( width / GetTolerance() );
	idx += (int)floor( ( x - minX ) / GetTolerance() );

	return idx;
}

void RoboticArm::GetSuccessors(const armAngles &nodeID, std::vector<armAngles> &neighbors) const
{
	neighbors.resize(0);
	for (int x = 0; x < nodeID.GetNumArms(); x++)
	{
		armAngles s = nodeID;
		armRotations a;
		a.SetRotation(x, kRotateCW);
		ApplyAction(s, a);

		if (LegalState(s))
			neighbors.push_back(s);

		s = nodeID;
		a.SetRotation(x, kRotateCCW);
		ApplyAction(s, a);

		if (LegalState(s))
			neighbors.push_back(s);
	}
}

void RoboticArm::GetActions(const armAngles &nodeID, std::vector<armRotations> &actions) const
{
	actions.resize(0);
	for (int x = 0; x < nodeID.GetNumArms(); x++)
	{
		armAngles s = nodeID;
		armRotations a;
		a.SetRotation(x, kRotateCW);
		ApplyAction(s, a);

		if (LegalState(s))
			actions.push_back(a);

		s = nodeID;
		a.SetRotation(x, kRotateCCW);
		ApplyAction(s, a);

		if (LegalState(s))
			actions.push_back(a);
	}

//	actions.resize(0);
//	for (int x = 0; x < nodeID.GetNumArms(); x++)
//	{
//		armAngles a(nodeID);
//		a.SetAngle(x, nodeID.GetAngle(x)+2);
//		if (LegalState(a))
//		{
//			armRotations rot;
//			rot.SetRotation(x, kRotateCW);
//			actions.push_back(rot);
//		}
//		a.SetAngle(x, nodeID.GetAngle(x)-2);
//		if (LegalState(a))
//		{
//			armRotations rot;
//			rot.SetRotation(x, kRotateCCW);
//			actions.push_back(rot);
//		}
//	}
}

armRotations RoboticArm::GetAction(const armAngles &s1, const armAngles &s2) const
{
	armRotations ar;
	for (int x = 0; x < s1.GetNumArms(); x++)
	{
		ar.SetRotation(x, (tRotation)(s2.GetAngle(x)-s1.GetAngle(x)));
	}
	return ar;
}

void RoboticArm::ApplyAction(armAngles &s, armRotations dir) const
{
	armAngles newState = s;
	for (int x = 0; x < newState.GetNumArms(); x++) {
		newState.SetAngle(x, newState.GetAngle(x)+2*dir.GetRotation(x));
	}
	//if (LegalState(newState))
	s = newState;
}

bool RoboticArm::InvertAction(armRotations &a) const
{
	for (int x = 0; x < 6; x++)
		a.SetRotation(x, (tRotation)(-(int)a.GetRotation(x)));
	return true;
}

void RoboticArm::AddObstacle(line2d obs)
{
	obstacles.push_back(obs);
	ce->AddObstacle(obs);
//	printf("Found solution %d moves; length %f, %d nodes expanded\n",
//		   states.size(), ce->GetPathLength(states), astar.GetNodesExpanded());
}

void RoboticArm::PopObstacle()
{
	obstacles.pop_back();
	ce->PopObstacle();
}

armAngles RoboticArm::GetRandomState()
{
	armAngles ar;
	ar.SetNumArms(DOF);
	for (int x = 0; x < DOF; x++)
		ar.SetAngle(x, 2*(random()%512));
	return ar;
}

double RoboticArm::HCost(const armAngles &node1, const armAngles &node2)
{
	double h;
	if (!node1.IsGoalState() && !node2.IsGoalState())
	{
		double val = 0;
		for (int x = 0; x < node1.GetNumArms(); x++)
		{
			double tmp = abs(node1.GetAngle(x) - node2.GetAngle(x));
			val += tmp/2;
		}
		//printf("Default heur: %f\n", val);
		for (unsigned int x = 0; x < heuristics.size(); x++)
			val = max(val, heuristics[x]->HCost(node1, node2));
		return val;
	}

	if (node1.IsGoalState()) return HCost(node2, node1);
	assert(node2.IsGoalState());

	std::vector<line2d> armSegments1;
	GenerateLineSegments(node1, armSegments1);
	recVec a = armSegments1.back().end;
	double x, y;
	node2.GetGoal(x, y);
	double actDistance = sqrt((x-a.x)*(x-a.x)+(y-a.y)*(y-a.y));
	double movementAmount = (node1.GetNumArms()*armLength*sin(TWOPI*4.0/1024.0));

	{
		TemplateAStar<recVec, line2d, ConfigEnvironment> astar;
		recVec g(x, y, 0);
		ce->StoreGoal(g);
		astar.GetPath(ce, a, g, states);
		actDistance = max(actDistance, ce->GetPathLength(states));
	}

	h = actDistance / movementAmount;

	return h;

#if 0
	recVec a, b;
	if (node1.IsGoalState())
		node1.GetGoal(a.x, a.y);
	else {
		GenerateLineSegments(node1, armSegments);
		a = armSegments.back().end;
	}

	if (node2.IsGoalState())
		node2.GetGoal(b.x, b.y);
	else {
		GenerateLineSegments(node2, armSegments);
		b = armSegments.back().end;
	}
	return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
#endif
}

#if 0
double RoboticArm::GCost(const armAngles &node1, const armAngles &node2)
{
	recVec a, b;
	if (node1.IsGoalState())
		node1.GetGoal(a.x, a.y);
	else {
		GenerateLineSegments(node1, armSegments);
		a = armSegments.back().end;
	}

	if (node2.IsGoalState())
		node2.GetGoal(b.x, b.y);
	else {
		GenerateLineSegments(node2, armSegments);
		b = armSegments.back().end;
	}
	return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
#endif

#if 0
double RoboticArm::GCost(const armAngles &node1, const armRotations &act)
{
	armAngles node2;
	GetNextState(node1, act, node2);
	return GCost(node1, node2);
}
#endif

bool RoboticArm::GoalTest(const armAngles &node, const armAngles &goal)
{
	if (!goal.IsGoalState())
	{
		return (node == goal);
	}
	assert(goal.IsGoalState());
	GenerateLineSegments(node, armSegments);

	recVec a;
	a = armSegments.back().end;
	double x, y;
	goal.GetGoal(x, y);
	return x-a.x <= tolerance && a.x-x < tolerance
	  && y-a.y <= tolerance && a.y-y < tolerance;
}

uint64_t RoboticArm::GetStateHash(const armAngles &node) const
{
	// want a perfect hash function
	//return node.angles;
	uint64_t res = 0;
	for (int x = 0; x < node.GetNumArms(); x++)
		res = (uint64_t)(res<<9)|((uint64_t)node.GetAngle(x)/2);
//	assert(res < 512*512*512);
	return res;
}

void RoboticArm::GetStateFromHash(uint64_t hash, armAngles &a) const
{
	for (int x = a.GetNumArms()-1; x >= 0; x--)
	{
		a.SetAngle(x, (hash&0x1FF)*2);
		hash >>= 9;
	}
}

uint64_t RoboticArm::GetActionHash(armRotations act) const
{
	return act.rotations;
}

void RoboticArm::OpenGLDraw() const
{
//	if (window == 1)
//	{
//		ce->OpenGLDraw(1);
//		return;
//	}
	glBegin(GL_QUADS);
	glColor3f(0, 0, 0.1);
	glVertex3f(-1, -1, 0.1);
	glVertex3f(1, -1, 0.1);
	glVertex3f(1, 1, 0.1);
	glVertex3f(-1, 1, 0.1);
	glEnd();

	glColor3f(1, 0, 0);
	for (unsigned int x = 0; x < obstacles.size(); x++)
	{
		DrawLine(obstacles[x]);
	}
}

void RoboticArm::OpenGLDraw(const armAngles &a) const
{
//	if (window == 1)
//	{
//		glColor3f(1, 1, 0);
//		for (unsigned int x = 1; x < states.size(); x++)
//		{
//			DrawLine(line2d(states[x-1], states[x]));
//		}
//		ce->OpenGLDraw(1);
//		return;
//	}

	recVec e;
	if (a.IsGoalState())
	{
		e.z = 0;
		a.GetGoal(e.x, e.y);
	}
	else {
		GenerateLineSegments(a, armSegments);

		for (unsigned int x = 0; x < armSegments.size(); x++)
		{
			glColor3f(1, 1, 1);
			//printf("Drawing line segment %d of %d\n", x, armSegments.size());
			DrawLine(armSegments[x]);
		}
		e = armSegments.back().end;
	}

	glBegin(GL_LINE_LOOP);
	glColor3f(0, 1.0, 0);
	glVertex3f(e.x+tolerance, e.y+tolerance, 0);
	glVertex3f(e.x-tolerance, e.y+tolerance, 0);
	glVertex3f(e.x-tolerance, e.y-tolerance, 0);
	glVertex3f(e.x+tolerance, e.y-tolerance, 0);
	glEnd();

}

void RoboticArm::OpenGLDraw(const armAngles &, const armRotations &) const
{
}

//void RoboticArm::OpenGLDraw(const armAngles &, const armRotations &, GLfloat, GLfloat, GLfloat) const
//{
//}
//
//void RoboticArm::OpenGLDraw(const armAngles &, GLfloat, GLfloat, GLfloat) const
//{
//}

void RoboticArm::DrawLine(line2d l) const
{
	glLineWidth(5);
	glBegin(GL_LINES);
	glVertex3f(l.start.x, l.start.y, 0);
	glVertex3f(l.end.x, l.end.y, 0);
	glEnd();
	glLineWidth(1);
}

void RoboticArm::GetNextState(const armAngles &currents, armRotations dir, armAngles &news) const
{
	news = currents;
	ApplyAction(news, dir);
}

bool RoboticArm::LegalState(armAngles &a) const
{
//	if( legalStateTable != NULL ) {
//		uint64_t idx;
//
//		idx = ArmAnglesIndex( a );
//		if( legalStateTable[ idx >> 3 ]  & ( 1 << ( idx & 7 ) ) ) {
//			return true;
//		}
//		return false;
//	}

	GenerateLineSegments(a, armSegments);
	for (unsigned int x = 0; x < armSegments.size(); x++)
	{
		for (unsigned int y = 0; y < obstacles.size(); y++)
		{
			if (armSegments[x].crosses(obstacles[y]))
				return false;
		}
		for (unsigned int y = x+2; y < armSegments.size(); y++)
			if (armSegments[x].crosses(armSegments[y]))
				return false;

		if ((x > 0) && (a.GetAngle(x) == 0))
			return false;
	}
	return true;
}

bool RoboticArm::LegalArmConfig(armAngles &a) const
{
//	if (m_TableComplete)
//		return legals[a.GetAngle(1)][a.GetAngle(2)];
	GenerateLineSegments(a, armSegments);
	for (unsigned int x = 0; x < armSegments.size(); x++)
	{
		for (unsigned int y = x+2; y < armSegments.size(); y++)
			if (armSegments[x].crosses(armSegments[y]))
				return false;

		if ((x > 0) && (a.GetAngle(x) == 0))
			return false;
	}
	return true;
}

void RoboticArm::GenerateLineSegments(const armAngles &a, std::vector<line2d> &armSegments1) const
{
	armSegments1.resize(0);
	for (int x = 0; x < a.GetNumArms(); x++)
	{
		recVec prev;
		recVec start;
		recVec end;

		//double angle = TWOPI*a.GetAngle(x)/1024.0;
		int angle = a.GetAngle(x);
		if (x == 0)
		{
			start.x = 0;
			start.y = 0;
			start.z = 0;
			prev = start;
			prev.y = -armLength;
		}
		else {
			start = armSegments1.back().end;
			prev = armSegments1.back().start;
		}

		// offset to origin
		prev.x -= start.x;
		prev.y -= start.y;

		end.x = prev.x*GetCos(angle) - prev.y*GetSin(angle) + start.x;
		end.y = prev.x*GetSin(angle) + prev.y*GetCos(angle) + start.y;
		end.z = 0;

		armSegments1.push_back(line2d(start, end));
	}
	assert(armSegments1.size() > 0);
}

double RoboticArm::GetSin(int angle) const
{
	return sinTable[angle];
}

double RoboticArm::GetCos(int angle) const
{
	return cosTable[angle];
}

void RoboticArm::BuildSinCosTables()
{
	sinTable.resize(1024);
	cosTable.resize(1024);
	for (int x = 0; x < 1024; x++)
	{
		sinTable[x] = sin(TWOPI*(double)x/1024.0);
		cosTable[x] = cos(TWOPI*(double)x/1024.0);
	}
}

ArmToTipHeuristic::ArmToTipHeuristic(RoboticArm *r)
{
	ra = r;
	m_TableComplete = false;
	legalStateTable = NULL;
	legalGoalTable = NULL;
	tipPositionTables = NULL;
	GenerateCPDB();
}

double ArmToTipHeuristic::HCost(const armAngles &node1, const armAngles &node2)
{
	double x, y;
	node2.GetGoal(x, y);

	double h = 0;
	uint16_t tableH;
	for (unsigned i = 0; i < distancesTables.size(); ++i )
	{
		if (node1.GetNumArms() == tablesNumArms[ i ] )
		{
			tableH = UseHeuristic( node1, x, y,
								  distancesTables[ i ],
								  minTipDistancesTables[ i ],
								  maxTipDistancesTables[ i ] );
			if ((double)tableH > h )
			{
				h = (double)tableH;
			}
		}
	}
	return h;
}

void ArmToTipHeuristic::GenerateCPDB()
{
	int numArms = 3;
	//void GenerateLegalArmConfigs();
	armAngles a;
	a.SetNumArms(numArms);
	a.SetAngle(0, 0);
	// 0, 512, 512
	std::vector<std::vector<bool> > legals;
	legals.resize(512);
	for (unsigned int x = 0; x < legals.size(); x++)
	{
		legals[x].resize(512);
		printf("Building table for %d\n", x);
		for (unsigned int y = 0; y < legals[x].size(); y++)
		{
			a.SetAngle(1, 2*x);
			a.SetAngle(2, 2*y);
			legals[x][y] = ra->LegalArmConfig(a);
		}
	}
	m_TableComplete = true;
}

uint64_t ArmToTipHeuristic::ArmAnglesIndex( const armAngles &arm )
{
	uint64_t idx;
	int s;

	idx = 0;
	for( s = 0; s < arm.GetNumArms(); ++s ) {
		idx <<= 9;
		idx |= arm.GetAngle( s ) >> 1;
	}

	return idx;
}

int ArmToTipHeuristic::TipPositionIndex( const double x, const double y,
										const double minX, const double minY,
										const double width )
{
	int idx;

	// if we had a guarantee that width was a multiple of
	// tolerance, we could do a bunch of simplification

	idx = (int)floor( ( y - minY ) / ra->GetTolerance() );
	idx *= (int)floor( width / ra->GetTolerance() );
	idx += (int)floor( ( x - minX ) / ra->GetTolerance() );

	return idx;
}

int ArmToTipHeuristic::WriteArmAngles(FILE *file, armAngles &a)
{
	int s;
	int16_t v;

	v = a.GetNumArms();
	if( fwrite( &v, sizeof( v ), 1, file ) < 1 ) {
		return 0;
	}
	for( s = 0; s < a.GetNumArms(); ++s ) {
		v = a.GetAngle( s );
		if( fwrite( &v, sizeof( v ), 1, file ) < 1 ) {
			return 0;
		}
	}
	return 1;
}

int ArmToTipHeuristic::ReadArmAngles(FILE *file, armAngles &a)
{
	armAngles angles;
	int s;
	int16_t v;

	if( fread( &v, sizeof( v ), 1, file ) < 1 ) {
		return 0;
	}
	angles.SetNumArms( v );
	for( s = 0; s < angles.GetNumArms(); ++s ) {
		if( fread( &v, sizeof( v ), 1, file ) < 1 ) {
			return 0;
		}
		angles.SetAngle( s, v );
	}

	a = angles;
	return 1;
}

void ArmToTipHeuristic::UpdateTipDistances( armAngles &arm, uint16_t distance,
				     uint16_t *minTipDistances,
				     uint16_t *maxTipDistances )
{
	int idx;
	double x, y;

	ra->GetTipPosition( arm, x, y );
	idx = TipPositionIndex( x, y, -1.0, -1.0, 2.0 );
	if( distance < minTipDistances[ idx ] ) {
	  minTipDistances[ idx ] = distance;
	}
	if( distance > maxTipDistances[ idx ] ) {
	  maxTipDistances[ idx ] = distance;
	}
}

// this works because of two things
// a) clockwise and counterclockwise are each others inverses
// and both actions are (potentially) legal moves for every arm segment
// b) action costs are uniform, so all children which have not
// been examined are in the next frontier
// returns the number of states in nextFile
uint64_t ArmToTipHeuristic::GenerateNextDepth( FILE *curFile, FILE *nextFile,
					uint16_t curDistance,
					uint16_t *distances,
					uint16_t *minTipDistances,
					uint16_t *maxTipDistances,
					armAngles &lastAdded )
{
	uint64_t count = 0, idx;
	unsigned i;
	armAngles arm;
	std::vector<armRotations> actions;

	while( ReadArmAngles( curFile, arm ) ) {
		ra->GetActions( arm, actions );
		for( i = 0; i < actions.size(); ++i ) {
			armAngles child = arm;
			ra->ApplyAction( child, actions[ i ] );

			idx = ArmAnglesIndex( child );
			if( distances[ idx ]
			    > curDistance + 1 ) {
				// new arm configuration

				distances[ idx ] = curDistance + 1;
				WriteArmAngles( nextFile, child );
				if( minTipDistances ) {
				  UpdateTipDistances( child, curDistance + 1,
						      minTipDistances,
						      maxTipDistances );
				}
				++count;
			}
		}
	}

	lastAdded = arm;

	return count;
}

/* returns 1 if goal will generate a reasonable heuristic, 0 otherwise */
int ArmToTipHeuristic::GenerateHeuristicSub( const armAngles &sampleArm,
				      const bool quiet,
				      armAngles *goals, const int numGoals,
				      uint16_t *distances,
				      uint16_t *minTipDistances,
				      uint16_t *maxTipDistances,
				      armAngles &lastAdded )
{
	uint64_t count, i, total;
	int numArms = sampleArm.GetNumArms(), segment, g;
	uint16_t distance;
	armAngles arm;
	FILE *curFile, *nextFile;

	arm.SetNumArms( numArms );

	count = NumArmAnglesIndices( arm );
	for( i = 0; i < count; ++i ) {
		distances[ i ] = 65535;
	}

	if( minTipDistances ) {
		count = NumTipPositionIndices();
		for( i = 0; i < count; ++i ) {
			minTipDistances[ i ] = 65535;
			maxTipDistances[ i ] = 0;
		}
	}

	nextFile = tmpfile();
	assert( nextFile != NULL );

	count = 0;
	total = 0;

	if( !quiet ) {
		printf( "populating depth 0\n" );
	}
	for( segment = 0; segment < numArms; ++segment ) {
		arm.SetAngle( segment, 0 );
	}
	while( 1 ) {
		if( ra->LegalState( arm ) ) {
		  ++total;

		  for( g = 0; g < numGoals; ++g ) {
		    if( ra->GoalTest( arm, goals[ g ] ) ) {
		      // new distance 0 (goal) arm configuration

		      distances[ ArmAnglesIndex( arm ) ] = 0;
		      WriteArmAngles( nextFile, arm );
		      UpdateTipDistances( arm, 0, minTipDistances,
					  maxTipDistances );
		      ++count;
		      break;
		    }
		  }
		}

		// next configuration
		segment = 0;
		do {
			armRotations action;
			action.SetRotation( segment, kRotateCW );
			ra->ApplyAction( arm, action );
			if( arm.GetAngle( segment ) != 0 ) {
				break;
			}
		} while( ++segment < numArms );
		if( segment == numArms ) {
			// tried all configurations
			break;
		}
	}

	printf( "%llu legal states\n", total );

	if( !count ) {
	  fclose( nextFile );
	  return 0;
	}

	distance = 0;
	total = 0;
	do {
		total += count;
		if( !quiet ) {
			printf( "%llu states at distance %u\n",
				count, distance );
		}
		curFile = nextFile;
		rewind( curFile );
		nextFile = tmpfile();

		count = GenerateNextDepth( curFile, nextFile, distance,
					   distances, minTipDistances,
					   maxTipDistances, lastAdded );

		++distance;
		fclose( curFile );
	} while( count );
	fclose( nextFile );

	if( !quiet ) {
		printf( "%llu total states\n", total );
	}

	// there are a number of small disconnected subspaces,
	// so make sure goal doesn't correspond to this subspace!
	if( distances[ ArmAnglesIndex( sampleArm ) ] == 65535 ) {
		// sample arm not reachable!
		return 0;
	}

	return 1;
}

/* this function generates a table-based heuristic function for
   the current environment */
void ArmToTipHeuristic::GenerateRandomHeuristic( const armAngles &sampleArm )
{
	uint16_t *distances, *minTipDistances, *maxTipDistances;
	armAngles goal, last;

	distances = new uint16_t[ NumArmAnglesIndices( sampleArm ) ];
	minTipDistances = new uint16_t[ NumTipPositionIndices() ];
	maxTipDistances = new uint16_t[ NumTipPositionIndices() ];

	do {
		goal.SetGoal( (double)random()/(double)RAND_MAX * 2.0 - 1.0,
			      (double)random()/(double)RAND_MAX * 2.0 - 1.0 );
	} while( !GenerateHeuristicSub( sampleArm, false, &goal, 1, distances,
					minTipDistances, maxTipDistances,
					last ) );

	distancesTables.push_back( distances );
	minTipDistancesTables.push_back( minTipDistances );
	maxTipDistancesTables.push_back( maxTipDistances );
	tablesNumArms.push_back( sampleArm.GetNumArms() );
}

/* this function generates a table-based heuristic function for
   the current environment */
int ArmToTipHeuristic::GenerateHeuristic( const armAngles &sampleArm,
				   armAngles &goal )
{
	uint16_t *distances, *minTipDistances, *maxTipDistances;
	armAngles last;

	distances = new uint16_t[ NumArmAnglesIndices( sampleArm ) ];
	minTipDistances = new uint16_t[ NumTipPositionIndices() ];
	maxTipDistances = new uint16_t[ NumTipPositionIndices() ];

	if( !GenerateHeuristicSub( sampleArm, false, &goal, 1, distances,
				   minTipDistances, maxTipDistances, last ) ) {
		delete[] maxTipDistances;
		delete[] minTipDistances;
		delete[] distances;
		return 0;
	}

	distancesTables.push_back( distances );
	minTipDistancesTables.push_back( minTipDistances );
	maxTipDistancesTables.push_back( maxTipDistances );
	tablesNumArms.push_back( sampleArm.GetNumArms() );

	return 1;
}

/* this function generates a table-based heuristic function for
   the current environment */
int ArmToTipHeuristic::GenerateMaxDistHeuristics( const armAngles &sampleArm,
					   const int numHeuristics )
{
	int i, ret;
	uint16_t *distances, *minTipDistances, *maxTipDistances;
	armAngles last;
	armAngles *goals;
	goals = new armAngles[numHeuristics];
	double x, y;

	last = sampleArm;
	ra->GetTipPosition( last, x, y );
	last.SetGoal( x, y );
	for( i = 0; i < numHeuristics; ++i ) {
		distances = new uint16_t[ NumArmAnglesIndices( sampleArm ) ];
		minTipDistances = new uint16_t[ NumTipPositionIndices() ];
		maxTipDistances = new uint16_t[ NumTipPositionIndices() ];

		printf( "generating next goal position\n" );
		if( i ) {
		  ret = GenerateHeuristicSub( sampleArm, true, goals, i,
					      distances, minTipDistances,
					      maxTipDistances, goals[ i ] );
		} else {
		  ret = GenerateHeuristicSub( sampleArm, true, &last, 1,
					      distances, minTipDistances,
					      maxTipDistances, goals[ i ] );
		}
		if( !ret ) {
			delete[] maxTipDistances;
			delete[] minTipDistances;
			delete[] distances;
			return i;
		}
		ra->GetTipPosition( goals[ i ], x, y );
		printf( "new goal position: (%lf,%lf)\n", x, y );
		goals[ i ].SetGoal( x, y );

		if( !GenerateHeuristicSub( sampleArm, false, &goals[ i ], 1,
					   distances, minTipDistances,
					   maxTipDistances, last ) ) {
			delete[] maxTipDistances;
			delete[] minTipDistances;
			delete[] distances;
			return i;
		}

		distancesTables.push_back( distances );
		minTipDistancesTables.push_back( minTipDistances );
		maxTipDistancesTables.push_back( maxTipDistances );
		tablesNumArms.push_back( sampleArm.GetNumArms() );
	}
	delete []goals;
	return i;
}

uint16_t ArmToTipHeuristic::UseHeuristic(const armAngles &s, armAngles &g,
				   uint16_t *distances )
{
	uint16_t d_s, d_g;

	d_s = distances[ ArmAnglesIndex( s ) ];
	d_g = distances[ ArmAnglesIndex( g ) ];
	if( d_s < d_g ) {
	  return d_g - d_s;
	}
	return d_s - d_g;
}

uint16_t ArmToTipHeuristic::UseHeuristic(const armAngles &arm,
				   double goalX, double goalY,
				   uint16_t *distances,
				   uint16_t *minTipDistances,
				   uint16_t *maxTipDistances )
{
	int32_t mind, maxd, t;	// 32 bits because of the subtraction below
	int i, j, index;
	double x, y;

	mind = 65535;
	maxd = 0;
	for( y = goalY - ra->GetTolerance(), i = 0; i < 3; y += ra->GetTolerance(), ++i ) {
	  for( x = goalX - ra->GetTolerance(), j = 0; j < 3; x += ra->GetTolerance(), ++j ) {
	    index =  TipPositionIndex( x, y, -1.0, -1.0, 2.0 );
	    if( minTipDistances[ index ] < mind ) {
	      mind = minTipDistances[ index ];
	    }
	    if( maxTipDistances[ index ] > maxd ) {
	      maxd = maxTipDistances[ index ];
	    }
	  }
	}

	t = distances[ ArmAnglesIndex( arm ) ];
//printf( "dist(s->g)=%u - max(dist(c->g))=%u\n", (unsigned)t, (unsigned)maxd );
//printf( "min(dist(c->g))=%u - dist(s->g)=%u\n", (unsigned)mind, (unsigned)t );
	maxd = t - maxd;
	mind = mind - t;
	if( mind > maxd ) {
	  maxd = mind;
	}
	if( maxd < 0 ) {
	  maxd = 0;
	}

//if( maxd > 0 ) printf( "%u\n", (unsigned)maxd );

	return maxd;
}

bool ArmToTipHeuristic::ValidGoalPosition( double goalX, double goalY )
{
	int i, j, index;
	double x, y, tx, ty;

	if( legalGoalTable == NULL ) {
		// no table to use, can't prove anything
		return false;
	}

	for( y = goalY - ra->GetTolerance(), i = 0; i < 3; y += ra->GetTolerance(), ++i ) {
	  for( x = goalX - ra->GetTolerance(), j = 0; j < 3; x += ra->GetTolerance(), ++j ) {
	    tx = x;
	    if( tx < -1.0 ) {
	      tx = -1.0;
	    } else if( tx >= 1.0 ) {
	      tx = 0.999999;
	    }
	    ty = y;
	    if( ty < -1.0 ) {
	      ty = -1.0;
	    } else if( ty >= 1.0 ) {
	      ty = 0.999999;
	    }

	    index =  TipPositionIndex( tx, ty, -1.0, -1.0, 2.0 );
	    if( !( legalGoalTable[ index >> 3 ] & ( 1 << ( index & 7 ) ) ) ) {
	      // given one unreachable square, there's a possibility
	      // that even if the rest are reachable, they're
	      // only reachable because of states that are
	      // actually further than tolerance away from (x,y)
	      return false;
	    }
	  }
	}

	return true;
}

void ArmToTipHeuristic::GenerateLegalStateTable( armAngles &legalArm )
{
	uint64_t numStates, numTip, i;
	uint16_t *distances, *minTipDistances, *maxTipDistances, distance;
	uint8_t *lst, *lgt;
	armAngles arm, lastAdded;
	FILE *curFile, *nextFile;

	printf( "generating legal state table\n" );

	numStates = NumArmAnglesIndices( legalArm );
	numTip = NumTipPositionIndices();

	lst = new uint8_t[ ( numStates + 7 ) >> 3 ];
	memset( lst, 0, ( numStates + 7 ) >> 3 );
	lgt = new uint8_t[ ( numTip + 7 ) >> 3 ];
	memset( lgt, 0, ( numTip + 7 ) >> 3 );
	distances = new uint16_t[ numStates ];
	for( i = 0; i < numStates; ++i ) {
		distances[ i ] = 65535;
	}
	minTipDistances = new uint16_t[ numTip ];
	maxTipDistances = new uint16_t[ numTip ];
	for( i = 0; i < numTip; ++i ) {
		minTipDistances[ i ] = 65535;
		maxTipDistances[ i ] = 0;
	}

	nextFile = tmpfile();
	assert( nextFile != NULL );

	distances[ ArmAnglesIndex( legalArm ) ] = 0;
	UpdateTipDistances( legalArm, 0, minTipDistances, maxTipDistances );
	WriteArmAngles( nextFile, legalArm );

	distance = 0;
	do {
		curFile = nextFile;
		rewind( curFile );
		nextFile = tmpfile();

		i = GenerateNextDepth( curFile, nextFile, distance,
				       distances, minTipDistances,
				       maxTipDistances, lastAdded );

		++distance;
		fclose( curFile );
	} while( i );
	fclose( nextFile );
	printf( "done: maximum distance of %d from chosen state\n",
		(int)distance );

	for( i = 0; i < numStates; ++i ) {
		if( distances[ i ] < 65535 ) {
			lst[ i >> 3 ] |= 1 << ( i & 7 );
		}
	}

	for( i = 0; i < numTip; ++i ) {
		if( minTipDistances[ i ]
		    <= maxTipDistances[ i ] ) {
			lgt[ i >> 3 ] |= 1 << ( i & 7 );
		}
	}

	legalStateTable = lst;
	legalGoalTable = lgt;
	delete[] maxTipDistances;
	delete[] minTipDistances;
	delete[] distances;
}

void ArmToTipHeuristic::GenerateTipPositionTables( armAngles &sampleArm )
{
	int numArms = sampleArm.GetNumArms(), segment;
	double x, y;
	armAngles arm;

	printf( "generating tip position table\n" );

	if( tipPositionTables != NULL ) {
		return;
	}

	tipPositionTables = new std::vector<armAngles>[ NumTipPositionIndices() ];

	arm.SetNumArms( numArms );

	for (segment = 0; segment < numArms; ++segment)
	{
		arm.SetAngle( segment, 0 );
	}

	while( 1 )
	{
		if( ra->LegalState( arm ) )
		{
			ra->GetTipPosition( arm, x, y );
			tipPositionTables[TipPositionIndex( x, y, -1.0, -1.0, 2.0 )].push_back( arm );
		}

		// next configuration
		segment = 0;
		do {
			armRotations action;
			action.SetRotation( segment, kRotateCW );
			ra->ApplyAction( arm, action );
			if( arm.GetAngle( segment ) != 0 ) {
				break;
			}
		} while( ++segment < numArms );
		if (segment == numArms )
		{
			// tried all configurations
			break;
		}
	}

}

ArmToArmHeuristic::ArmToArmHeuristic(RoboticArm *r, armAngles &initial, bool optimize)
{
	optimizeLocations = optimize;
	ra = r;
	GenerateLegalStates(initial);
}

double ArmToArmHeuristic::HCost(const armAngles &node1, const armAngles &node2)
{
	if (node1.IsGoalState() || node2.IsGoalState())
	{
		//printf("Wrong problem type!\n");
		return 0.0;
	}
	double hval = 0.0;
	for (unsigned int x = 0; x < distances.size(); x++)
	{
		double nextval = abs(distances[x][ra->GetStateHash(node1)] - distances[x][ra->GetStateHash(node2)]);
//		printf("Heuristic %d: |%d-%d| = %f\n", x,
//			   distances[x][ra->GetStateHash(node1)],
//			   distances[x][ra->GetStateHash(node2)],
//			   nextval);
		hval = max(nextval, hval);
	}
	return hval;
}

int ArmToArmHeuristic::TipPositionIndex(const double x, const double y,
										const double minX, const double minY,
										const double width )
{
	int idx;

	// if we had a guarantee that width was a multiple of
	// tolerance, we could do a bunch of simplification
	idx = (int)floor( ( y - minY ) / ra->GetTolerance() );
	idx *= (int)floor( width / ra->GetTolerance() );
	idx += (int)floor( ( x - minX ) / ra->GetTolerance() );

	return idx;
}

void ArmToArmHeuristic::AddDiffTable()
{
	armAngles start = SelectStartNode();

	int which = distances.size();
	printf("Building new heuristic table [%d]\n", which);

	distances.resize(which+1);
	//distances[which].resize();
	std::deque<armAngles> q;
	q.push_back(start);
	canonicalStates.push_back(start);
	while (q.size() > 0)
	{
//		if ((cnt++%10000) == 0)
//			printf("(%d) Q size: %d\n", cnt, (int)q.size());
		armAngles a = q.front();
		q.pop_front();
		uint64_t hash = ra->GetStateHash(a);
		if (hash >= distances[which].size())
			distances[which].resize(hash+1);
		std::vector<armAngles> moves;
		ra->GetSuccessors(a, moves);
//		printf("Getting successors of node %lld at depth %d\n", hash, distances[which][hash]);
		for (unsigned int x = 0; x < moves.size(); x++)
		{
			uint64_t newHash = ra->GetStateHash(moves[x]);
			if (newHash >= distances[which].size())
				distances[which].resize(newHash+1);
			if (distances[which][newHash] != 0)
				continue;

			distances[which][newHash] = distances[which][hash]+1;
//			printf("Setting cost of node %lld to %d (1+%d from %lld)\n", newHash, distances[which][newHash],
//				   distances[which][hash], hash);
			q.push_back(moves[x]);
		}
	}
	printf("Done\n");
}

armAngles ArmToArmHeuristic::SelectStartNode()
{
	armAngles start;
	std::deque<armAngles> q;
	std::vector<bool> used;
	used.resize(512*512*512);
	if ((!optimizeLocations) || (distances.size() == 0))
	{
		do {
			start = ra->GetRandomState();
		} while (!IsLegalState(start));
	}
	if (!optimizeLocations)
		return start;
	if (distances.size() == 0)
	{
		used[ra->GetStateHash(start)] = true;
		q.push_back(start);
	}
	for (unsigned int x = 0; x < canonicalStates.size(); x++)
	{
		q.push_back(canonicalStates[x]);
		used[ra->GetStateHash(canonicalStates[x])] = true;
	}
	armAngles a;
	while (q.size() > 0)
	{
		a = q.front();
		q.pop_front();

		std::vector<armAngles> moves;
		ra->GetSuccessors(a, moves);
		for (unsigned int x = 0; x < moves.size(); x++)
		{
			if (used[ra->GetStateHash(moves[x])])
				continue;
			used[ra->GetStateHash(moves[x])] = true;
			q.push_back(moves[x]);
		}
	}
	return a;
}

bool ArmToArmHeuristic::IsLegalState(armAngles &arm)
{
	return legalStates[ra->GetStateHash(arm)];
}

void ArmToArmHeuristic::GenerateLegalStates(armAngles &init)
{
	int cnt = 0;
	//std::vector<bool> legalStates;
	printf("Getting legal states and tip positions\n");
	legalStates.resize(512*512*512);
	std::deque<armAngles> q;
	q.push_back(init);
	tipPositionTables.resize(200*200);
	while (q.size() > 0)
	{
		if ((cnt++%10000) == 0)
			printf("(%d) Q size: %d\n", cnt, (int)q.size());
		armAngles a = q.front();
		q.pop_front();
		std::vector<armAngles> moves;
		ra->GetSuccessors(a, moves);
		for (unsigned int x = 0; x < moves.size(); x++)
		{
			if (legalStates[ra->GetStateHash(moves[x])])
				continue;
			legalStates[ra->GetStateHash(moves[x])] = true;
			q.push_back(moves[x]);
			double x1, y1;
			ra->GetTipPosition(moves[x], x1, y1);
			int tipIndex = TipPositionIndex(x1, y1);
			tipPositionTables[tipIndex].push_back(moves[x]);
		}
	}
	printf("Done\n");
}


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
        android:id="@+id/map_totemz"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:apiKey="@string/google_maps_key"/>

</LinearLayout>


text:
{-# LANGUAGE LambdaCase, ViewPatterns,ScopedTypeVariables, NoMonomorphismRestriction #-}
module Syntax.Slot(slot,s) where

import Language.Haskell.TH
import Language.Haskell.TH.Quote
import qualified Language.Haskell.Meta as M
import Language.Haskell.Exts.Annotated as A
import Language.Haskell.Exts.Annotated.Simplify
import Language.Haskell.Exts.SrcLoc
import Data.Generics
import Data.Data
import Control.Applicative
import Text.Read
import Data.Either
import Text.Printf
import qualified Data.Vector as V
import Data.List
import qualified Data.Map as M
import Debug.Trace(trace)

--tr x = trace (show x) x
tr x = x

slot = s

s = QuasiQuoter onExp e e e where
	e _ = fail "Not here"
	onExp s = case parseExp s of
		ParseOk a -> transform a
		ParseFailed _ s -> fail s
	transform exp = do
		let
			f = \case
				Var _ (UnQual _ (A.Ident (l::SrcSpanInfo) x)) -> case x of
					"ı" -> [Left (0,l)]
					"_ı" -> [Left (1,l)]
					'_':(readMaybe -> Just (n::Int)) -> [Right (n,l)]
				_ -> []
			((groupBy (\(a,_) (b,_)->a+b==1)->gs), ns) = partitionEithers $ everything (++) (mkQ [] f) exp
			ms = [0..(maximum $ tr (length gs-1): map fst ns)]
		names <- (`mapM` ms) $ (show <$>). newName.printf "slot_%02d"
		let namesV = V.fromList names
		let namesI = M.fromList $ sort $ concat $ zipWith (\n g->[(l,n)|(_,l)<-g]) names gs
		return $ LamE (map (VarP . mkName) names) $ M.toExp $ sExp $ (`everywhere` exp) $ mkT $ \case
			Var l0 (UnQual l1 (A.Ident (l::SrcSpanInfo) x)) -> Var l0 $ UnQual l1 $ A.Ident l $ case x of
				"ı" -> fromI
				"_ı" -> fromI
				'_':(readMaybe -> Just (n::Int)) -> namesV V.! n
				x -> x
				where
				fromI = namesI M.! l
			x -> x
			--Var l (UnQual _ (show->x)) -> case x of

branch f r = case r of
	Right e -> f e
	Left err -> fail err


text:
require 'spec_helper'
require 'silver_lining'

describe Vcloud::Item::NetworkConnection do
  it "constructs" do
    Vcloud::Item::NetworkConnection.new
  end

  it "needs customization" do
    connection = Vcloud::Item::NetworkConnection.new(:needs_customization => "true")

    expect( connection ).to be_needs_customization
  end

  it "is connected" do
    connection = Vcloud::Item::NetworkConnection.new(:connected => "true")

    expect( connection ).to be_connected
  end
end


text:
package com.castlebravostudios.rayguns.items.frames

import com.castlebravostudios.rayguns.api.items.BaseRaygunModule
import com.castlebravostudios.rayguns.api.items.ItemModule
import com.castlebravostudios.rayguns.api.items.RaygunFrame
import com.castlebravostudios.rayguns.mod.ModularRayguns

object MantisFrame extends BaseRaygunModule with RaygunFrame {
  val moduleKey = "MantisFrame"
  val powerModifier = 1.0
  val nameSegmentKey = "rayguns.MantisFrame.segment"

   def createItem() : ItemModule = new ItemModule( this )
    .setUnlocalizedName("rayguns.MantisFrame")
    .setTextureName("rayguns:frame_mantis")
    .setCreativeTab( ModularRayguns.raygunsTab )
    .setMaxStackSize(1)
}


text:
<?php

namespace properties\Controller\SubleasePhoto;

use Canopy\Request;

class Admin extends User
{

    protected function deleteCommand(Request $request)
    {
        $photo = $this->factory->load($this->id);
        $this->factory->delete($photo);
        return array('success' => true);
    }

    protected function savePostCommand(Request $request)
    {
        $sublease_id = $request->pullPostInteger('subleaseId');
        $subleaseFactory = new \properties\Factory\Sublease;
        $sublease = $subleaseFactory->load($sublease_id);
        return $this->factory->post($sublease);
    }

    protected function jsonPatchCommand(Request $request)
    {
        $photo = $this->factory->load($this->id);
        $variableName = $request->pullPatchString('varname');
        switch ($variableName) {
            case 'move':
                $this->factory->sort($photo,
                        $request->pullPatchInteger('newPosition'));
                break;
        }
        return array('success' => true);
    }

    protected function rotatePutCommand(Request $request)
    {
        $photo = $this->factory->load($this->id);
        $this->factory->rotate($photo, $request->pullPutInteger('direction'));
        return array('success' => 1);
    }

}


text:
/* -*- Mode: C -*- */
/*======================================================================
 FILE: jniICalTriggerType_cxx.cpp
 CREATOR: structConverter
 (C) COPYRIGHT 2002, Critical Path
======================================================================*/

#include <jni.h>

#include "jniICalTriggerType_cxx.h"
#include "jniICalTimeType_cxx.h"
#include "jniICalDurationType_cxx.h"

static jfieldID ICalTriggerType_Time_FID;
static jfieldID ICalTriggerType_Duration_FID;

void initICalTriggerTypeFieldIDs(JNIEnv* env, jclass clazz)
{
	ICalTriggerType_Time_FID = env->GetFieldID(clazz, "time", "Lnet/cp/jlibical/ICalTimeType;");
	ICalTriggerType_Duration_FID = env->GetFieldID(clazz, "duration", "Lnet/cp/jlibical/ICalDurationType;");
}

void  jni_SetTime_in_ICalTriggerType(struct ICalTriggerType* __ICalTriggerType_, JNIEnv *env, jobject thisICalTriggerType)
{
	jobject	lcl_jobj0;
	lcl_jobj0 = env->GetObjectField(thisICalTriggerType, ICalTriggerType_Time_FID);
	jni_SetYear_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetMonth_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetDay_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetHour_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetMinute_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetSecond_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetIs_utc_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetIs_date_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_SetZone_in_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
}

void jni_GetTime_from_ICalTriggerType(struct ICalTriggerType* __ICalTriggerType_, JNIEnv *env, jobject thisICalTriggerType)
{
	jobject	lcl_jobj0;
	lcl_jobj0 = env->GetObjectField(thisICalTriggerType, ICalTriggerType_Time_FID);
	jni_GetYear_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetMonth_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetDay_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetHour_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetMinute_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetSecond_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetIs_utc_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetIs_date_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
	jni_GetZone_from_ICalTimeType(&(__ICalTriggerType_->time), env, lcl_jobj0);
}

void  jni_SetDuration_in_ICalTriggerType(struct ICalTriggerType* __ICalTriggerType_, JNIEnv *env, jobject thisICalTriggerType)
{
	jobject	lcl_jobj0;
	lcl_jobj0 = env->GetObjectField(thisICalTriggerType, ICalTriggerType_Duration_FID);
	jni_SetIs_neg_in_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_SetDays_in_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_SetWeeks_in_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_SetHours_in_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_SetMinutes_in_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_SetSeconds_in_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
}

void jni_GetDuration_from_ICalTriggerType(struct ICalTriggerType* __ICalTriggerType_, JNIEnv *env, jobject thisICalTriggerType)
{
	jobject	lcl_jobj0;
	lcl_jobj0 = env->GetObjectField(thisICalTriggerType, ICalTriggerType_Duration_FID);
	jni_GetIs_neg_from_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_GetDays_from_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_GetWeeks_from_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_GetHours_from_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_GetMinutes_from_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
	jni_GetSeconds_from_ICalDurationType(&(__ICalTriggerType_->duration), env, lcl_jobj0);
}

// copy all fields from the c struct (__ICalTriggerType_) to the java object (thisICalTriggerType).
void jni_SetAll_in_ICalTriggerType(struct ICalTriggerType* __ICalTriggerType_, JNIEnv* env, jobject thisICalTriggerType)
{
	jni_SetTime_in_ICalTriggerType(__ICalTriggerType_, env, thisICalTriggerType);
	jni_SetDuration_in_ICalTriggerType(__ICalTriggerType_, env, thisICalTriggerType);
}

// copy all fields from the java object (thisICalTriggerType) to the c struct (__ICalTriggerType_).
void jni_GetAll_from_ICalTriggerType(struct ICalTriggerType* __ICalTriggerType_, JNIEnv* env, jobject thisICalTriggerType)
{
	jni_GetTime_from_ICalTriggerType(__ICalTriggerType_, env, thisICalTriggerType);
	jni_GetDuration_from_ICalTriggerType(__ICalTriggerType_, env, thisICalTriggerType);
}

/*
 * Class:     net_cp_jlibical_ICalTriggerType
 * Method:    init
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_net_cp_jlibical_ICalTriggerType_init__J
  (JNIEnv* env, jobject thisICalTriggerType, jlong data)
{
	// copy all fields from the c struct (data) to the java object (thisICalTimeType).
	jni_SetAll_in_ICalTriggerType((ICalTriggerType*)data,env,thisICalTriggerType);
}

/*
 * Class:     net_cp_jlibical_ICalTriggerType
 * Method:    initFIDs
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_net_cp_jlibical_ICalTriggerType_initFIDs(JNIEnv *env, jclass clazz) {
	initICalTriggerTypeFieldIDs(env, clazz);
}


text:
<?php

namespace ElfChat\Controller\Chat;

use Doctrine\ORM\NoResultException;
use ElfChat\Controller;
use ElfChat\Entity\User\GuestUser;
use ElfChat\Entity\User;
use ElfChat\Security\Authentication\Remember;
use ElfChat\Validator\Constraints\UserName;
use Silicone\Route;
use Symfony\Component\HttpFoundation\Cookie;

class Login extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function check()
    {
        $session = $this->app->session();
        $em = $this->app->entityManager();

        $form = $this->app->form()
            ->add('username')
            ->add('password', 'password')
            ->add('remember_me', 'checkbox', array('required' => false))
            ->getForm();

        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $data = $form->getData();

            try {
                $user = User::findOneByName($data['username']);
            } catch (NoResultException $e) {
                $user = null;
            }

            if (null !== $user) {
                if (password_verify($data['password'], $user->password)) {
                    $session->set('user', $saved = array($user->id, $user->role));

                    $response = $this->app->redirect($this->app->url('chat'));

                    if ($data['remember_me']) {
                        $remember = $this->app['security.remember']->encode($saved);

                        $response->headers->setCookie(
                            new Cookie(Remember::REMEMBER_ME, $remember, time() + (3600 * 24 * 7))
                        );
                    }

                    return $response;
                }
            }

            $error = $this->app->trans('Bad credentials');
        }

        $guestForm = $this->app->form()
            ->add('guestname', 'text', array(
                'constraints' => new UserName(),
            ))
            ->getForm();

        $guestForm->handleRequest($this->request);

        if ($guestForm->isValid()) {
            $data = $guestForm->getData();

            $guest = new GuestUser();
            $guest->name = $data['guestname'];

            $em->persist($guest);
            $em->flush($guest);

            $session->set('user', array($guest->id, $guest->role));

            return $this->app->redirect($this->app->url('chat'));
        }

        $response = $this->render('login/login.twig', array(
            'error' => isset($error) ? $error : null,
            'form' => $form->createView(),
            'guestForm' => $guestForm->createView(),
        ));
        return $response;
    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logout()
    {
        $this->app->session()->remove('user');
        $response = $this->app->redirect($this->app->url('chat'));
        $response->headers->clearCookie(Remember::REMEMBER_ME);
        return $response;
    }
}


text:
/**
 * @param {string} nombre de la clase
 * @param {object} atributos de la clase
 */
Ext.define('sisprod.controller.SystemSecurityRoleController', {
   extend: 'sisprod.controller.Base',
//   stores : ['SystemEntityRoleAssignmentGridStore'],
   models : ['SystemEntityRoleAssignmentModel'],
   entityName: 'SystemSecurityRole',
//   refs: [{ref: 'listSystemSecurityRole', selector: 'listSystemSecurityRole'}],
   views : ['SystemSecurityRole.AdminSystemSecurityRole'],
//
//   requires: [
//       'sisprod.store.SystemSecurityRoleStore'
//   ],

   messages: {
       successfulAssignment: 'Permissions assigned successfuly!',
       confirmationText: 'Are you sure you want assign selected roles?',
       selectSecurityItem: 'Select User/Group before!'
   },

   init : function(){
       var me = this;
        this.control({
//           'listSystemSecurityRole button[action=update]':{
//               click: this.showUpdateOnButton
//           },

           'adminSystemSecurityRole button[action=showPermissions]':{
               click: this.onShowPermissions
           },

           'adminSystemSecurityRole button[action=savePermissions]':{
               click: this.onSavePermissions
           },

           'adminSystemSecurityRole radiogroup[id=securityItemType]':{
               change: this.onChangeSecurityItemType
           },

           'adminSystemSecurityRole combobox[id=idSecurityItem]':{
               select: this.onSelectSecurityItem
           }

//           'listSystemSecurityRole dataview': {
//               itemdblclick: this.showUpdate
//           },
//
//           'updateSystemSecurityRole button[action=save]': {
//               click: this.saveEntity
//           }

       });
       this.callParent(arguments);
    },

    beforeShowInitialView: function(data, tabPanel, tabId){
        return true;
    },

    onSelectSecurityItem: function(combobox, records, eventOptions){
        var me = this;
        //
        me.showPermissions(combobox);
    },

    onShowPermissions: function(button){
        var me = this;
        //
        me.showPermissions(button);
//        if(Ext.isDefined(menuStore) && menuStore !== null){
//            menu.store = Ext.create('sisprod.store.SystemEntityRoleAssignmentMenuStore').load({
//                params: { usedId: 1 },
//                callback: function(record, options){
//                    menu.setRootNode(menuStore.getRootNode());
//                }
//            });
//        }
//        else{
//            menu.store.load({
//                params: { usedId: 1 },
//                callback: function(record, options){
//                    menu.setRootNode(menuStore.getRootNode());
//                }
//            });
//        }
    },

    showPermissions: function(component){
        var me = this;
        //
        var menu = component.up('tabPanelItem').queryById('systemEntityRoleAssignmentMenu');
        var grid = component.up('tabPanelItem').queryById('systemEntityRoleAssignmentGrid');
        var securityItem = component.up('panel').queryById('idSecurityItem');
        var idSecurityItem = securityItem.getValue();
        //
        if(!Ext.isDefined(idSecurityItem) || idSecurityItem === null){
            Ext.Msg.alert(me.controllerMessages.alertMessage, me.messages.selectSecurityItem);
            return;
        }
        //
        var gridStore = grid.getStore();
        var values = {};
        var securityItemType = Ext.getCmp('securityItemType').getValue();
        if(securityItemType.type === 'user') values["userId"] = idSecurityItem;
        else values["groupId"] = idSecurityItem;
        gridStore.load({ params: values });
        //
        var menuStore = menu.getStore();
        menuStore = Ext.create('sisprod.store.SystemEntityRoleAssignmentMenuStore').load({
            params: values,
            callback: function(record, options){
                menu.setRootNode(menuStore.getRootNode());
            }
        });
    },

    onSavePermissions: function(button){
        var me = this;
        var securityItem = button.up('tabPanelItem').queryById('idSecurityItem');
        var idSecurityItem = securityItem.getValue();
        if(!Ext.isDefined(idSecurityItem) || idSecurityItem === null){
            Ext.Msg.alert(me.controllerMessages.alertMessage, me.messages.selectSecurityItem);
            return;
        }
        var roles = new Array();
        //
        if(Ext.isDefined(idSecurityItem) && idSecurityItem !== null){
            var menu = button.up('tabPanelItem').queryById('systemEntityRoleAssignmentMenu');
            var grid = button.up('tabPanelItem').queryById('systemEntityRoleAssignmentGrid');
            //
//            var menuStore = menu.getStore();
            var gridStore = grid.getStore();
            //
            for(var i = 0; i< gridStore.getCount(); i++){
                var record = gridStore.getAt(i);
                if(record.data['listRoleGranted']) roles.push(record.data['listRoleId']);
                if(record.data['createRoleGranted']) roles.push(record.data['createRoleId']);
                if(record.data['updateRoleGranted']) roles.push(record.data['updateRoleId']);
                if(record.data['deleteRoleGranted']) roles.push(record.data['deleteRoleId']);
                if(record.data['exportRoleGranted']) roles.push(record.data['exportRoleId']);
            }
            //
            var checked = menu.getView().getChecked();
            for(var i = 0; i< checked.length; i++){
                var data = checked[i].raw;
                var roleId = data['roleId'];
                if(Ext.isDefined(roleId) && roleId !== null) roles.push(roleId);
            }
        }
        if(roles.length > 0){
            var values = { grantedRoles: roles.join(',') };
            var securityItemType = Ext.getCmp('securityItemType').getValue();
            if(securityItemType.type === 'user') values["userId"] = idSecurityItem;
            else values["groupId"] = idSecurityItem;
            //
            Ext.Msg.show({
                title: me.controllerMessages.confirmText,
                msg: me.messages.confirmationText,
                buttons: Ext.Msg.YESNO,
                icon: Ext.Msg.QUESTION,
                fn: function(button){
                    if(button==="yes"){
                        Ext.BaseAjax.request({
                            url: 'rest/systemSecurityRole/saveGrantedSecurityRoles.htm',
                            method: "POST",
                            params: values,
                            success: function(response){
                                var responseData = Ext.decode(response.responseText);
                                if(responseData.success)
                                    Ext.Msg.alert(me.controllerMessages.alertMessage, me.messages.successfulAssignment);
                                else Ext.Msg.alert(me.controllerMessages.alertMessage, responseData.message);
                            }
                        });
                    }
                }
            });
        }
    },

    onChangeSecurityItemType: function(radioGroup, newValue, oldValue, eventOptions){
        var panel = radioGroup.up('panel');
        var securityItem = panel.queryById('idSecurityItem');
        securityItem.clearValue();
        securityItem.getStore().reload();
    }
});


text:
CREATE OR REPLACE FUNCTION cron.Dispatch(OUT RunProcessID integer, OUT RunInSeconds numeric, OUT MaxProcesses integer, OUT ConnectionPoolID integer, OUT RetryOnError numeric)
RETURNS RECORD
LANGUAGE plpgsql
SET search_path TO public, pg_temp
AS $FUNC$
DECLARE
_OK        boolean;
_JobID     integer;
_RunAtTime timestamptz;
BEGIN

IF NOT pg_try_advisory_xact_lock('cron.Dispatch()'::regprocedure::int, 0) THEN
    RAISE EXCEPTION 'Aborting cron.Dispatch() because of a concurrent execution';
END IF;

SELECT
    P.ProcessID,
    CASE
        WHEN J.RunAfterTimestamp > now()       THEN J.RunAfterTimestamp
        WHEN J.RunAfterTime      > now()::time THEN now()::date + J.RunAfterTime
        WHEN P.LastRunFinishedAt IS NULL       THEN now()
        ELSE P.LastRunFinishedAt + CASE WHEN P.BatchJobState = 'DONE' THEN J.IntervalDONE ELSE J.IntervalAGAIN END
    END,
    CP.MaxProcesses,
    J.ConnectionPoolID,
    extract(epoch from J.RetryOnError)
INTO
    RunProcessID,
    _RunAtTime,
    MaxProcesses,
    ConnectionPoolID,
    RetryOnError
FROM cron.Jobs AS J
INNER JOIN cron.Processes AS P ON (P.JobID = J.JobID)
LEFT JOIN cron.ConnectionPools AS CP ON (CP.ConnectionPoolID = J.ConnectionPoolID)
WHERE P.RunAtTime IS NULL
AND J.Enabled
AND P.Enabled
AND (P.BatchJobState IS DISTINCT FROM 'DONE' OR J.IntervalDONE IS NOT NULL)
AND (now() > J.RunUntilTimestamp OR now()::time > J.RunUntilTime) IS NOT TRUE
ORDER BY 2 NULLS LAST, 1
LIMIT 1
FOR UPDATE OF P;
IF NOT FOUND THEN
    RETURN;
END IF;

RunInSeconds := extract(epoch from _RunAtTime - now());

UPDATE cron.Processes SET RunAtTime = _RunAtTime WHERE ProcessID = RunProcessID AND RunAtTime IS NULL RETURNING TRUE INTO STRICT _OK;
RAISE DEBUG '% pg_backend_pid % : spawn new process -> [JobID % RunAtTime % RunProcessID % RunInSeconds % MaxProcesses % ConnectionPoolID %]', clock_timestamp()::timestamp(3), pg_backend_pid(), _JobID, _RunAtTime, RunProcessID, RunInSeconds, MaxProcesses, ConnectionPoolID;
RETURN;

END;
$FUNC$;

ALTER FUNCTION cron.Dispatch() OWNER TO pgcronjob;


text:
Slides presented at AppliedR MeetUp September 20th, 2017

### Workflow

- install `xaringang` and `coalitions` packages
```r
devtools::install_github('yihui/xaringan')
devtools::install_github('adibender/coalitions')
```

- Host site on local server + continuous preview:
```r
xaringan::infinite_moon_reader("appliedR-slides.Rmd")
```

### xaringan/remark.js sources

- https://slides.yihui.name/xaringan/#1
- https://remarkjs.com/#1


text:
using UnityEngine;
using System.Collections;

[AddComponentMenu("Playground/Movement/Auto Move")]
[RequireComponent(typeof(Rigidbody2D))]
public class AutoMove : Physics2DObject
{
	// These are the forces that will push the object every frame
	// don't forget they can be negative too!
	public Vector2 direction = new Vector2(1f, 0f);

	//is the push relative or absolute to the world?
	public bool relativeToRotation = true;

	// FixedUpdate is called once per frame
	void FixedUpdate ()
	{
		if(relativeToRotation)
		{
			rigidbody2D.AddRelativeForce(direction * 2f);
		}
		else
		{
			rigidbody2D.AddForce(direction * 2f);
		}
	}

	//Draw an arrow to show the direction in which the object will move
	void OnDrawGizmosSelected()
	{
		if(this.enabled)
		{
			float extraAngle = (relativeToRotation) ? transform.rotation.eulerAngles.z : 0f;
			Utils.DrawMoveArrowGizmo(transform.position, direction, extraAngle);
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace OpenCFP\Http\Action\Talk;

use OpenCFP\Domain\CallForPapers;
use OpenCFP\Http\View;
use Symfony\Component\HttpFoundation;
use Symfony\Component\Routing;
use Twig\Environment;

final class CreateAction
{
    /**
     * @var View\TalkHelper
     */
    private $talkHelper;

    /**
     * @var CallForPapers
     */
    private $callForPapers;

    /**
     * @var Environment
     */
    private $twig;

    /**
     * @var Routing\Generator\UrlGeneratorInterface
     */
    private $urlGenerator;

    public function __construct(
        View\TalkHelper $talkHelper,
        CallForPapers $callForPapers,
        Environment $twig,
        Routing\Generator\UrlGeneratorInterface $urlGenerator
    ) {
        $this->talkHelper    = $talkHelper;
        $this->callForPapers = $callForPapers;
        $this->twig          = $twig;
        $this->urlGenerator  = $urlGenerator;
    }

    public function __invoke(HttpFoundation\Request $request): HttpFoundation\Response
    {
        if (!$this->callForPapers->isOpen()) {
            $request->getSession()->set('flash', [
                'type'  => 'error',
                'short' => 'Error',
                'ext'   => 'You cannot create talks once the call for papers has ended',
            ]);

            $url = $this->urlGenerator->generate('dashboard');

            return new HttpFoundation\RedirectResponse($url);
        }

        $content = $this->twig->render('talk/create.twig', [
            'formAction'     => $this->urlGenerator->generate('talk_create'),
            'talkCategories' => $this->talkHelper->getTalkCategories(),
            'talkTypes'      => $this->talkHelper->getTalkTypes(),
            'talkLevels'     => $this->talkHelper->getTalkLevels(),
            'title'          => $request->request->get('title'),
            'description'    => $request->request->get('description'),
            'type'           => $request->request->get('type'),
            'level'          => $request->request->get('level'),
            'category'       => $request->request->get('category'),
            'desired'        => $request->request->get('desired'),
            'slides'         => $request->request->get('slides'),
            'other'          => $request->request->get('other'),
            'sponsor'        => $request->request->get('sponsor'),
            'buttonInfo'     => 'Submit my talk!',
        ]);

        return new HttpFoundation\Response($content);
    }
}


text:
@import AppKit;

@interface EventMonitor : NSObject

- (id)initWithMask:(NSEventMask)mask handler:(void (^)(NSEvent *))handler;
- (void)start;
- (void)stop;

@end


text:
package org.handwerkszeug.riak.config;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;

/**
 * @author taichi
 */
public interface RiakConfig {

	Integer getTimeout();

	InetSocketAddress getRiakAddress();

	ExecutorService getBossExecutor();

	ExecutorService getWorkerExecutor();

	ExecutorService getActionExecutor();

}


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

namespace ASCIIString
{
    class ASCIIString
    {
        static void Main(string[] args)
        {
            int number = int.Parse(Console.ReadLine());
            string result = "";
            for (int i = 1; i <= number; i++)
            {
                int numberToConvert = int.Parse(Console.ReadLine());
                char letter = Convert.ToChar(numberToConvert);
                result += letter;
            }
            Console.WriteLine(result);
        }
    }
}


text:
"""Arch Linux Image Builder for GCE.

This script creates a clean Arch Linux image that can be used in Google Compute
Engine.

Usage: ./build-gce-arch.py -> archlinux-***.tar.gz
       ./build-gce-arch.py --packages docker
       ./build-gce-arch.py --help -> Detailed help.
"""
import argparse
import os
import logging
from datetime import date

import utils

DEFAULT_MIRROR = 'http://mirrors.kernel.org/archlinux/$repo/os/$arch'
#DEFAULT_MIRROR = 'http://mirror.us.leaseweb.net/archlinux/$repo/os/$arch'
TARGET_ARCH = 'x86_64'

def main():
  args = ParseArgs()
  utils.SetupLogging(quiet=args.quiet, verbose=args.verbose)
  workspace_dir = None
  image_file = None
  try:
    workspace_dir = utils.CreateTempDirectory()
    bootstrap_file = DownloadArchBootstrap(args.bootstrap)
    utils.Untar(bootstrap_file, workspace_dir)
    arch_root = PrepareBootstrap(workspace_dir, args.mirror, not args.nopacmankeys)
    relative_builder_path = utils.CopyBuilder(arch_root)
    ChrootIntoArchAndBuild(arch_root, relative_builder_path, args)
    image_name, image_filename, image_description = GetImageNameAndDescription(
        args.outfile)
    image_file = SaveImage(arch_root, image_filename)
    if args.upload and image_file:
      UploadImage(image_file, args.upload, make_public=args.public)
      if args.register:
        AddImageToComputeEngineProject(
            image_name, args.upload, image_description)
  finally:
    if not args.nocleanup and workspace_dir:
      utils.DeleteDirectory(workspace_dir)

def ParseArgs():
  parser = argparse.ArgumentParser(
      description='Arch Linux Image Builder for Compute Engine')
  parser.add_argument('-p', '--packages',
                      dest='packages',
                      nargs='+',
                      help='Additional packages to install via Pacman.')
  parser.add_argument('--mirror',
                      dest='mirror',
                      default=DEFAULT_MIRROR,
                      help='Mirror to download packages from.')
  parser.add_argument('--bootstrap',
                      dest='bootstrap',
                      help='Arch Linux Bootstrap tarball. '
                           '(default: Download latest version)')
  parser.add_argument('-v', '--verbose',
                      dest='verbose',
                      default=False,
                      help='Verbose console output.',
                      action='store_true')
  parser.add_argument('-q', '--quiet',
                      dest='quiet',
                      default=False,
                      help='Suppress all console output.',
                      action='store_true')
  parser.add_argument('--upload',
                      dest='upload',
                      default=None,
                      help='Google Cloud Storage path to upload to.')
  parser.add_argument('--size_gb',
                      dest='size_gb',
                      default=10,
                      help='Volume size of image (in GiB).')
  parser.add_argument('--accounts',
                      dest='accounts',
                      nargs='+',
                      help='Space delimited list of user accounts to create on '
                      'the image. Format: username:password')
  parser.add_argument('--nocleanup',
                      dest='nocleanup',
                      default=False,
                      help='Prevent cleaning up the image build workspace '
                           'after image has been created.',
                      action='store_true')
  parser.add_argument('--outfile',
                      dest='outfile',
                      default=None,
                      help='Name of the output image file.')
  parser.add_argument('--debug',
                      dest='debug',
                      default=False,
                      help='Configure the image for debugging.',
                      action='store_true')
  parser.add_argument('--public',
                      dest='public',
                      default=False,
                      help='Make image file uploaded to Cloud Storage '
                           'available for everyone.',
                      action='store_true')
  parser.add_argument('--register',
                      dest='register',
                      default=False,
                      help='Add the image to Compute Engine project. '
                           '(Upload to Cloud Storage required.)',
                      action='store_true')
  parser.add_argument('--nopacmankeys',
                      dest='nopacmankeys',
                      default=False,
                      help='Disables signature checking for pacman packages.',
                      action='store_true')
  return parser.parse_args()

def DownloadArchBootstrap(bootstrap_tarball):
  utils.LogStep('Download Arch Linux Bootstrap')
  if bootstrap_tarball:
    url = bootstrap_tarball
    sha1sum = None
  else:
    url, sha1sum = GetLatestBootstrapUrl()
  logging.debug('Downloading %s', url)
  local_bootstrap = os.path.join(os.getcwd(), os.path.basename(url))
  if os.path.isfile(local_bootstrap):
    logging.debug('Using local file instead.')
    if sha1sum and utils.Sha1Sum(local_bootstrap) == sha1sum:
      return local_bootstrap
  utils.DownloadFile(url, local_bootstrap)
  if not sha1sum or utils.Sha1Sum(local_bootstrap) != sha1sum:
      raise ValueError('Bad checksum')
  return local_bootstrap

def ChrootIntoArchAndBuild(arch_root, relative_builder_path, args):
  params = {
    'quiet': args.quiet,
    'verbose': args.verbose,
    'packages': args.packages,
    'mirror': args.mirror,
    'accounts': args.accounts,
    'debugmode': args.debug,
    'size_gb': args.size_gb
  }
  chroot_archenv_script = os.path.join('/', relative_builder_path,
                                       'arch-staging.py')
  utils.RunChroot(arch_root,
                  '%s "%s"' % (chroot_archenv_script, utils.EncodeArgs(params)))
  logging.debug('Bootstrap Chroot: sudo %s/bin/arch-chroot %s/',
                arch_root, arch_root)

def SaveImage(arch_root, image_filename):
  utils.LogStep('Save Arch Linux Image in GCE format')
  source_image_raw = os.path.join(arch_root, 'disk.raw')
  image_raw = os.path.join(os.getcwd(), 'disk.raw')
  image_file = os.path.join(os.getcwd(), image_filename)
  utils.Run(['cp', '--sparse=always', source_image_raw, image_raw])
  utils.Run(['tar', '-Szcf', image_file, 'disk.raw'])
  return image_file

def UploadImage(image_path, gs_path, make_public=False):
  utils.LogStep('Upload Image to Cloud Storage')
  utils.SecureDeleteFile('~/.gsutil/*.url')
  utils.Run(['gsutil', 'rm', gs_path])
  utils.Run(['gsutil', 'cp', image_path, gs_path])
  if make_public:
    utils.Run(['gsutil', 'acl', 'set', 'public-read', gs_path])

def AddImageToComputeEngineProject(image_name, gs_path, description):
  utils.LogStep('Add image to project')
  utils.Run(['gcloud', 'compute', 'images', 'delete', image_name, '-q'])
  utils.Run(['gcloud', 'compute', 'images', 'create', image_name, '-q',
             '--source-uri', gs_path,
             '--description', description])

def PrepareBootstrap(workspace_dir, mirror_server, use_pacman_keys):
  utils.LogStep('Setting up Bootstrap Environment')
  arch_root = os.path.join(workspace_dir, os.listdir(workspace_dir)[0])
  mirrorlist = 'Server = {MIRROR_SERVER}'.format(MIRROR_SERVER=mirror_server)
  utils.AppendFile(os.path.join(arch_root, 'etc/pacman.d/mirrorlist'),
                   mirrorlist)
  utils.CreateDirectory(os.path.join(arch_root, 'run/shm'))
  if use_pacman_keys:
    utils.RunChroot(arch_root, 'pacman-key --init')
    utils.RunChroot(arch_root, 'pacman-key --populate archlinux')
  else:
    utils.ReplaceLine(os.path.join(arch_root, 'etc/pacman.conf'), 'SigLevel', 'SigLevel = Never')
  # Install the most basic utilities for the bootstrapper.
  utils.RunChroot(arch_root,
                  'pacman --noconfirm -Sy python3 sed')

  return arch_root

def GetLatestBootstrapUrl():
  base_url = 'http://mirrors.kernel.org/archlinux/iso/latest/'
  sha1sums = utils.HttpGet(base_url + 'sha1sums.txt')
  items = sha1sums.splitlines()
  for item in items:
    if TARGET_ARCH in item and 'bootstrap' in item:
      entries = item.split()
      return base_url + entries[1], entries[0]
  raise RuntimeError('Cannot find Arch bootstrap url')

def GetImageNameAndDescription(outfile_name):
  today = date.today()
  isodate = today.strftime("%Y-%m-%d")
  yyyymmdd = today.strftime("%Y%m%d")
  image_name = 'arch-v%s' % yyyymmdd
  if outfile_name:
    image_filename = outfile_name
  else:
    image_filename = '%s.tar.gz' % image_name
  description = 'Arch Linux x86-64 built on %s' % isodate
  return image_name, image_filename, description

main()