text:
package cn.sharesdk.demo;

import java.io.File;
import java.io.FileOutputStream;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import m.framework.ui.widget.slidingmenu.SlidingMenu;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * entrance of the project, UI shell of sliding menu
 * ui logics and events are handled by {@link MainAdapter}
 */
public class MainActivity extends Activity implements Callback {
	private static final String FILE_NAME = "/pic.jpg";
	public static String TEST_IMAGE;
	private SlidingMenu menu;
	private int orientation;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		orientation = getResources().getConfiguration().orientation;

		menu = new SlidingMenu(this);
		menu.setMenuItemBackground(R.color.sliding_menu_item_down, R.color.sliding_menu_item_release);
		menu.setMenuBackground(R.color.sliding_menu_background);
		menu.setTtleHeight(cn.sharesdk.framework.utils.R.dipToPx(this, 44));
		menu.setBodyBackground(R.color.sliding_menu_body_background);
		menu.setShadowRes(R.drawable.sliding_menu_right_shadow);
		menu.setMenuDivider(R.drawable.sliding_menu_sep);
		menu.setAdapter(new MainAdapter(menu));
		setContentView(menu);

		ShareSDK.initSDK(this);

		new Thread() {
			public void run() {
				initImagePath();
				UIHandler.sendEmptyMessageDelayed(1, 100, MainActivity.this);
			}
		}.start();
	}

	private void initImagePath() {
		try {
			String cachePath = cn.sharesdk.framework.utils.R.getCachePath(this, null);
			TEST_IMAGE = cachePath + FILE_NAME;
			File file = new File(TEST_IMAGE);
			if (!file.exists()) {
				file.createNewFile();
				Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
				FileOutputStream fos = new FileOutputStream(file);
				pic.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
			}
		} catch(Throwable t) {
			t.printStackTrace();
			TEST_IMAGE = null;
		}
	}

	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case 1: {
				menu.triggerItem(MainAdapter.GROUP_DEMO, MainAdapter.ITEM_DEMO);
			}
			break;
			case 2: {
				String text = getString(R.string.receive_rewards, msg.arg1);
				Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
			}
			break;
		}
		return false;
	}

	/** this method will be called after the screen rotation to refresh the sliding menu */
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (orientation != newConfig.orientation) {
			orientation = newConfig.orientation;
			menu.refresh();
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN
				&& !menu.isMenuShown()) {
			menu.showMenu();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}

	/** converts ShareSDK actions into string */
	public static String actionToString(int action) {
		switch (action) {
			case Platform.ACTION_AUTHORIZING: return "ACTION_AUTHORIZING";
			case Platform.ACTION_GETTING_FRIEND_LIST: return "ACTION_GETTING_FRIEND_LIST";
			case Platform.ACTION_FOLLOWING_USER: return "ACTION_FOLLOWING_USER";
			case Platform.ACTION_SENDING_DIRECT_MESSAGE: return "ACTION_SENDING_DIRECT_MESSAGE";
			case Platform.ACTION_TIMELINE: return "ACTION_TIMELINE";
			case Platform.ACTION_USER_INFOR: return "ACTION_USER_INFOR";
			case Platform.ACTION_SHARE: return "ACTION_SHARE";
			default: {
				return "UNKNOWN";
			}
		}
	}

}


text:
"""
    [ Letter Monster V2 ]
    Copyright (C) 2013, Cristi Constantin.
    All Rights Reserved.
"""

import time
import struct
import binascii
from PIL import Image, ImageFilter
import numpy as np

# All valid PIL filters
Filters = ('BLUR', 'SHARPEN', 'EDGE_ENHANCE', 'SMOOTH', 'SMOOTH_MORE', 'DETAIL', 'CONTOUR', 'EDGE_ENHANCE_MORE')

Patterns = {
    'default'    : u'&80$21|;:\' ',     # Original Patrick T. Cossette pattern
    'saufanlee'  : u'#WKDGLftji+;,:. ', # Sau Fan Lee pattern
    'dark'       : u'WWWwww.',          # Good for color HTML
    'huge'       : u'MMMMMMM@@@@@@@WWWWWWWWWBBBBBBBB000000008888888ZZZZZZZZZaZaaaaaa2222222SSSSSSSXXXXXXXXXXX7777777rrrrrrr;;;;;;;;iiiiiiiii:::::::,:,,,,,,.........    ',
    'dos'        : u'\u2588\u2593\u2592\u2665\u2666\u263b\u256c\u263a\u25ca\u25cb\u2591 '
}

def Consume(image, output, x=0, y=0, pattern='default', filter=''):

    '''
    Takes a supported image as input, transforms it into a Rectangular Unicode Array and exports the result.\n\
    You can use different patterns for transforming : default, dark, huge, etc.\n\
    You can also apply filters : BLUR, SHARPEN, EDGE_ENHANCE, SMOOTH, etc.\n\
    '''

    try:
        vInput = Image.open( image )
    except:
        print( 'Letter-Monster snarls: "`%s` is not a valid image path, or Python-Imaging '
            'cannot open that type of file! Cannot consume!"' % image ) ; return

    ti = time.clock() # Global counter.

    if x and not y:     # If x has a value.
        if DEBUG: print( 'Letter-Monster says: "I\'m resizing to X = %i."' % x )
        y = (x * vInput.size[1]) / vInput.size[0]
        if DEBUG: print( 'Letter-Monster says: "Y becomes %i."' % y )
    elif y and not x:   # Or if y has a value.
        if DEBUG: print( 'Letter-Monster says: "I\'m resizing to Y = %i."' % y )
        x = (y * vInput.size[0]) / vInput.size[1]
        if DEBUG: print( 'Letter-Monster says: "X becomes %i."' % x )

    elif x and y:       # If both x and y have a value.
        if DEBUG: print( 'Letter-Monster says: "Disproportionate resize X = %i, Y = %i."' % (x,y) )
    if x or y:          # If resize was called.
        vInput = vInput.resize((x, y), Image.BICUBIC) # Do the resize.
    del x ; del y

    if filter: # If filter was called.
        for filt in filter.split('|'):
            filt = filt.upper()
            if filt in Filters:
                vInput = vInput.filter( getattr(ImageFilter, filt) )
                if DEBUG: print( 'Letter-Monster says: "Applied %s filter."' % filt )
            else:
                print( 'Letter-Monster growls: "I don\'t know any filter called `%s`! I will ignore it."' % filt )

    if pattern.lower() in Patterns:
        vPattern = Patterns[pattern.lower()]
    else:
        print( 'Letter-Monster growls: "I don\' know any pattern called `%s`! I will use default pattern."' % pattern )
        vPattern = Patterns['default']

    vLen = len( vPattern )
    vLetters = np.empty( (vInput.size[1], vInput.size[0]), 'U' )
    vColors = []

    if vInput.mode=='L' or 'P': # Convert grayscale / indexed images to RGB.
        pxaccess = vInput.convert('RGB').load()
        ch = 3
    else:
        pxaccess = vInput.load()
        ch = len(vInput.getbands())

    fix_clr = lambda x: (x / 51) * 51

    for py in range(vInput.size[1]): # Cycle through the image's pixels, one by one
        for px in range(vInput.size[0]):

            pix_color = pxaccess[px, py] # Pointer to current pixel
            vColor = sum(pix_color)      # Calculate general darkness of the pixel

            fixed_color = [ fix_clr(pix_color[0]), fix_clr(pix_color[1]), fix_clr(pix_color[2]) ]
            vColors.append( binascii.hexlify(struct.pack('BBB', *fixed_color))[::2] )

            for vp in range( vLen ):                       # For each element in the string pattern
                if vColor <= ( 255 * ch / vLen * (vp+1) ): # Return matching character from pattern
                    vLetters[py,px] = vPattern[vp]
                    break
                # If not in range, return last character from pattern
                elif vColor > ( 255 * ch / vLen * vLen ) and vColor <= ( 255 * ch ):
                    vLetters[py,px] = vPattern[-1]
                    break

    # Equalize "non conventional" colors...
    eq_colors = sorted(set(vColors))
    print 'Found `{}` unique colors.'.format(len(eq_colors))
    print 'Colors : `{}`.'.format(eq_colors)

    tf = time.clock()
    if DEBUG: print( 'Letter-Monster says: "Consume took %.4f seconds total."' % (tf-ti) )

    if output.endswith('htm') or output.endswith('html'):

        vOut = open(output, 'w')
        vOut.write('\n
\n')

        last_color = 0
        color_index = 0

        for py in range(vInput.size[1]):
            for px in range(vInput.size[0]):
                curr_color = vColors[color_index]
                if curr_color != last_color:
                    last_color = curr_color
                    if color_index: vOut.write('')
                    vOut.write('{}'.format(curr_color, vLetters[py,px]))
                else:
                    vOut.write(vLetters[py,px])
                color_index += 1
            vOut.write('\n')

        vOut.write('\n
')
        vOut.close()

    elif output.endswith('jade'):

        vOut = open(output, 'w')
        vOut.write('\n\n')

        last_color = 0
        color_index = 0

        for py in range(vInput.size[1]):
            vOut.write('| ')
            for px in range(vInput.size[0]):
                curr_color = vColors[color_index]
                if curr_color != last_color:
                    last_color = curr_color
                    if color_index: vOut.write('')
                    vOut.write('{}'.format(curr_color, vLetters[py,px]))
                else:
                    vOut.write(vLetters[py,px])
                color_index += 1
            vOut.write('\n')

        vOut.write('\n')
        vOut.close()

    else:

        vOut = open(output, 'w')
        vOut.close()

#

if __name__ == '__main__':

    DEBUG = True

    Consume('house1.png', 'export.jade', x=120, pattern='dark')

#

redpajama_set_name: RedPajamaGithub


text:
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from dnd.mobile.views import permanent_redirect_object_mobile
from dnd.models import Rule
from dnd.views import is_3e_edition

def rule_detail_mobile(request, rulebook_slug, rulebook_id, rule_slug, rule_id):
    rule = get_object_or_404(
        Rule.objects.select_related('rulebook', 'rulebook__dnd_edition'),
        pk=rule_id)
    if (rule.slug != rule_slug or
                unicode(rule.rulebook.id) != rulebook_id or
                rule.rulebook.slug != rulebook_slug):
        return permanent_redirect_object_mobile(request, rule)

    return render_to_response('dnd/mobile/rules/rule_detail.html',
                              {
                                  'rule': rule,
                                  'rulebook': rule.rulebook,
                                  'request': request,
                                  'i_like_it_url': request.build_absolute_uri(),
                                  'inaccurate_url': request.build_absolute_uri(),
                                  'display_3e_warning': is_3e_edition(rule.rulebook.dnd_edition),
                              }, context_instance=RequestContext(request), )


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.Runtime.Serialization;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Diagnostics;
using Microsoft.Win32;
using System.Threading;
using System.Globalization;
using System.Threading.Tasks;

namespace ClangCompile
{
    public static class StringSplitter
    {
        public static IEnumerable<string> Split(this string str, Func<char, bool> controller)
        {
            int nextPiece = 0;
            for (int c = 0; c < str.Length; c++)
            {
                if (controller(str[c]))
                {
                    yield return str.Substring(nextPiece, c - nextPiece);
                    nextPiece = c + 1;
                }
            }

            yield return str.Substring(nextPiece);
        }

        public static IEnumerable<string> SplitCommandLine(string commandLine)
        {
            bool inQuotes = false;
            return commandLine.Split(c =>
            {
                if (c == '\"')
                    inQuotes = !inQuotes;

                return !inQuotes && c == ' ';
            })
                                .Select(arg => arg.Trim())
                                .Where(arg => !string.IsNullOrEmpty(arg));
        }
    }

    [Rule(Name="Clang", PageTemplate="tool", DisplayName="Clang", Order="200")]
    [DataSource(Persistence="ProjectFile", ItemType="ClangCompile")]
    [PropertyCategory(Name="General", DisplayName="General", Order = 0)]
    [PropertyCategory(Name = "Paths", DisplayName = "Paths", Order = 1)]
    [PropertyCategory(Name = "Language", DisplayName = "Language", Order = 2)]
    [PropertyCategory(Name = "Preprocessor", DisplayName = "Preprocessor", Order = 3)]
    [PropertyCategory(Name = "All Options", DisplayName = "All Options", Subtype = "Search", Order = 4)]
    [PropertyCategory(Name = "Command Line", DisplayName = "Command Line", Subtype = "CommandLine", Order = 5)]
    [FileExtension(Name="*.c", ContentType="ClangCpp")]
    [FileExtension(Name="*.cpp", ContentType="ClangCpp")]
    [FileExtension(Name="*.cc", ContentType="ClangCpp")]
    [FileExtension(Name="*.cxx", ContentType="ClangCpp")]
    [FileExtension(Name="*.m", ContentType="ClangObjCpp")]
    [FileExtension(Name="*.mm", ContentType="ClangObjCpp")]
    [ItemType(Name="ClangCompile", DisplayName="Clang source")]
    [ContentType(Name="ClangCpp", DisplayName="Clang C/C++", ItemType="ClangCompile")]
    [ContentType(Name = "ClangObjCpp", DisplayName = "Clang Objective C/C++", ItemType = "ClangCompile")]
    public class Clang : ToolTask
    {
        /// <summary>
        /// This class holds an item to be compiled by clang.
        /// </summary>
        class ClangItem
        {
            private Clang clangTask = null;
            private List<string> stdOut;
            private List<string> stdErr;

            public ITaskItem Item { get; private set; }
            public string ObjFileName { get; private set; }
            public string DepFileName { get; private set; }
            public string CommandLine { get; private set; }
            public int ExitCode { get; private set; }

            public ClangItem(Clang clangTask, ITaskItem item, string objFileName, string depFileName, string commandLine)
            {
                this.clangTask = clangTask;
                this.Item = item;
                this.ObjFileName = objFileName;
                this.DepFileName = depFileName;
                this.CommandLine = commandLine;
                this.stdOut = new List<string>();
                this.stdErr = new List<string>();
            }

            public void RunClang(string executable)
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = executable;
                startInfo.Arguments = this.CommandLine;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;

                string stdOutString = null;
                string stdErrString = null;

                Process process = Process.Start(startInfo);

                // Wait for the program to complete as we record all of its StdOut and StdErr
                Parallel.Invoke(
                    () => { stdOutString = process.StandardOutput.ReadToEnd(); },
                    () => { stdErrString = process.StandardError.ReadToEnd(); }
                    );

                process.WaitForExit();

                ExitCode = process.ExitCode;
                if (!string.IsNullOrEmpty(stdOutString))
                {
                    this.stdOut = (stdOutString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList();
                }

                if (!string.IsNullOrEmpty(stdErrString))
                {
                    this.stdErr = (stdErrString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList();
                }
            }

            public void LogOutput()
            {
                clangTask.LogEventsFromTextOutput(this.Item.ItemSpec, MessageImportance.High);

                for (int i = 0; i < this.stdOut.Count; i++)
                {
                    clangTask.LogEventsFromTextOutput(this.stdOut[i], MessageImportance.Normal);
                }

                for (int i = 0; i < this.stdErr.Count; i++)
                {
                    clangTask.LogEventsFromTextOutput(this.stdErr[i], MessageImportance.Normal);
                }
            }
        }

        // This is only used to output our .tlog files at a logical time, after the end of a build.
        class TLogWriter : IDisposable
        {
            public readonly static string cacheKey = "ClangTaskTLogWriter";

            // Tracker has an AppDomain lifetime, so our cache should never be deleted before it.
            DependencyTracker tracker;

            public TLogWriter(DependencyTracker t)
            {
                tracker = t;
            }

            public void Dispose()
            {
                foreach (var file in tracker.cachedTlogMaps)
                {
                    StreamWriter sw = null;
                    try
                    {
                        // Write all the tlog files out to disk.
                        sw = new StreamWriter(File.Open(file.Key, FileMode.Create));

                        foreach (var val in file.Value)
                        {
                            sw.WriteLine("^" + val.Key);
                            foreach (string line in val.Value) {
                                sw.WriteLine(line);
                            }
                        }

                        sw.Close();
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("Error writing TLog file: {0}", (object)file.Key);
                        if (sw != null)
                        {
                            sw.Close();
                        }
                    }
                }
            }
        }

        DependencyTracker Tracker
        {
            get
            {
                if (BuildEngine4 != null)
                {
                    tracker = (DependencyTracker)BuildEngine4.GetRegisteredTaskObject(DependencyTracker.cacheKey, RegisteredTaskObjectLifetime.AppDomain);
                }

                if (tracker == null)
                {
                    tracker = new DependencyTracker();

                    if (BuildEngine4 != null)
                    {
                        BuildEngine4.RegisterTaskObject(DependencyTracker.cacheKey, tracker, RegisteredTaskObjectLifetime.AppDomain, false);
                    }
                }

                return tracker;
            }
        }

        TLogWriter TLogs
        {
            get
            {
                if (BuildEngine4 != null)
                {
                    tlogWriter = (TLogWriter)BuildEngine4.GetRegisteredTaskObject(TLogWriter.cacheKey, RegisteredTaskObjectLifetime.Build);
                }

                if (tlogWriter == null)
                {
                    tlogWriter = new TLogWriter(Tracker);

                    if (BuildEngine4 != null)
                    {
                        BuildEngine4.RegisterTaskObject(TLogWriter.cacheKey, tlogWriter, RegisteredTaskObjectLifetime.Build, false);
                    }
                }
                return tlogWriter;
            }
        }

        TLogWriter tlogWriter;
        static DependencyTracker tracker;

        // CanonicalTrackedInputFiles' caching behaviour isn't good enough. Visual Studio watches the filesystem
        // with vigour, so we'll do the same thing.
        // This has an app object lifetime, so from Visual Studio our incremental builds will be fast, but commandline
        // builds with be comparable to CL.
        class DependencyTracker
        {
            public static readonly string cacheKey = "ClangCompileDependencyTracker";
            public Dictionary<string, Dictionary<string, List<string>>> cachedTlogMaps = new Dictionary<string, Dictionary<string, List<string>>>();

            // Only use canonical paths please.
            DateTime GetModDate(string path)
            {
                if (!cachedFileModDates.ContainsKey(path))
                {
                    try
                    {
                        // Todo: Consider moving to using directories instead?
                        FileSystemWatcher w = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
                        w.Changed += WatchedFileChanged;
                        w.Renamed += WatchedFileRenamed;
                        w.Deleted += WatchedFileDeleted;
                        w.EnableRaisingEvents = true;
                        watcher.Add(w);

                        cachedFileModDates[path] = File.GetLastWriteTime(path);
                    } catch (Exception) {
                        // File likely doesn't exist, possibly from an old .tlog, or a moved project.
                        // The watcher likely died at this point, so don't cache the date, since we'll probably want to retry later.
                        return DateTime.MinValue;
                    }
                }

                return cachedFileModDates[path];
            }

            void WatchedFileRenamed(object sender, RenamedEventArgs e)
            {
                GetModDate(e.FullPath); // Track the 'new' file
                SetOutOfDate(e.FullPath);
                SetOutOfDate(e.OldFullPath);
            }

            void WatchedFileDeleted(object sender, FileSystemEventArgs e)
            {
                SetOutOfDate(e.FullPath);
                needsRebuilding[e.FullPath] = true;
            }

            void WatchedFileChanged(object sender, FileSystemEventArgs e)
            {
                switch(e.ChangeType) {
                    case WatcherChangeTypes.Created:
                        GetModDate(e.FullPath); // Track the new file
                        SetOutOfDate(e.FullPath);
                        break;
                    case WatcherChangeTypes.Changed:
                        SetOutOfDate(e.FullPath);
                        break;
                    default:
                        // see w_Renamed
                        break;
                }
            }

            public void SetDependencies(string source, List<string> deps)
            {
                dependencies.Remove(source);
                dependencies[source] = deps;
                GetModDate(source); // Start tracking the files

                // Clear old updates
                foreach (List<string> updateList in updates.Values)
                {
                    updateList.Remove(source);
                }

                // Add them back
                foreach (var dep in deps)
                {
                    if (!updates.Keys.Contains(dep))
                    {
                        updates[dep] = new List<string>();
                    }
                    GetModDate(dep);
                    updates[dep].Add(source);
                }
            }

            public void SetUpToDate(string file, bool upToDate = true)
            {
                needsRebuilding[file] = !upToDate;
            }

            void SetOutOfDate(string file, int nTries = 2)
            {
                List<string> updateList;
                if (nTries > 0 && updates.TryGetValue(file, out updateList))
                {
                    foreach (string updFile in updateList)
                    {
                        needsRebuilding[updFile] = true;
                        SetOutOfDate(updFile, --nTries);
                    }
                }

            }

            DateTime GetNewestInTreeInner(string file, int nTries = 2)
            {
                DateTime newest = GetModDate(file);
                List<string> deps;

                if (nTries > 0 && dependencies.TryGetValue(file, out deps))
                {
                    foreach (string depFile in deps)
                    {
                        DateTime depMod = GetNewestInTreeInner(depFile, --nTries);
                        if (depMod > newest)
                        {
                            newest = depMod;
                        }
                    }
                }

                return newest;
            }

            DateTime GetNewestInTree(string file)
            {
                DateTime newest = DateTime.MinValue;
                List<string> deps;

                if (dependencies.TryGetValue(file, out deps))
                {
                    foreach (string depFile in deps)
                    {
                        DateTime depMod = GetNewestInTreeInner(depFile);
                        if (depMod > newest)
                        {
                            newest = depMod;
                        }
                    }
                }

                return newest;
            }

            public bool OutOfDate(string file)
            {
                bool ret;
                if (needsRebuilding.TryGetValue(file, out ret))
                {
                    return ret;
                }

                if (!File.Exists(file))
                {
                    return true;
                }

                DateTime fileModDate;
                DateTime newestModDate;

                try
                {
                    fileModDate = GetModDate(file);
                    newestModDate = GetNewestInTree(file);
                }
                catch (Exception)
                {
                    // FileNotFoundException is never thrown, it just returns 00:00/1/1/1601 UTC
                    needsRebuilding[file] = true;
                    return true;
                }

                if (fileModDate > newestModDate)
                {
                    needsRebuilding[file] = false;
                    return false;
                }

                needsRebuilding[file] = true;
                return true;
           }

            List<FileSystemWatcher> watcher = new List<FileSystemWatcher>();

            Dictionary<string, DateTime> cachedFileModDates = new Dictionary<string,DateTime>();

            Dictionary<string, List<string>> dependencies = new Dictionary<string, List<string>>();
            Dictionary<string, List<string>> updates = new Dictionary<string,List<string>>(); // Bottom up view of dependencies.

            Dictionary<string, bool> needsRebuilding = new Dictionary<string, bool>();
        }

#region Private and utils
        void LogMessage(MessageImportance importance, string message, params object[] list)
        {
#if !LOWLEVEL_DEBUG
            if(importance == MessageImportance.High)
#endif
            {
                if (BuildEngine4 != null)
                {
                    Log.LogMessage(importance, message, list);
                }
            }
        }

        void LogWarning(string message, params object[] list)
        {
            if (BuildEngine4 != null)
            {
                Log.LogWarning(message, list);
            }
        }

        string DecorateFile(string path, string extension)
        {
            return Path.GetFileNameWithoutExtension(path) + "_" + Path.GetFullPath(path).GetHashCode().ToString("X") + extension;
        }

        string GetSpecial(string name, object value, ITaskItem input)
        {
            // ToLower is affected by localization. Need to be careful here.
            name = name.ToLower(new CultureInfo("en-US", false));

            if (value == null)
            {
                if (name == "inputfilename")
                {
                    return Path.GetFileName(input.ItemSpec);
                }
                else if (name == "inputabsdir")
                {
                    return Path.GetDirectoryName(Path.GetFullPath(input.ToString()));
                }
                else if (name == "dependencyfile")
                {
                    return GetSpecial("objectfilename", ObjectFileName, input) + ".d";
                }
            }

            if (name == "objectfilename")
            {
                if (value.ToString().Last() == '\\' || value.ToString().Last() == '/')
                {
                    return value + DecorateFile(input.ItemSpec, ".obj");
                }
            }
            else if (name == "input")
            {
                return GetFullPath(input.ToString());
            }

            return value == null ? null : value.ToString();
        }

        static string GetFullPath(string path)
        {
            if (path == null || path == "")
            {
                return "";
            }

            // Clang is not erroneously escaping quotes... per se. Windows allows quotes in filenames, but trims trailing whitespace.
            // eg. "C:\SomeDir\"SomeFile"" is a valid path. For clang to accept it you'd have to escape the filename quotes to "C:\SomeDir\\"SomeFile\""
            // "C:\SomeDir\" is not valid, since it thinks you're trying to refer to a file in SomeDir by the name of " [and subsequent arguments since we didn't match the quote]
            string fullPath = Path.GetFullPath(path);
            if (fullPath.EndsWith("\\"))
            {
                fullPath = fullPath.Substring(0, fullPath.Length - 1);
            }
            return "\"" + fullPath + "\"";
        }

        string GetClangExe()
        {
            return LLVMDirectory + @"\bin\clang.exe";
        }

        string GetClangResourceDir()
        {
            return LLVMDirectory + @"\lib\clang\" + LLVMClangVersion;
        }
        #endregion

        #region MSBuild Properties
        [PropertyPage(Visible = false, IncludeInCommandLine = false)]
        public string LLVMClangVersion
        {
            get
            {
                if(LLVMClangVersionValue == null || LLVMClangVersionValue == "")
                {
                    LogMessage(MessageImportance.Low, "Clang exe: {0}", GetClangExe());

                    ProcessStartInfo clangPsi = new ProcessStartInfo(GetClangExe(), @"-v");
                    Process clangVersionProc = new Process();

                    clangPsi.CreateNoWindow = true;
                    clangPsi.RedirectStandardError = true;
                    clangPsi.UseShellExecute = false;
                    clangVersionProc.StartInfo = clangPsi;
                    clangVersionProc.Start();
                    clangVersionProc.WaitForExit();

                    string versionString = clangVersionProc.StandardError.ReadToEnd();
                    LogMessage(MessageImportance.Low, "Clang version: {0}", versionString);
                    // clang's version output: clang with Microsoft CodeGen version <version number>
                    string version = versionString.Split(' ')[5];
                    LLVMClangVersion = version;
                }
                return LLVMClangVersionValue;
            }
            set
            {
                LLVMClangVersionValue = value;
            }
        }

        static string LLVMClangVersionValue;

        [PropertyPage(Visible = false, IncludeInCommandLine = false)]
        public string LLVMResourceDir
        {
            get
            {
                if (LLVMResourceDirValue == null || LLVMResourceDirValue == "")
                {
                    LLVMResourceDirValue = GetClangResourceDir();
                }
                return LLVMResourceDirValue;
            }
            set
            {
                LLVMResourceDirValue = value;
            }
        }

        string LLVMResourceDirValue;

        [Required]
        [PropertyPage(Visible = false, IncludeInCommandLine = false)]
        public string CommandTLogFile
        {
            get;
            set;
        }

        [Required]
        [PropertyPage(Visible = false, IncludeInCommandLine = false)]
        public string ProjectFile
        {
            get;
            set;
        }

        [Required]
        [PropertyPage(Visible = false, IncludeInCommandLine = false)]
        public string ReadTLogFile
        {
            get;
            set;
        }

        [Required]
        [PropertyPage(
          Category = "Command Line",
          Switch = "-c ",
          Visible = false)]
        [DataSource(
            Persistence = "ProjectFile",
            ItemType = "ClangCompile",
            SourceType = "Item")]
        public ITaskItem[] Input { get; set; }

        // Don't build the outputs, just create the output items.
        public bool Autocomplete { get; set; }

        public enum HeaderMapEnum
        {
            [Field(DisplayName="Disabled", Description="Disable use of header maps.")]
            Disabled,
            [Field(DisplayName="Project", Description="User a header map containing all headers in the VS project.")]
            Project,
            [Field(DisplayName = "Combined", Description = "User a header map containing all headers in the VS project, as well as any headers found in the same directory as the source files being compiled.")]
            Combined,
        }

        [PropertyPage(
            Category = "General",
            Description = "Specify type of header map to use.",
            DisplayName = "Use Header Map",
            IncludeInCommandLine = false)]
        [EnumeratedValue(Enumeration = typeof(HeaderMapEnum))]
        public string HeaderMap
        {
            get { return HeaderMapValue.ToString(); }
            set { HeaderMapValue = (HeaderMapEnum)Enum.Parse(typeof(HeaderMapEnum), value, true); }
        }

        HeaderMapEnum HeaderMapValue;

        [PropertyPage(
            DisplayName = "Framework-style header map entries",
            Description = "Add framework-style entries to header map.",
            Category = "General",
            IncludeInCommandLine = false)]
        public bool HeaderMapAddFrameworkEntries { get; set; }

        [PropertyPage(
            Category = "General",
            DisplayName = "Header Map Include",
            Description = "Header Map Include",
            Visible = false)]
        public string HeaderMapInclude { get; set; }

        public enum RuntimeLibraryEnum
        {
            [Field(DisplayName = "Multi-threaded", Description = "Causes your application to use the multithread, static version of the run-time library.", Switch = "-D_MT -Xclang --dependent-lib=libcmt -Xclang --dependent-lib=oldnames")]
            MultiThreaded,
            [Field(DisplayName = "Multi-threaded Debug", Description = "Defines _DEBUG and _MT. This option also causes the compiler to place the library name LIBCMTD.lib into the .obj file so that the linker will use LIBCMTD.lib to resolve external symbols.", Switch= "-D_DEBUG -D_MT -Xclang --dependent-lib=libcmtd -Xclang --dependent-lib=oldnames")]
            MultiThreadedDebug,
            [Field(DisplayName = "Multi-threaded DLL", Description = "Causes your application to use the multithread- and DLL-specific version of the run-time library. Defines _MT and _DLL and causes the compiler to place the library name MSVCRT.lib into the .obj file.", Switch = "-D_MT -D_DLL -Xclang --dependent-lib=msvcrt -Xclang --dependent-lib=oldnames")]
            MultiThreadedDLL,
            [Field(DisplayName = "Multi-threaded Debug DLL", Description = "Defines _DEBUG, _MT, and _DLL and causes your application to use the debug multithread- and DLL-specific version of the run-time library. It also causes the compiler to place the library name MSVCRTD.lib into the .obj file.", Switch = "-D_DEBUG -D_MT -D_DLL -Xclang --dependent-lib=msvcrtd -Xclang --dependent-lib=oldnames")]
            MultiThreadedDebugDLL
        }

        [PropertyPage(
            Category = "General",
            Description = "Specify runtime library for linking.",
            DisplayName = "Runtime Library")]
        [EnumeratedValue(Enumeration = typeof(RuntimeLibraryEnum))]
        public string RuntimeLibrary
        {
            get { return RuntimeLibraryValue.ToString(); }
            set { RuntimeLibraryValue = (RuntimeLibraryEnum)Enum.Parse(typeof(RuntimeLibraryEnum), value, true); }
        }

        RuntimeLibraryEnum RuntimeLibraryValue;

        public enum OptimizationLevelEnum {
            [Field(Switch="-O0", DisplayName="Disabled", Description="Disable optimization.")]
            Disabled,
            [Field(Switch="-Os", DisplayName="Optimize for size", Description="Medium level, with extra optimizations to reduce code size.")]
            MinSpace,
            [Field(Switch="-O2", DisplayName="Optimize for speed", Description="More optimizations.")]
            MaxSpeed,
            [Field(Switch="-O3", DisplayName="Maximum optimizations", Description="Even more optimizations.")]
            Full
        }

        [PropertyPage(
            Category="General",
            DisplayName="Optimization Level",
            Description="Select option for code optimization.")]
        [EnumeratedValue(Enumeration = typeof(OptimizationLevelEnum))]
        public string OptimizationLevel
        {
            get { return OptimizationLevelValue.ToString(); }
            set { OptimizationLevelValue = (OptimizationLevelEnum)Enum.Parse(typeof(OptimizationLevelEnum), value, true); }
        }

        OptimizationLevelEnum OptimizationLevelValue;

        [PropertyPage(
            DisplayName = "Debug Information",
            Description = "Specifies whether to keep debug information.",
            Category = "General",
            Switch = "-g")]
        public bool DebugInformation { get; set; }

        [PropertyPage(
            DisplayName = "Enable Exceptions",
            Description = "Specifies exception handling model to be used by the compiler for (Objective-)C++.",
            Category = "General",
            Switch = "-fexceptions")]
        public bool ExceptionHandling { get; set; }

        [PropertyPage(
            DisplayName = "Enable Objective-C ARC",
            Description = "Specifies whether to use Automatic Reference Counting.",
            Category = "General",
            Switch = "-fobjc-arc")]
        public bool ObjectiveCARC { get; set; }

        [PropertyPage(
            DisplayName = "Enable C and Objective-C Modules",
            Description = "Specifies whether to use Clang modules.",
            Category = "General",
            Switch = "-fmodules")]
        public bool ObjectiveCModules { get; set; }

        [PropertyPage(
            DisplayName = "Path to Objective-C modules",
            Description = "Path to the directory where the modules will be cached",
            Category = "General",
            Visible = false,
            Switch = "-fmodules-cache-path=")]
        [ResolvePath()]
        public string ObjectiveCModulesCachePath { get; set; }

        [PropertyPage(
            Category = "Paths",
            DisplayName = "Hidden SYSTEM include search paths",
            Description = "Hidden SYSTEM include search paths",
            Switch = "-isystem ",
            Visible = false)]
        [ResolvePath()]
        public string[] InternalSystemIncludePaths { get; set; }

        [PropertyPage(
            Category = "Paths",
            DisplayName = "Hidden include paths",
            Description = "Hidden include paths",
            Switch = "-I ",
            Visible = false)]
        [ResolvePath()]
        public string[] InternalIncludePaths { get; set; }

        [PropertyPage(
            Category = "Paths",
            DisplayName = "Hidden force inclusions",
            Description = "Hidden force inclusions",
            Switch = "-include ",
            Visible = false)]
        public string[] InternalForceIncludes { get; set; }

        [PropertyPage(
            Category = "Paths",
            DisplayName = "Excluded Search Path Subdirectories",
            Description = "Wildcard pattern for subdirectories to exclude from recursive search",
            IncludeInCommandLine = false)]
        public string[] ExcludedSearchPathSubdirectories
        {
            get { return ExcludedSearchPathSubdirectoriesValues; }
            set { ExcludedSearchPathSubdirectoriesValues = convertWildcardToRegEx(value); }
        }

        string[] ExcludedSearchPathSubdirectoriesValues;

        private static string[] convertWildcardToRegEx(string[] wildcardPaths)
        {
            List<string> patterns = new List<string>();

            foreach (string wildcard in wildcardPaths)
            {
                string pattern = Regex.Escape(wildcard);
                pattern = pattern.Replace("/", "\\\\");

                // Convert "*" to ".*", i.e. match any character except the path separator, zero or more times.
                pattern = pattern.Replace("\\*", "[^\\\\]*");

                // Convert "?" to ".", i.e. match exactly one character except the path separator.
                pattern = pattern.Replace("\\?", "[^\\\\]");

                patterns.Add(pattern + "$");
            }

            return patterns.ToArray();
        }

        private void dirSearch(string dirPath, ref List<string> outPaths)
        {
            int maxCount = outPaths.Count + 2048;
            outPaths.Add(dirPath);
            for (var i = outPaths.Count - 1; i < Math.Min(outPaths.Count, maxCount); i++)
            {
                try
                {
                    foreach (string d in Directory.GetDirectories(outPaths[i]))
                    {
                        bool excluded = false;
                        if (ExcludedSearchPathSubdirectories != null)
                        {
                            foreach (string pattern in ExcludedSearchPathSubdirectories)
                            {
                                if (Regex.IsMatch(d, pattern, RegexOptions.None))
                                {
                                    excluded = true;
                                    break;
                                }
                            }
                        }

                        if (!excluded)
                        {
                            outPaths.Add(d);
                        }
                    }
                }
                catch (System.Exception) { }
            }
        }

        private string[] expandPathGlobs(string[] inPaths)
        {
            List<string> outPaths = new List<string>();
            foreach (string path in inPaths)
            {
                string winPath = path.Replace('/', '\\');
                if (winPath.EndsWith("\\**"))
                    dirSearch(winPath.Substring(0, path.Length - 3), ref outPaths);
                else
                    outPaths.Add(winPath);
            }
            return outPaths.ToArray();
        }

        [PropertyPage(
            Category = "Paths",
            DisplayName = "User Include Paths",
            Description = "User header search paths.",
            Switch = "-iquote ")]
        [ResolvePath()]
        public string[] UserIncludePaths
        {
            get { return UserIncludePathsValue; }
            set { UserIncludePathsValue = expandPathGlobs(value); }
        }

        string[] UserIncludePathsValue;

        [PropertyPage(
            Category = "Paths",
            DisplayName = "Include Paths",
            Description = "Header search paths.",
            Switch = "-I")]
        [ResolvePath()]
        public string[] IncludePaths
        {
            get { return IncludePathsValue; }
            set { IncludePathsValue = expandPathGlobs(value); }
        }

        string[] IncludePathsValue;

        [PropertyPage(
            Category = "Paths",
            Subtype = "file",
            DisplayName = "Object File Name",
            Description = "Specifies a name to override the default object file name.",
            Switch = "-o ",
            IncludeInCommandLine = false)]
        [ResolvePath()]
        public string ObjectFileName { get; set; }

        [PropertyPage(
            Category = "Preprocessor",
            DisplayName = "Preprocessor Definitions",
            Description = "Define preprocessor symbols for your source files.",
            Switch = "-D")]
        public string[] PreprocessorDefinitions { get; set; }

        [PropertyPage(
            Category = "Preprocessor",
            DisplayName = "Undefine Preprocessor Definitions",
            Description = "Specifies one or more preprocessor undefines.",
            Switch = "-U")]
        public string[] UndefinePreprocessorDefinitions { get; set; }

        // This option needs to go BEFORE the file being compiled
        public enum CompileAsEnum
        {
            [Field(DisplayName = "Default", Description = "Default", Switch = "")]
            Default,
            [Field(DisplayName = "Compile as C Code", Description = "Compile as C Code", Switch = "-x c")]
            CompileAsC,
            [Field(DisplayName = "Compile as C++ Code", Description = "Compile as C++ Code", Switch = "-x c++")]
            CompileAsCpp,
            [Field(DisplayName = "Compile as Objective C Code", Description = "Compile as Objective C Code", Switch = "-x objective-c")]
            CompileAsObjC,
            [Field(DisplayName = "Compile as Objective C++ Code", Description = "Compile as Objective C++ Code", Switch = "-x objective-c++")]
            CompileAsObjCpp
        }

        [PropertyPage(
            Category = "Language",
            DisplayName = "Compile As",
            Description = "Select compile language for [Objective] C/C++ files.")]
        [EnumeratedValue(Enumeration = typeof(CompileAsEnum))]
        public string CompileAs
        {
            get { return CompileAsValue.ToString(); }
            set { CompileAsValue = (CompileAsEnum)Enum.Parse(typeof(CompileAsEnum), value, true); }
        }

        CompileAsEnum CompileAsValue;

        [PropertyPage(
            Category = "Language",
            DisplayName = "LLVM Directory",
            Description = "Use LLVM from this directory for compilation",
            IncludeInCommandLine = false)]
        public string LLVMDirectory { get; set; }

        [PropertyPage(
            Category = "General",
            Subtype = "file",
            DisplayName = "Prefix Header",
            Description = "Specifies prefix header file to be included when compiling all source files.",
            Switch = "-include ")]
        [ResolvePath()]
        public string[] PrefixHeader { get; set; }

        [PropertyPage(
            Category = "General",
            DisplayName = "Maximum Clang Processes",
            Description = "Specifies the maximum number of clang processes to run in parallel. The argument can be -1 or any positive integer. A positive property value limits the number of concurrent operations to the set value. If it is -1, there is no limit on the number of concurrently running operations.",
            IncludeInCommandLine = false)]
        public int MaxClangProcesses { get; set; }

        [PropertyPage(
            Category = "Language",
            DisplayName = "Other C Flags",
            Description = "Other C Flags",
            IncludeInCommandLine = false)]
        public string OtherCFlags { get; set; }

        [PropertyPage(
            Category = "Language",
            DisplayName = "Other C++ Flags",
            Description = "Other C++ Flags",
            IncludeInCommandLine = false)]
        public string OtherCPlusPlusFlags { get; set; }

        [PropertyPage(
            Category = "Language",
            DisplayName = "Language-specific flags",
            Description = "Language-specific flags",
            Visible = false)]
        public string OtherFlags { get; set; }

        [PropertyPage(
            Category = "Language",
            DisplayName = "Use WinObjC standard library",
            Description = "Uses the WinObjC standard C/C++ library definitions when compiling. This can create some compatibility issues with COM interfaces and Windows-specific source code.")]
        public Boolean WOCStdLib { get; set; }

        [PropertyPage(
            DisplayName = "Command Line",
            Visible = false,
            IncludeInCommandLine = false)]
        public string CommandLineTemplate { get; set; }

        public string AutocompleteCommandLineTemplate { get; set; }

        [Output]
        [PropertyPage(
            DisplayName = "Outputs",
            Visible = false,
            IncludeInCommandLine = false)]
        public ITaskItem[] Outputs { get; set; }

        [PropertyPage(
            Subtype = "AdditionalOptions",
            Category = "Command Line",
            DisplayName = "Additional Options",
            Description = "Additional Options",
            IncludeInCommandLine=false)]
        public string AdditionalOptions { get; set; }

        [PropertyPage(
            Category = "Preprocessor",
            DisplayName = "Dependency File",
            Description = "Specifies a name to override the default dependency file name.",
            Switch = "-MF ",
            IncludeInCommandLine = false)]
        [ResolvePath()]

        public string DependencyFile { get; set; }

        [PropertyPage(
            Category = "Preprocessor",
            DisplayName = "Use System Headers For Dependencies",
            Description = "Don't ignore system headers when calculating dependencies.",
            Switch = "-MD",
            ReverseSwitch = "-MMD")]
        public bool SystemHeaderDeps { get; set; }
        #endregion

        #region ToolTask Overrides
        // ToLower() is affected by localization.
        // Be VERY careful when adding static strings to the dictionary, since lookup is also done with ToLower.
        static Dictionary<string, PropertyInfo> AllProps = typeof(Clang).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).ToDictionary(x => x.Name.ToLower());

        protected override string GenerateFullPathToTool()
        {
            return GetClangExe();
        }

        protected override string ToolName
        {
            get { return "clang.exe"; }
        }

        private string ReplaceOptions(string commandLine, ITaskItem input)
        {
            Match subst = Regex.Match(commandLine, @"\[\w+\]", RegexOptions.IgnoreCase);

            while (subst.Success)
            {
                string autoSubst = subst.Value.Substring(1, subst.Value.Length - 2);
                string substStr = "";

                LogMessage(MessageImportance.Low, "Replace value: {0}", autoSubst);

                PropertyInfo pInfo;
                if (AllProps.TryGetValue(autoSubst.ToLower(), out pInfo))
                {
                    ResolvePathAttribute pathAttr = (ResolvePathAttribute)Attribute.GetCustomAttribute(pInfo, typeof(ResolvePathAttribute));
                    PropertyPageAttribute ppAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(pInfo, typeof(PropertyPageAttribute));
                    string propSwitch = ppAttr.Switch;
                    object value = pInfo.GetValue(this);
                    string propVal = GetSpecial(autoSubst, value, input);

                    if (propVal != null && propVal != "")
                    {
                        if (propSwitch != null && propSwitch != "")
                        {
                            substStr += propSwitch;
                        }
                        if (pathAttr != null)
                        {
                            try
                            {
                                substStr += GetFullPath(propVal);
                            }
                            catch (Exception)
                            {
                                LogWarning(string.Format("Unable to resolve path {0} for property: {1}", value.ToString(), pInfo.Name));
                            }
                        }
                        else
                        {
                            substStr += propVal;
                        }
                    }
                }
                else
                {
                    Log.LogError("Only [Input] [AllOptions] [AdditionalOptions] and task properties are acceptped substitutions for command line arguments; Unknown expansion: " + autoSubst);
                    return null;
                }

                commandLine = commandLine.Replace(subst.Value, substStr);
                subst = subst.NextMatch();
            }

            LogMessage(MessageImportance.Low, "Commandline: {0}", commandLine);

            // NOTE: See GetFullPath about escaping quotes.
            return commandLine;
        }

        protected override string GenerateCommandLineCommands()
        {
            return GenerateCommandLineCommands(CommandLineTemplate);
        }

        protected string GenerateCommandLineCommands(string template)

        {
            string commandToRun = template;
            Match subst = Regex.Match(commandToRun, @"\[alloptions\]", RegexOptions.IgnoreCase);

            if (subst.Success)
            {
                string autoSubst = subst.Value.Substring(1, subst.Value.Length - 2);
                string substStr = "";

                LogMessage(MessageImportance.Low, "Replacing all options");
                foreach (PropertyInfo pInfo in AllProps.Values)
                {
                    PropertyPageAttribute ppAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(pInfo, typeof(PropertyPageAttribute));
                    EnumeratedValueAttribute enumAttr = (EnumeratedValueAttribute)Attribute.GetCustomAttribute(pInfo, typeof(EnumeratedValueAttribute));
                    ResolvePathAttribute pathAttr = (ResolvePathAttribute)Attribute.GetCustomAttribute(pInfo, typeof(ResolvePathAttribute));

                    if (ppAttr == null)
                    {
                        LogMessage(MessageImportance.Low, "Skipping {0}", pInfo.Name);
                        continue;
                    }

                    if (!ppAttr.IncludeInCommandLine)
                    {
                        LogMessage(MessageImportance.Low, "Excluding {0}", pInfo.Name);
                        continue;
                    }

                    if (enumAttr != null)
                    {
                        FieldInfo fInfo = enumAttr.Enumeration.GetField((string)pInfo.GetValue(this));
                        FieldAttribute fAttr = (FieldAttribute)Attribute.GetCustomAttribute(fInfo, typeof(FieldAttribute));

                        if (fAttr.Switch == null || fAttr.Switch == "")
                        {
                            continue;
                        }

                        LogMessage(MessageImportance.Low, "Field({0}) switch: {1}", fInfo.Name, fAttr.Switch);
                        substStr += fAttr.Switch + " ";
                    }
                    else
                    {
                        if (pInfo.PropertyType.IsAssignableFrom(typeof(string[])))
                        {
                            string concatStr = ppAttr.Switch;
                            string[] propVal = (string[])pInfo.GetValue(this);

                            LogMessage(MessageImportance.Low, "String array({0}) switch: {1}", pInfo.Name, concatStr);

                            if (propVal != null)
                            {
                                foreach (var item in propVal)
                                {
                                    if (pathAttr != null) // Just awful.
                                    {
                                        try
                                        {
                                            substStr += concatStr + GetFullPath((string)item) + " ";
                                        }
                                        catch (Exception)
                                        {
                                            LogWarning(string.Format("Unable to resolve path {0} for property: {1}", item, pInfo.Name));
                                        }
                                    }
                                    else
                                    {
                                        substStr += concatStr + item + " ";
                                    }
                                    // substStr += string.Join(" ", Array.ConvertAll<string, string>(propVal, new Converter<string, string>(delegate(string x) { return concatStr + " " + x; }))) + " ";
                                }
                            }
                        }
                        else if (pInfo.PropertyType.IsAssignableFrom(typeof(bool)))
                        {
                            object propVal = pInfo.GetValue(this);
                            string cmdStr = propVal.ToString();
                            string cmdSwitch = (bool)propVal ? ppAttr.Switch : ppAttr.ReverseSwitch;

                            if (cmdSwitch != null && cmdSwitch != "")
                            {
                                LogMessage(MessageImportance.Low, "Bool({0}) switch: {1}", pInfo.Name, cmdSwitch);
                                substStr += cmdSwitch + " ";
                            }
                            else if ((bool)propVal)
                            {
                                LogWarning("Boolean is visible, but has no switch: {0}", pInfo.Name);
                            }
                        }
                        else if (pInfo.PropertyType.IsAssignableFrom(typeof(string)))
                        {
                            object propVal = pInfo.GetValue(this);

                            if (propVal != null && (string)propVal != "")
                            {
                                LogMessage(MessageImportance.Low, "String({0}) prop: {1}", pInfo.Name, (string)propVal);
                                if (ppAttr.Switch != null && ppAttr.Switch != "")
                                {
                                    substStr += ppAttr.Switch;
                                }
                                if (pathAttr != null) // Just awful.
                                {
                                    try
                                    {
                                        substStr += GetFullPath((string)propVal) + " ";
                                    }
                                    catch (Exception)
                                    {
                                        LogWarning(string.Format("Unable to resolve path {0} for property: {1}", propVal, pInfo.Name));
                                    }
                                }
                                else
                                {
                                    substStr += (string)propVal + " ";
                                }
                            }
                        }
                    }
                }

                commandToRun = commandToRun.Replace(subst.Value, substStr);
            }

            LogMessage(MessageImportance.Low, "Commandline: {0}", commandToRun);

            // NOTE: See GetFullPath about escaping quotes.
            return commandToRun;
        }

        protected override bool SkipTaskExecution()
        {
            if (Autocomplete)
            {
                return false;
            }

            // We need to wait until all the mod dates have been set before moving on, or we may get a race condition.
            object modDateSync = new object();
            int nModDate = 0;
            bool skip = true;

            // Instantiate the writer.
            TLogWriter writer = TLogs;

            if (!Tracker.cachedTlogMaps.ContainsKey(Path.GetFullPath(ReadTLogFile)))
            {
                var deps = ReadTLog(Path.GetFullPath(ReadTLogFile));
                var outs = ReadTLog(Path.GetFullPath(ReadTLogFile.Replace("read", "write")));
                foreach (var dep in deps)
                {
                    Tracker.SetDependencies(dep.Key, dep.Value);
                }
                foreach (var output in outs)
                {
                    Tracker.SetDependencies(output.Value[0], new List<string>() { output.Key }); // Only one output per file
                }
            }

            Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f =>
                {
                    TaskItem i = new TaskItem(f);
                    i.ItemSpec = GetSpecial("objectfilename", ObjectFileName, i);
                    i.SetMetadata("ObjectFileName", i.ItemSpec);
                    return i;
                }));

            foreach (ITaskItem item in Input)
            {
                string inputFileName = Path.GetFullPath(item.ItemSpec);
                string objFileName = Path.GetFullPath(GetSpecial("objectfilename", ObjectFileName, item));
                string depFileName = Path.GetFullPath(GetSpecial("dependencyfile", DependencyFile, item));

                WaitCallback waitCallback = new WaitCallback(f =>
                {
                    try
                    {
                        File.SetLastWriteTime(objFileName, DateTime.Now);
                        if (File.Exists(depFileName))
                        {
                            File.SetLastWriteTime(depFileName, DateTime.Now);
                        }
                    }
                    catch (Exception e)
                    {
                        LogWarning("Caught exception trying to set last modification: {0}", e.ToString());
                    }

                    lock (modDateSync) {
                        if (--nModDate == 0) {
                            Monitor.Pulse(modDateSync);
                        }
                    }
                });

                if (tracker.OutOfDate(objFileName))
                {
                    skip = false;
                    continue;
                }

                if (!File.Exists(objFileName))
                {
                    tracker.SetUpToDate(objFileName, false);
                    skip = false;
                    continue;
                }

                if (File.GetLastWriteTime(ProjectFile) < File.GetLastWriteTime(objFileName))
                {
                    // Touch the file so MSBuild is happy.
                    lock (modDateSync) {
                        nModDate++;
                    }

                    ThreadPool.QueueUserWorkItem(waitCallback);
                    continue;
                }
                else
                {
                    Dictionary<string, List<string>> cmdMap = ReadTLog(Path.GetFullPath(CommandTLogFile));
                    List<string> cmdLine;

                    // If the commandlines are different, rebuild.
                    if (cmdMap.TryGetValue(inputFileName, out cmdLine))
                    {
                        if (cmdLine.First().Substring(1) == ReplaceOptions(GenerateCommandLineCommands(), item))
                        {
                            // Touch the file so MSBuild is happy.
                            lock (modDateSync) {
                                nModDate++;
                            }

                            ThreadPool.QueueUserWorkItem(waitCallback);
                            continue;
                        }
                        else
                        {
                            tracker.SetUpToDate(objFileName, false);
                        }
                    }
                }

                skip = false;
            }

            lock (modDateSync) {
                if (nModDate > 0) {
                    Monitor.Wait(modDateSync);
                }
            }

            return skip;
        }

        protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
        {
            int retCode = 0;

            if (Autocomplete)
            {
                Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f =>
                {
                    TaskItem i = new TaskItem(f);
                    i.SetMetadata("ObjectFileName", GetSpecial("objectfilename", ObjectFileName, i));
                    i.SetMetadata("AutocompleteCommand", ReplaceOptions(GenerateCommandLineCommands(AutocompleteCommandLineTemplate), f));
                    return i;
                }));
                return 0;
            }
            else
            {
                Outputs = Array.ConvertAll<ITaskItem, ITaskItem>(Input, new Converter<ITaskItem, ITaskItem>(f =>
                {
                    TaskItem i = new TaskItem(f);
                    i.ItemSpec = GetSpecial("objectfilename", ObjectFileName, i);
                    i.SetMetadata("ObjectFileName", i.ItemSpec);
                    return i;
                }));
            }

            List<ClangItem> clangItems = new List<ClangItem>(Input.Length);
            for (int i = 0; i < Input.Length; i++)
            {
                ITaskItem item = Input[i];
                string objFileName = Path.GetFullPath(GetSpecial("objectfilename", ObjectFileName, item));
                string depFileName = Path.GetFullPath(GetSpecial("dependencyfile", DependencyFile, item));

                if (File.Exists(objFileName) && !tracker.OutOfDate(objFileName))
                {
                    continue;
                }

                string commandLine = ReplaceOptions(commandLineCommands, item);
                clangItems.Add(new ClangItem(this, item, objFileName, depFileName, commandLine));
            }

            if ((MaxClangProcesses > 1) || (MaxClangProcesses == -1))
            {
                Parallel.ForEach(clangItems, new ParallelOptions { MaxDegreeOfParallelism = MaxClangProcesses }, (clangItem) =>
                {
                    clangItem.RunClang(pathToTool);
                    lock (this)
                    {
                        clangItem.LogOutput();
                    }
                });
            }
            else
            {
                for(int i=0;i<clangItems.Count; i++)
                {
                    clangItems[i].RunClang(pathToTool);
                    clangItems[i].LogOutput();
                    if (clangItems[i].ExitCode != 0)
                    {
                        //Note: this break is for backward compatibility.  We would previously return on the first file that failed to compile correctly.
                        break;
                    }
                }
            }

            for (int i = 0; i < clangItems.Count; i++)
            {
                ClangItem clangItem = clangItems[i];
                retCode |= clangItem.ExitCode;

                string inputFullPath = Path.GetFullPath(clangItem.Item.ItemSpec);

                ReadTLog(Path.GetFullPath(CommandTLogFile))[inputFullPath] = new List<string>() { clangItem.CommandLine };

                if (clangItem.ExitCode == 0)
                {
                    if (File.Exists(clangItem.DepFileName))
                    {
                        List<string> deps = ReadDependencyFile(clangItem.DepFileName);
                        if (deps != null)
                        {
                            // Should we do anything special if we fail to parse the dependency file?
                            // As it stands now, if we fail the object file will not be up to date, and it will continute to be built.
                            Tracker.SetDependencies(inputFullPath, deps);
                            Tracker.SetUpToDate(clangItem.ObjFileName);
                        }
                        Tracker.SetDependencies(clangItem.ObjFileName, new List<string>() { inputFullPath });
                    }
                }
                else
                {
                    tracker.SetUpToDate(inputFullPath, false); // Probably an invalid object file, if it exists.
                    if ((MaxClangProcesses > 1) || (MaxClangProcesses == -1))
                    {
                        //Note: this return is for backward compatibility.  We would previously return on the first file that failed to compile correctly.
                        return retCode;
                    }
                }
            }
            return retCode;
        }

#endregion

        List<string> ReadDependencyFile(string file)
        {
            StreamReader sr = null;

            if (!File.Exists(file))
            {
                return null;
            }

            List<string> deps = new List<string>();

            try
            {
                sr = new StreamReader(File.Open(file, FileMode.Open));

                Regex matchDep = new Regex(@"((\\\s|\S)+)");
                string curLine = null;
                string sourceFile = null;
                string outputFile = null;

                // First line has the object file, everything before the ':'
                // The first dependency is the source file
                // The rest is a list of header files we depend on. The line ends with " \\\cl\rf"

                while ((curLine = sr.ReadLine()) != null)
                {
                    if(curLine.Contains(@": ")) {
                        outputFile = curLine.Substring(0, curLine.IndexOf(@": "));
                        curLine = curLine.Substring(curLine.IndexOf(@": ") + 1);
                    }

                    // Cull the trailed slash
                    if (curLine[curLine.Length - 1] == '\\')
                    {
                        curLine = curLine.Substring(0, curLine.Length - 2);
                    }

                    Match depMatch = matchDep.Match(curLine);

                    while (depMatch.Success)
                    {
                        // Replace escaped spaces
                        string value = depMatch.Groups[0].Value.Replace("\\ ", " ").Replace("/", "\\");

                        if (sourceFile == null)
                        {
                            sourceFile = value;
                            ReadTLog(Path.GetFullPath(ReadTLogFile))[sourceFile] = deps;
                            if (outputFile == null)
                            {
                                LogWarning("Output file not found in dependency file ({0})", file);
                            }
                            else
                            {
                                ReadTLog(Path.GetFullPath(ReadTLogFile.Replace("read", "write")))[sourceFile] = new List<string>() { outputFile, file };
                            }
                        }
                        else
                        {
                            deps.Add(value);
                        }

                        depMatch = depMatch.NextMatch();
                    }
                }
            }
            catch (Exception e)
            {
                LogWarning("Caught exception reading dependency file: " + e.ToString());
            }

            if (sr != null)
            {
                sr.Close();
            }

            return deps;
        }

        Dictionary<string, List<string>> ReadTLog(string file)
        {
            if (Tracker.cachedTlogMaps.ContainsKey(file))
            {
                return Tracker.cachedTlogMaps[file];
            }

            Dictionary<string, List<string>> retMap = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
            StreamReader sr = null;

            if (!File.Exists(file))
            {
                Tracker.cachedTlogMaps[file] = retMap;
                return retMap;
            }

            try
            {
                sr = new StreamReader(File.Open(file, FileMode.Open));
                string curLine = null;
                string keyVal = null;

                while ((curLine = sr.ReadLine()) != null)
                {
                    if (curLine[0] == '^')
                    {
                        keyVal = curLine.Substring(1);
                        retMap.Add(keyVal, new List<string>());
                    }
                    else
                    {
                        if (keyVal == null)
                        {
                            // We got ourselves a malformed tlog. Throw it out.
                            LogWarning("TLog file is malformed.");
                            retMap = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
                            break;
                        }
                        retMap[keyVal].Add(curLine);
                    }
                }
            }
            catch (Exception e)
            {
                LogWarning("Caught exception reading TLog: {0}", e.ToString());
            }

            if (sr != null)
            {
                sr.Close();
            }

            Tracker.cachedTlogMaps[file] = retMap;

            return retMap;
        }
    }
}


text:
<?php

namespace nabu\data\commerce;
use nabu\core\CNabuEngine;
use nabu\core\exceptions\ENabuCoreException;
use nabu\data\commerce\base\CNabuCommerceListBase;
use nabu\data\customer\CNabuCustomer;

/**
 * @author Rafael Gutierrez <rgutierrez@nabu-3.com>
 * @version 3.0.0 Surface
 * @package \nabu\data\lang
 */
class CNabuCommerceList extends CNabuCommerceListBase
{
    /**
     * Customer owner instance
     * @var CNabuCustomer
     */
    private $nb_customer;

    /**
     * Creates the instance. Receives as parameter the Customer instance that owns these Commerce List.
     * @param CNabuCustomer $nb_customer Customer owner instance.
     */
    public function __construct(CNabuCustomer $nb_customer = null)
    {
        parent::__construct();

        $this->nb_customer = $nb_customer;
    }

    public function acquireItem($key, $index = false)
    {
        if (!($item = parent::acquireItem($key, $index)) && CNabuEngine::getEngine()->isMainDBAvailable()) {
            switch ($index) {
                case self::INDEX_KEY:
                    $item = CNabuCommerce::findByKey($this->nb_customer, $key);
                    throw new ENabuCoreException(ENabuCoreException::ERROR_FEATURE_NOT_IMPLEMENTED);
                    break;
            }
        }

        return $item;
    }
}


text:
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.stuartwarren</groupId>
  <artifactId>instrumentit</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>InstrumentIt</name>
  <description>Monitor the metrics of your application</description>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <scm>
    <url>https://github.com/stuart-warren/instrumentit</url>
    <connection>scm:git:https://github.com/stuart-warren/instrumentit.git</connection>
    <developerConnection>scm:git:https://github.com/stuart-warren/instrumentit.git</developerConnection>
  </scm>

  <developers>
    <developer>
      <id>stuart-warren</id>
      <name>Stuart Warren</name>
      <email>stuart@stuartwarren.com</email>
    </developer>
  </developers>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.7.4</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.7.4</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <archive>
            <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.7.4</version>
            <scope>compile</scope>
          </dependency>
        </dependencies>
        <configuration>
          <complianceLevel>1.7</complianceLevel>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.1</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <finalName>uber-${project.artifactId}-${project.version}</finalName>
          <artifactSet>
            <excludes>
              <exclude>org.aspectj:aspectjrt</exclude>
            </excludes>
          </artifactSet>
        </configuration>
      </plugin>
    </plugins>
    <pluginManagement>
    	<plugins>
    		<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
    		<plugin>
    			<groupId>org.eclipse.m2e</groupId>
    			<artifactId>lifecycle-mapping</artifactId>
    			<version>1.0.0</version>
    			<configuration>
    				<lifecycleMappingMetadata>
    					<pluginExecutions>
    						<pluginExecution>
    							<pluginExecutionFilter>
    								<groupId>org.codehaus.mojo</groupId>
    								<artifactId>
    									aspectj-maven-plugin
    								</artifactId>
    								<versionRange>[1.6,)</versionRange>
    								<goals>
    									<goal>compile</goal>
    								</goals>
    							</pluginExecutionFilter>
    							<action>
    								<ignore></ignore>
    							</action>
    						</pluginExecution>
    					</pluginExecutions>
    				</lifecycleMappingMetadata>
    			</configuration>
    		</plugin>
    	</plugins>
    </pluginManagement>
  </build>

  <distributionManagement>
    <repository>
      <uniqueVersion>false</uniqueVersion>
      <id>sonatype-nexus-releases</id>
      <name>StuartWarren Repository</name>
      <url>http://nexus.stuartwarren.com/nexus/content/repositories/releases/</url>
      <layout>default</layout>
    </repository>
    <snapshotRepository>
      <uniqueVersion>true</uniqueVersion>
      <id>sonatype-nexus-snapshots</id>
      <name>StuartWarren Snapshots</name>
      <url>http://nexus.stuartwarren.com/nexus/content/repositories/snapshots/</url>
      <layout>default</layout>
    </snapshotRepository>
  </distributionManagement>

</project>


text:
package org.jzy3d.plot2d.primitive;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import org.jzy3d.colors.Color;
import org.jzy3d.colors.ColorMapper;
import org.jzy3d.colors.colormaps.IColorMap;
import org.jzy3d.plot3d.primitives.axes.layout.providers.ITickProvider;
import org.jzy3d.plot3d.primitives.axes.layout.renderers.ITickRenderer;

/**
 * @author Martin Pernollet
 */
public class ColorbarImageGenerator {
	public ColorbarImageGenerator(IColorMap map, float min, float max, ITickProvider provider, ITickRenderer renderer){
		mapper = new ColorMapper(map, min, max);
		this.min = min;
		this.max = max;
		this.provider = provider;
		this.renderer = renderer;
	}

	public ColorbarImageGenerator(ColorMapper mapper, ITickProvider provider, ITickRenderer renderer){
		this(mapper.getColorMap(), mapper.getZMin(), mapper.getZMax(), provider, renderer);
	}

	/** Renders the {@link ColorbarImageGenerator} to an image. */
	public Image toImage(int width, int height){
		int barWidth = 20;

		if(barWidth>width)
			return null;

		// Init image output
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D graphic = image.createGraphics();

		int txtSize=12;
		graphic.setFont(new java.awt.Font("Arial",0,txtSize)); //Text for the numbers in the ColorBar is Size=12

		// Draw background
		if(hasBackground){
			graphic.setColor(backgroundColor);
			graphic.fillRect(0, 0, width, height);
		}

		// Draw colorbar centering in half the Legend text height
		for(int h=txtSize/2; h<=(height-txtSize/2); h++){
			// Compute value & color
			float v = min + (max-min) * ((float)h)/((float)(height-txtSize));
//			Color c = mapper.getColor(new Coord3d(0,0,v));
			Color c = mapper.getColor(v);  //To allow the Color to be a variable independent of the coordinates

			// Draw line
			graphic.setColor(c.awt());
			graphic.drawLine(0, height-h, barWidth, height-h);
		}

		// Contour of bar
		graphic.setColor(foregroundColor);
		graphic.drawRect(0, txtSize/2, barWidth, height-txtSize);

		// Text annotation
		float[] ticks = provider.generateTicks(min, max);
		float ypos;
		String txt;
		for(int t=0; t<ticks.length; t++){
//			ypos = (int)(height-height*((ticks[t]-min)/(max-min)));
			ypos = (int)txtSize+(height-txtSize-(height-txtSize)*((ticks[t]-min)/(max-min))); //Making sure that the first and last tick appear in the colorbar
			txt = renderer.format(ticks[t]);
			graphic.drawString(txt, barWidth+1, ypos);
		}

		return image;
	}

	/*********************************************************************/

	public boolean hasBackground() {
		return hasBackground;
	}

	public void setHasBackground(boolean hasBackground) {
		this.hasBackground = hasBackground;
	}

	public Color getBackgroundColor() {
		return new Color(backgroundColor);
	}

	public void setBackgroundColor(Color backgroundColor) {
		this.backgroundColor = backgroundColor.awt();
	}

	public Color getForegroundColor() {
		return new Color(foregroundColor);
	}

	public void setForegroundColor(Color foregroundColor) {
		this.foregroundColor = foregroundColor.awt();
	}

	/*********************************************************************/

	protected ColorMapper mapper;
	protected ITickProvider provider;
	protected ITickRenderer renderer;
	protected float min;
	protected float max;
	protected boolean hasBackground = false;
	protected java.awt.Color backgroundColor;
	protected java.awt.Color foregroundColor = java.awt.Color.BLACK;

	public static final int MIN_BAR_WIDTH  = 100;
	public static final int MIN_BAR_HEIGHT = 100;
}


text:
using System;
using System.Collections.Generic;

using SchoolSystem.Cli.Core.Contracts;
using SchoolSystem.Cli.Models.Contracts;

namespace SchoolSystem.Cli.Core
{
    public class Engine
    {
        private const string TerminationCommand = "End";
        private const string NullProvidersExceptionMessage = "cannot be null.";

        private readonly IReader reader;
        private readonly IWriter writer;
        private readonly IParser parser;

        /* Could also extract Database provider for Teachers and Students collections
           But it will become too complex for the purposes of this exam */

        public Engine(IReader readerProvider, IWriter writerProvider, IParser parserProvider)
        {
            if (readerProvider == null)
            {
                throw new ArgumentNullException($"Reader {NullProvidersExceptionMessage}");
            }

            if (writerProvider == null)
            {
                throw new ArgumentNullException($"Writer {NullProvidersExceptionMessage}");
            }

            if (parserProvider == null)
            {
                throw new ArgumentNullException($"Parser {NullProvidersExceptionMessage}");
            }

            this.reader = readerProvider;
            this.writer = writerProvider;
            this.parser = parserProvider;

            Teachers = new Dictionary<int, ITeacher>();
            Students = new Dictionary<int, IStudent>();
        }

        public static IDictionary<int, ITeacher> Teachers { get; set; }

        public static IDictionary<int, IStudent> Students { get; set; }

        public void Start()
        {
            while (true)
            {
                try
                {
                    var commandAsString = this.reader.ReadLine();

                    if (commandAsString == TerminationCommand)
                    {
                        break;
                    }

                    this.ProcessCommand(commandAsString);
                }
                catch (Exception ex)
                {
                    this.writer.WriteLine(ex.Message);
                }
            }
        }

        private void ProcessCommand(string commandAsString)
        {
            if (string.IsNullOrWhiteSpace(commandAsString))
            {
                throw new ArgumentNullException("Command cannot be null or empty.");
            }

            var command = this.parser.ParseCommand(commandAsString);
            var parameters = this.parser.ParseParameters(commandAsString);

            var executionResult = command.Execute(parameters);
            this.writer.WriteLine(executionResult);
        }
    }
}


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt

package com.google.appinventor.server.project;

import com.google.appinventor.server.storage.StorageIo;
import com.google.appinventor.shared.rpc.BlocksTruncatedException;
import com.google.appinventor.shared.rpc.RpcResult;
import com.google.appinventor.shared.rpc.project.ChecksumedLoadFile;
import com.google.appinventor.shared.rpc.project.ChecksumedFileException;
import com.google.appinventor.shared.rpc.project.NewProjectParameters;
import com.google.appinventor.shared.rpc.project.ProjectRootNode;
import com.google.appinventor.shared.rpc.user.User;
import com.google.appinventor.shared.storage.StorageUtil;
import com.google.appinventor.shared.util.Base64Util;

import java.util.List;

/**
 * The base class for classes that provide project services for a specific
 * project type.
 *
 * @author lizlooney@google.com (Liz Looney)
 */
public abstract class CommonProjectService {
  protected final String projectType;
  protected final StorageIo storageIo;

  protected CommonProjectService(String projectType, StorageIo storageIo) {
    this.projectType = projectType;
    this.storageIo = storageIo;
  }

  /**
   * Stores the project settings.
   *
   * @param userId the user id
   * @param projectId  project ID
   * @param settings  project settings
   */
  public void storeProjectSettings(String userId, long projectId, String settings) {
    storageIo.storeProjectSettings(userId, projectId, settings);
  }

  /**
   * Creates a new project.
   *
   * @param userId the user id
   * @param projectName project name
   * @param params optional parameters (project type dependent)
   *
   * @return new project ID
   */
  public abstract long newProject(String userId, String projectName, NewProjectParameters params);

  /**
   * Copies a project with a new name.
   *
   * @param userId the user id
   * @param oldProjectId  old project ID
   * @param newName new project name
   */
  public abstract long copyProject(String userId, long oldProjectId, String newName);

  /**
   * Deletes a project.
   *
   * @param userId the user id
   * @param projectId  project ID as received by
   */
  public void deleteProject(String userId, long projectId) {
    storageIo.deleteProject(userId, projectId);
  }

  /**
   * Returns the project root node for the requested project.
   *
   * @param userId the user id
   * @param projectId  project ID as received by {@link
   *                   com.google.appinventor.shared.rpc.project.ProjectService#getProjects()}
   *
   * @return  root node of project
   */
  public abstract ProjectRootNode getRootNode(String userId, long projectId);

  /**
   * Adds a file to the given project.
   *
   * @param userId the user id
   * @param projectId  project ID
   * @param fileId  ID of file to delete
   * @return modification date for project
   */
  public long addFile(String userId, long projectId, String fileId) {
    List<String> sourceFiles = storageIo.getProjectSourceFiles(userId, projectId);
    if (!sourceFiles.contains(fileId)) {
      storageIo.addSourceFilesToProject(userId, projectId, false, fileId);
    }
    return storageIo.uploadRawFileForce(projectId, fileId, userId, new byte[0]);
  }

  /**
   * Deletes a file in the given project.
   *
   * @param userId the user id
   * @param projectId  project ID
   * @param fileId  ID of file to delete
   * @return modification date for project
   */
  public long deleteFile(String userId, long projectId, String fileId) {
    final long date = storageIo.deleteFile(userId, projectId, fileId);
    storageIo.removeSourceFilesFromProject(userId, projectId, false, fileId);
    return date;
  }

  /**
   * Deletes all files that are contained directly in the given directory. Files
   * in sub-packages are not deleted.
   *
   * @param userId the user id
   * @param projectId project ID
   * @param directory path of the directory
   */
  public long deleteFiles(String userId, long projectId, String directory) {
    // TODO(user): This is not efficient.
    for (String fileId : storageIo.getProjectSourceFiles(userId, projectId)) {
      if (fileId.startsWith(directory + '/') && fileId.indexOf('/', directory.length() + 1) == -1) {
        storageIo.deleteFile(userId, projectId, fileId);
        storageIo.removeSourceFilesFromProject(userId, projectId, false, fileId);
      }
    }
    return storageIo.getProjectDateModified(userId, projectId);
  }

  /**
   * Loads the file information associated with a node in the project tree. The
   * actual return value depends on the file kind. Source (text) files should
   * typically return their contents. Image files will be more likely to return
   * the URL that the browser can find them at.
   *
   * @param userId the user id
   * @param projectId  project root node ID
   * @param fileId  project node whose source should be loaded
   *
   * @return  implementation dependent
   */
  public String load(String userId, long projectId, String fileId) {
    return storageIo.downloadFile(userId, projectId, fileId, StorageUtil.DEFAULT_CHARSET);
  }

  /**
   * Loads the file information associated with a node in the project tree. The
   * actual return value depends on the file kind. Source (text) files should
   * typically return their contents. Image files will be more likely to return
   * the URL that the browser can find them at.
   *
   * This version returns a ChecksumedLoadFile object which includes the file
   * content and a SHA-1 hash to validate file integrity accross the network.
   *
   * @param userId the user id
   * @param projectId  project root node ID
   * @param fileId  project node whose source should be loaded
   *
   * @return  ChecksumedLoadFile object
   */
  public ChecksumedLoadFile load2(String userId, long projectId, String fileId) throws ChecksumedFileException {
    ChecksumedLoadFile retval = new ChecksumedLoadFile();
    retval.setContent(storageIo.downloadFile(userId, projectId, fileId, StorageUtil.DEFAULT_CHARSET));
    return retval;
  }

  /**
   * Attempt to record the project Id and error message when we detect a corruption
   * while loading a project.
   *
   * @param userId user id
   * @param projectId project id
   * @param message Error message from the thrown exception
   *
   */
  public void recordCorruption(String userId, long projectId, String fileId, String message) {
    storageIo.recordCorruption(userId, projectId, fileId, message);
  }

  /**
   * Loads the raw content of the associated file.
   *
   * @param userId the userid
   * @param projectId the project root node ID
   * @param fileId project node whose content is to be downloaded
   * @return the file contents
   */

  public byte[] loadraw(String userId, long projectId, String fileId) {
    return storageIo.downloadRawFile(userId, projectId, fileId);
  }

  /**
   * Loads the raw content of the associated file, base 64 encodes it
   * and returns the resulting base64 encoded string.
   *
   * @param userId the userid
   * @param projectId the project root node ID
   * @param fileId project node whose content is to be downloaded
   * @param the file contents encoded in base64
   */
  public String loadraw2(String userId, long projectId, String fileId) {
    byte [] filedata = storageIo.downloadRawFile(userId, projectId, fileId);
    return Base64Util.encodeLines(filedata);
  }

  /**
   * Saves the content of the file associated with a node in the project tree.
   * This is a backwards compatible version that always sets force to true
   * Its primary purpose is to ease the release transition. People running an
   * older Ode at release time won't lose. At some point this function should go
   * away and save2 renamed back to save (through stages).
   *
   * @param userId the user id
   * @param projectId  project root node ID
   * @param fileId  project node whose source should be loaded
   * @param content  content to be saved
   * @return modification date for project
   *
   * @see com.google.appinventor.shared.rpc.project.ProjectService#save(String, long, String, String)
   */
  public long save(String userId, long projectId, String fileId, String content) {
    try {
      return save2(userId, projectId, fileId, true, content);
    } catch (BlocksTruncatedException e) {
      // Won't happen because it isn't thrown when the force argument is true
      // This is here just to keep the Java compiler happy. It isn't smart enough
      // to know that the exception won't be thrown in this case.
      return 0;
    }
  }

  /**
   * Saves the content of the file associated with a node in the project tree.
   * if force is false, an error is thrown if an attempt is made to save a
   * trivial (empty) blocks file workspace that had previously had contents.
   *
   * @param userId the user id
   * @param projectId  project root node ID
   * @param fileId  project node whose source should be loaded
   * @param content  content to be saved
   * @return modification date for project
   *
   * @see com.google.appinventor.shared.rpc.project.ProjectService#save(String, long, String, String)
   */
  public long save2(String userId, long projectId, String fileId, boolean force, String content) throws BlocksTruncatedException {
    if (force) {
      return storageIo.uploadFileForce(projectId, fileId, userId,
          content, StorageUtil.DEFAULT_CHARSET);
    } else {
      return storageIo.uploadFile(projectId, fileId, userId,
          content, StorageUtil.DEFAULT_CHARSET);
    }
  }

  /**
   * Invokes a build command for the project.
   *
   * @param user the User that owns the {@code projectId}.
   * @param projectId  project id to be built
   * @param nonce -- random string used to find finished APK
   * @param target  build target (optional, implementation dependent)
   *
   * @return  build results
   */
  public abstract RpcResult build(User user, long projectId, String nonce, String target);

  /**
   * Gets the result of a build command for the project.
   *
   * @param user the User that owns the {@code projectId}.
   * @param projectId  project id to be built
   * @param target  build target (optional, implementation dependent.
   * @return  build results.  The following values may be in RpcResult.result:
   *            0: Build is done and was successful
   *            1: Build is done and was unsuccessful
   *           -1: Build is not yet done.
   */
  public abstract RpcResult getBuildResult(User user, long projectId, String target);
}


text:
#include <iostream>
#include "../basic/glfw3.h"
#include <OpenGL/glext.h>
#include <OpenGL/gl3ext.h>
#include <stdlib.h>
#include <math.h>

struct Rendering{
  virtual void initialize(int width, int height) = 0;
};

class RenderingClass : public Rendering{
public:
  RenderingClass();
  void initialize(int width, int height);
private:
  GLuint BuildShader(const char* source, GLenum shaderType) const;
  GLuint BuildProgram(const char* vertexShader, const char* fragmentShader) const;
  GLuint m_shader_program;
  GLuint m_framebuffer;
  GLuint m_colorRenderbuffer;
  // static GLboolean printShaderInfoLog(GLuint shader, const char *str);
  // static GLboolean printProgramInfoLog(GLuint program);
};

RenderingClass :: RenderingClass(){

}

void RenderingClass :: initialize(int width, int height){

  BuildProgram("vs","fr");

}

RenderingClass* createRenderingClass(){

  return new RenderingClass;
}

GLuint RenderingClass :: BuildShader(const char* source, GLenum shaderType) const{

}

GLuint RenderingClass :: BuildProgram(const char* vertexShader, const char* fragmentShader) const{

  std::cout << "Building programme." << std::endl;

}

int width = 200; int height = 200;

int main(){

  glfwInit();

  // t = 0.;
  GLFWwindow* window;

  window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);

  glfwGetFramebufferSize(window, &width, &height);

  while (!glfwWindowShouldClose(window)){

    glfwSwapInterval(1);

    glClearColor(0.,0.,0.5,1.);	/* blue background */

  }

  return 0;
}


text:
package logbook.gui.listener;

import logbook.gui.VersionDialog;
import logbook.gui.WindowBase;

import org.eclipse.swt.events.HelpEvent;
import org.eclipse.swt.events.HelpListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

/**
 * ヘルプキーを押した場合のリスナー
 *
 */
public final class HelpEventListener extends SelectionAdapter implements HelpListener {

    /** シェル */
    private final WindowBase parent;

    /**
     * コンストラクター
     *
     * @param shell シェル
     */
    public HelpEventListener(WindowBase parent) {
        this.parent = parent;
    }

    @Override
    public void helpRequested(HelpEvent paramHelpEvent) {
        new VersionDialog(this.parent).open();
    }

    @Override
    public void widgetSelected(SelectionEvent e) {
        new VersionDialog(this.parent).open();
    }
}