text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Alea;
using Alea.cuRAND;
using GpuStream = Alea.Stream;

namespace AleaTK
{
    public enum DeviceType
    {
        Cpu = 0,
        Gpu
    }

    public abstract class Device
    {
        public abstract DeviceType Type { get; }

        public void EnsureType(DeviceType targetType)
        {
            if (Type != targetType)
            {
                throw new InvalidOperationException("Device type doesn't match.");
            }
        }

        public CpuDevice ToCpuDevice()
        {
            EnsureType(DeviceType.Cpu);
            return (CpuDevice)this;
        }

        public GpuDevice ToGpuDevice()
        {
            EnsureType(DeviceType.Gpu);
            return (GpuDevice)this;
        }

        private static readonly ConcurrentDictionary<int, GpuDevice> GpuDevices =
            new ConcurrentDictionary<int, GpuDevice>();

        public static readonly Device CpuDevice = new CpuDevice();

        public static Device GpuDevice(Gpu gpu)
        {
            return GpuDevices.GetOrAdd(gpu.Device.Id, deviceId => new GpuDevice(Gpu.Get(deviceId)));
        }

        public static Device GpuDevice(int deviceId)
        {
            return GpuDevices.GetOrAdd(deviceId, _ => new GpuDevice(Gpu.Get(deviceId)));
        }
    }

    public sealed class CpuDevice : Device
    {
        internal CpuDevice()
        {
        }

        public override DeviceType Type => DeviceType.Cpu;

        public override string ToString()
        {
            return "CpuDevice";
        }
    }

    public sealed class GpuDevice : Device
    {
        internal GpuDevice(Gpu gpu)
        {
            Gpu = gpu;
            MemoryRepository = new DeviceMemoryRepository(gpu);
        }

        public override DeviceType Type => DeviceType.Gpu;

        public Gpu Gpu { get; }

        public DeviceMemoryRepository MemoryRepository { get; }

        public override string ToString()
        {
            return $"GpuDevice{Gpu}";
        }
    }

    public enum ContextType
    {
        Cpu = 0,
        Gpu
    }

    public abstract class Context : Disposable
    {
        public abstract ContextType Type { get; }

        public abstract Device Device { get; }

        public abstract Alea.cuRAND.Generator CreateRandomGenerator(PseudoRandomType type);

        private readonly ConcurrentDictionary<PseudoRandomType, Alea.cuRAND.Generator> _pseudoRandomGenerators =
            new ConcurrentDictionary<PseudoRandomType, Generator>();

        public Alea.cuRAND.Generator GetRandomGenerator(PseudoRandomType type)
        {
            return _pseudoRandomGenerators.GetOrAdd(type, CreateRandomGenerator);
        }

        public void EnsureType(ContextType targetType)
        {
            if (Type != targetType)
            {
                throw new InvalidOperationException("AttentionState type doesn't match.");
            }
        }

        public CpuContext ToCpuContext()
        {
            EnsureType(ContextType.Cpu);
            return (CpuContext)this;
        }

        public GpuContext ToGpuContext()
        {
            EnsureType(ContextType.Gpu);
            return (GpuContext)this;
        }

        private struct GpuContextKey
        {
            private int _deviceId;
            private int _streamId;

            public GpuContextKey(int deviceId, int streamId)
            {
                _deviceId = deviceId;
                _streamId = streamId;
            }
        }

        private static readonly ConcurrentDictionary<GpuContextKey, GpuContext> GpuContexts =
            new ConcurrentDictionary<GpuContextKey, GpuContext>();

        public static readonly Context CpuContext = new CpuContext();

        public static Context GpuContext(int deviceId, int streamId = 0)
        {
            var key = new GpuContextKey(deviceId, streamId);
            return GpuContexts.GetOrAdd(key, _ => new GpuContext(Gpu.Get(deviceId)));
        }

        public static Context GpuContext(Gpu gpu, int streamId = 0)
        {
            var key = new GpuContextKey(gpu.Device.Id, streamId);
            return GpuContexts.GetOrAdd(key, _ => new GpuContext(gpu));
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (var rng in _pseudoRandomGenerators.Values)
                {
                    rng.Dispose();
                }
            }
            base.Dispose(disposing);
        }
    }

    public sealed class CpuContext : Context
    {
        public CpuContext()
        {
            Device = Device.CpuDevice;
        }

        public override ContextType Type => ContextType.Cpu;

        public override Device Device { get; }

        public override Generator CreateRandomGenerator(PseudoRandomType type)
        {
            switch (type)
            {
                case PseudoRandomType.Default:
                    return Alea.cuRAND.Generator.CreateCpu(RngType.PSEUDO_DEFAULT);

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    public sealed class GpuContext : Context
    {
        public GpuContext(Gpu gpu, bool useDefaultStream = false)
        {
            Device = Device.GpuDevice(gpu);
            Gpu = gpu;
            if (useDefaultStream)
            {
                throw new NotImplementedException("TODO: add default stream support.");
            }
            else
            {
                Stream = gpu.CreateStream();
                if (Alea.cuDNN.Dnn.IsAvailable)
                {
                    Dnn = new Alea.cuDNN.Dnn(Stream);
                }
                if (Alea.cuBLAS.Blas.IsAvailable)
                {
                    Blas = new Alea.cuBLAS.Blas(Stream);
                }
            }
        }

        public override ContextType Type => ContextType.Gpu;

        public override Device Device { get; }

        public override Generator CreateRandomGenerator(PseudoRandomType type)
        {
            Generator rng;
            switch (type)
            {
                case PseudoRandomType.Default:
                    rng = Generator.CreateGpu(Gpu, RngType.PSEUDO_DEFAULT);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
            rng.SetStream(Stream);
            return rng;
        }

        public GpuStream Stream { get; }

        public Gpu Gpu { get; }

        public Alea.cuDNN.Dnn Dnn { get; }

        public Alea.cuBLAS.Blas Blas { get; }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                if (!Stream.IsDefault) Stream.Dispose();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from optparse import OptionParser, OptionValueError
import os
import shutil
import sys

"""Prep NaCl Toolchain

Does final assembly of the NaCl toolchain prior to building untrusted modules.
"""

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
NACL_DIR = os.path.dirname(SCRIPT_DIR)

# Mapping from TC/include relative path to original source
HEADER_MAP = {
  'x86_newlib': {
      'x86_64-nacl/include/pthread.h': 'src/untrusted/pthread/pthread.h',
      'x86_64-nacl/include/semaphore.h': 'src/untrusted/pthread/semaphore.h',
      'x86_64-nacl/include/nacl/dynamic_annotations.h':
          'src/untrusted/valgrind/dynamic_annotations.h',
      'x86_64-nacl/include/nacl/nacl_dyncode.h':
          'src/untrusted/nacl/nacl_dyncode.h',
      'x86_64-nacl/include/nacl/nacl_startup.h':
          'src/untrusted/nacl/nacl_startup.h',
      'x86_64-nacl/include/nacl/nacl_thread.h':
          'src/untrusted/nacl/nacl_thread.h',
      'x86_64-nacl/include/irt.h': 'src/untrusted/irt/irt.h',
      'x86_64-nacl/include/irt_ppapi.h': 'src/untrusted/irt/irt_ppapi.h',

      'x86_64-nacl/lib32/crt1.o': 'src/untrusted/stubs/crt1.x',
      'x86_64-nacl/lib/crt1.o': 'src/untrusted/stubs/crt1.x',
  },
  'x86_glibc': {
      'x86_64-nacl/include/nacl/dynamic_annotations.h':
          'src/untrusted/valgrind/dynamic_annotations.h',
      'x86_64-nacl/include/nacl/nacl_dyncode.h':
          'src/untrusted/nacl/nacl_dyncode.h',
      'x86_64-nacl/include/nacl/nacl_startup.h':
          'src/untrusted/nacl/nacl_startup.h',
      'x86_64-nacl/include/nacl/nacl_thread.h':
          'src/untrusted/nacl/nacl_thread.h',
      'x86_64-nacl/include/irt.h': 'src/untrusted/irt/irt.h',
      'x86_64-nacl/include/irt_ppapi.h': 'src/untrusted/irt/irt_ppapi.h',
  },
  'arm_newlib': {
      'arm-nacl/include/pthread.h': 'src/untrusted/pthread/pthread.h',
      'arm-nacl/include/semaphore.h': 'src/untrusted/pthread/semaphore.h',
      'arm-nacl/include/nacl/dynamic_annotations.h':
          'src/untrusted/valgrind/dynamic_annotations.h',
      'arm-nacl/include/nacl/nacl_dyncode.h':
          'src/untrusted/nacl/nacl_dyncode.h',
      'arm-nacl/include/nacl/nacl_startup.h':
          'src/untrusted/nacl/nacl_startup.h',
      'arm-nacl/include/nacl/nacl_thread.h':
          'src/untrusted/nacl/nacl_thread.h',
      'arm-nacl/include/include/irt.h': 'src/untrusted/irt/irt.h',
      'arm-nacl/include/include/irt_ppapi.h': 'src/untrusted/irt/irt_ppapi.h',
      'arm-nacl/lib/crt1.o': 'src/untrusted/stubs/crt1.x',
  },
  'x86_pnacl': {
      'newlib/sdk/include/include/pthread.h': 'src/untrusted/pthread/pthread.h',
      'newlib/sdk/include/include/semaphore.h': 'src/untrusted/pthread/semaphore.h',
      'newlib/sdk/include/include/nacl/dynamic_annotations.h':
          'src/untrusted/valgrind/dynamic_annotations.h',
      'newlib/sdk/include/include/nacl/nacl_dyncode.h':
          'src/untrusted/nacl/nacl_dyncode.h',
      'newlib/sdk/include/include/nacl/nacl_startup.h':
          'src/untrusted/nacl/nacl_startup.h',
      'newlib/sdk/include/include/nacl/nacl_thread.h':
          'src/untrusted/nacl/nacl_thread.h',
      'newlib/sdk/include/include/irt.h': 'src/untrusted/irt/irt.h',
      'newlib/sdk/include/include/irt_ppapi.h': 'src/untrusted/irt/irt_ppapi.h',
  }
}

def PosixPath(filepath):
  if sys.platform == 'win32':
    return filepath.replace('\\', '/')
  return filepath

def RealToRelative(filepath, basepath):
  """Returns a relative path from an absolute basepath and filepath."""
  path_parts = filepath.split('/')
  base_parts = basepath.split('/')
  while path_parts and base_parts and path_parts[0] == base_parts[0]:
    path_parts = path_parts[1:]
    base_parts = base_parts[1:]
  rel_parts = ['..'] * len(base_parts) + path_parts
  return '/'.join(rel_parts)

def MakeDir(outdir):
  if outdir and not os.path.exists(outdir):
    os.makedirs(outdir)

def GetInputs(tc_map, basepath):
  out_set = set()
  for filename in tc_map:
    src = PosixPath(os.path.join(NACL_DIR, tc_map[filename]))
    out_set.add(RealToRelative(src, basepath))

  return '\n'.join(sorted(out_set)) + '\n'

def CopyFiles(tc_map, tc_dst):
  for filename in tc_map:
    src = PosixPath(os.path.join(NACL_DIR, tc_map[filename]))
    dst = os.path.join(tc_dst, filename)
    MakeDir(os.path.dirname(dst))
    if not os.path.exists(src):
      raise RuntimeError('File not found: ' + src)

    shutil.copy(src, dst)

def DoMain(argv):
  parser = OptionParser()
  parser.add_option('-p', '--path', dest='path', default='',
                    help='Set include path.')
  parser.add_option('-t', '--tool', dest='tool', default='',
                    help='Select toolset.')
  parser.add_option('-i', '--inputs', dest='inputs', action='store_true',
                    help='Return dependency list.', default=False)
  parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
                    help='Enable versbose output.')

  options, files = parser.parse_args(argv)
  basepath = PosixPath(os.path.abspath(os.getcwd()))

  if len(files):
    raise OptionValueError('Not expecting arguments: ' + ' '.join(files))

  if options.tool not in HEADER_MAP:
    raise OptionValueError('Unknown tool name: ' + options.tool)

  tc_map = HEADER_MAP[options.tool]
  tc_dest = os.path.abspath(options.path)

  if options.inputs:
    return GetInputs(tc_map, basepath)

  if not options.path or not os.path.exists(options.path):
    raise RuntimeError('Must set path to a valid directory.')

  if not options.tool in HEADER_MAP:
    raise RuntimeError('Must specify the toolchain.')

  if not options.inputs:
    CopyFiles(tc_map, tc_dest)
    fh = open(os.path.join(tc_dest, 'stamp.prep'), 'w')
    fh.write('NACL SDK stamp for %s\n' % options.tool)
    fh.close()
    if options.verbose:
      print 'Created stamp file.'
  return 0

def main(argv):
  result = DoMain(argv[1:])
  if type(result) == int:
    return result

  sys.stdout.write(result)
  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv))


text:
<?php
$warning.=$lang["warning_no_page_permission"];
?>


text:
/* global Module */

Module.register("MMM-Voice-Control", {

	// Default module config.
	defaults: {
		language: "en",
		voiceTextRestTimeout: 3000, // 3 seconds
		listOfCommandsNotificationTime: 10000 // 10 seconds
	},

	getScripts: function() {
		return [this.file('node_modules/annyang/dist/annyang.js'), 'annyang-service.js', 'moment.js', 'commands.js'];
	},

	// Define required scripts.
	getStyles: function() {
		return ["style.css"];
	},

	getTranslations: function() {
		return {
			en: "translations/en.json",
			de: "translations/de.json",
			es: "translations/es.json",
			fr: "translations/fr.json",
			ko: "translations/ko.json"
		};
	},

	// Override dom generator.
	getDom: function() {
		var wrapper = document.createElement("div");
		wrapper.className = "small light";
		wrapper.innerHTML = this.interimResult;
		return wrapper;
	},

	restCommand: function(scope) {
		scope.interimResult = scope.translate("home").commands;
		scope.updateDom(500);
	},

	setLanguage: function() {
		moment.locale(config.language);
		this.annyangService.setLanguage(config.language);
		this.interimResult = this.translate("home").commands;
	},

	start: function() {
		Log.info("Starting module: " + this.name);

		this.annyangService = AnnyangService();
		this.isListening = false;
		this.setLanguage();
		this.readableCommands = {
			header: this.interimResult,
			commands: []
		};

		CommandManager(this);

		this.startAnnayang();
	},

	registerCommand: function(commandId, commandFunction) {
		var voiceTranslation = this.translate("commands")[commandId].voice;
		var textTranslation = this.translate("commands")[commandId].text;
		var descTranslation = this.translate("commands")[commandId].description;
		this.readableCommands.commands.push(textTranslation + ": " + descTranslation);
		this.annyangService.registerCommand(voiceTranslation, commandFunction);
	},

	startAnnayang: function() {
		var self = this;
		var resetCommandTimeout;
		self.annyangService.start(
			function() {
				self.isListening = true;
			},
			function(interimResult) {
				self.interimResult = interimResult;
				window.clearTimeout(resetCommandTimeout);
				Log.info("Interim result: " + self.interimResult);
				self.updateDom(500);
			},
			function(result) {
				if (typeof result != 'undefined') {
					self.interimResult = result[0];
					Log.info("Acting on result: " + self.interimResult);
					self.updateDom(500);
					resetCommandTimeout = window.setTimeout(function() {
							self.restCommand(self);
						},
						self.config.voiceTextRestTimeout
					);
				}
			},
			function(error) {
				console.log(error);
				if (error.error == "network") {
					self.speechError = "Google Speech Recognizer is down :(";
					self.annyangService.abort();
					self.isListening = false;
				}
			}
		);
	},
});


text:
package com.android.music;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Environment;
import android.view.View;
import android.widget.RemoteViews;

/**
 * Simple widget to show currently playing album art along
 * with play/pause and next track buttons.
 */
public class MediaAppWidgetProvider extends AppWidgetProvider {
    static final String TAG = "MusicAppWidgetProvider";

    public static final String CMDAPPWIDGETUPDATE = "appwidgetupdate";

    private static MediaAppWidgetProvider sInstance;

    static synchronized MediaAppWidgetProvider getInstance() {
        if (sInstance == null) {
            sInstance = new MediaAppWidgetProvider();
        }
        return sInstance;
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        defaultAppWidget(context, appWidgetIds);

        // Send broadcast intent to any running MediaPlaybackService so it can
        // wrap around with an immediate update.
        Intent updateIntent = new Intent(MediaPlaybackService.SERVICECMD);
        updateIntent.putExtra(MediaPlaybackService.CMDNAME,
                MediaAppWidgetProvider.CMDAPPWIDGETUPDATE);
        updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        updateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        context.sendBroadcast(updateIntent);
    }

    /**
     * Initialize given widgets to default state, where we launch Music on default click
     * and hide actions if service not running.
     */
    private void defaultAppWidget(Context context, int[] appWidgetIds) {
        final Resources res = context.getResources();
        final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.album_appwidget);

        views.setViewVisibility(R.id.title, View.GONE);
        views.setTextViewText(R.id.artist, res.getText(R.string.widget_initial_text));

        linkButtons(context, views, false /* not playing */);
        pushUpdate(context, appWidgetIds, views);
    }

    private void pushUpdate(Context context, int[] appWidgetIds, RemoteViews views) {
        // Update specific list of appWidgetIds if given, otherwise default to all
        final AppWidgetManager gm = AppWidgetManager.getInstance(context);
        if (appWidgetIds != null) {
            gm.updateAppWidget(appWidgetIds, views);
        } else {
            gm.updateAppWidget(new ComponentName(context, this.getClass()), views);
        }
    }

    /**
     * Check against {@link AppWidgetManager} if there are any instances of this widget.
     */
    private boolean hasInstances(Context context) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
                new ComponentName(context, this.getClass()));
        return (appWidgetIds.length > 0);
    }

    /**
     * Handle a change notification coming over from {@link MediaPlaybackService}
     */
    void notifyChange(MediaPlaybackService service, String what) {
        if (hasInstances(service)) {
            if (MediaPlaybackService.META_CHANGED.equals(what) ||
                    MediaPlaybackService.PLAYSTATE_CHANGED.equals(what)) {
                /* SPRD 476972  @{*/
                performUpdate(service, null, null);
            }
            /* SPRD 476972  @{*/
            if (MediaPlaybackService.SERVICE_DESTROY.equals(what)) {
                performUpdate(service, null, MediaPlaybackService.SERVICE_DESTROY);
            }
            /* @} */
        }
    }

    /**
     * Update all active widget instances by pushing changes
     */
    /* SPRD 476972  @{*/
    void performUpdate(MediaPlaybackService service, int[] appWidgetIds, String what) {
        final Resources res = service.getResources();
        final RemoteViews views = new RemoteViews(service.getPackageName(), R.layout.album_appwidget);

        CharSequence titleName = service.getTrackName();
        CharSequence artistName = service.getArtistName();
        CharSequence errorState = null;
        /* SPRD 476972  @{*/
        final boolean playing = service.isPlaying();

        if (MediaPlaybackService.SERVICE_DESTROY.equals(what)) {
            if (artistName != null) {
                views.setViewVisibility(R.id.title, View.VISIBLE);
                views.setTextViewText(R.id.title, titleName);
                views.setTextViewText(R.id.artist, artistName);
            } else {
                String text = res.getString(R.string.emptyplaylist);
                views.setTextViewText(R.id.artist, text);
                views.setViewVisibility(R.id.title, View.GONE);
                views.setTextViewText(R.id.title, null);
            }
            views.setImageViewResource(R.id.control_play, R.drawable.ic_appwidget_music_play);
            linkButtons(service, views, false);
            pushUpdate(service, appWidgetIds, views);
            return;
        }
        /* @} */
        // Format title string with track number, or show SD card message
        /* SPRD bug fix 544577  @{*/
        /*String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_SHARED) ||
                status.equals(Environment.MEDIA_UNMOUNTED)) {
            if (android.os.Environment.isExternalStorageRemovable()) {
                errorState = res.getText(R.string.sdcard_busy_title);
            } else {
                errorState = res.getText(R.string.sdcard_busy_title_nosdcard);
            }
        } else if (status.equals(Environment.MEDIA_REMOVED)) {
            if (android.os.Environment.isExternalStorageRemovable()) {
                errorState = res.getText(R.string.sdcard_missing_title);
            } else {
                errorState = res.getText(R.string.sdcard_missing_title_nosdcard);
            }
        } else */
        /* @} */
        if (titleName == null) {
            errorState = res.getText(R.string.emptyplaylist);
        }

        if (errorState != null) {
            // Show error state to user
            views.setViewVisibility(R.id.title, View.GONE);
            views.setTextViewText(R.id.artist, errorState);

        } else {
            // No error, so show normal titles
            views.setViewVisibility(R.id.title, View.VISIBLE);
            views.setTextViewText(R.id.title, titleName);
            views.setTextViewText(R.id.artist, artistName);
        }

        // Set correct drawable for pause state
        if (playing) {
            views.setImageViewResource(R.id.control_play, R.drawable.ic_appwidget_music_pause);
        } else {
            views.setImageViewResource(R.id.control_play, R.drawable.ic_appwidget_music_play);
        }

        // Link actions buttons to intents
        linkButtons(service, views, playing);

        pushUpdate(service, appWidgetIds, views);
    }

    /**
     * Link up various button actions using {@link PendingIntents}.
     *
     * @param playerActive True if player is active in background, which means
     *            widget click will launch {@link MediaPlaybackActivity},
     *            otherwise we launch {@link MusicBrowserActivity}.
     */
    private void linkButtons(Context context, RemoteViews views, boolean playerActive) {
        // Connect up various buttons and touch events
        Intent intent;
        PendingIntent pendingIntent;

        final ComponentName serviceName = new ComponentName(context, MediaPlaybackService.class);

        if (playerActive) {
            intent = new Intent(context, MediaPlaybackActivity.class);
            pendingIntent = PendingIntent.getActivity(context,
                    0 /* no requestCode */, intent, 0 /* no flags */);
            views.setOnClickPendingIntent(R.id.album_appwidget, pendingIntent);
        } else {
            intent = new Intent(context, MusicBrowserActivity.class);
            pendingIntent = PendingIntent.getActivity(context,
                    0 /* no requestCode */, intent, 0 /* no flags */);
            views.setOnClickPendingIntent(R.id.album_appwidget, pendingIntent);
        }

        intent = new Intent(MediaPlaybackService.TOGGLEPAUSE_ACTION);
        intent.setComponent(serviceName);
        pendingIntent = PendingIntent.getService(context,
                0 /* no requestCode */, intent, 0 /* no flags */);
        views.setOnClickPendingIntent(R.id.control_play, pendingIntent);

        intent = new Intent(MediaPlaybackService.NEXT_ACTION);
        intent.setComponent(serviceName);
        pendingIntent = PendingIntent.getService(context,
                0 /* no requestCode */, intent, 0 /* no flags */);
        views.setOnClickPendingIntent(R.id.control_next, pendingIntent);

        /* SPRD 476972  @{*/
        intent = new Intent(MediaPlaybackService.PREVIOUS_ACTION);
        intent.setComponent(serviceName);
        pendingIntent = PendingIntent.getService(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.control_pre, pendingIntent);
        /* @} */
    }
}


text:
static int nodecount = 1000;

#define PRINT_BEFORE_AFTER std::ofstream of("before.dot"); \
				of << "digraph before {" << std::endl; \
				root->printAST(root, of); \
				of << "}" << std::endl; \
				of.close(); \
				std::ofstream of1("after.dot"); \
				of1 << "digraph after {" << std::endl; \
				n->printAST(n, of1); \
				of1 << "}" << std::endl; \
				of1.close(); \
				exit(0);

SyntaxNode::SyntaxNode() : pbb(NULL), score(-1), correspond(NULL),
						   notGoto(false)
{
	nodenum = nodecount++;
}

SyntaxNode::~SyntaxNode()
{
}

int SyntaxNode::getScore()
{
	if (score == -1)
		score = evaluate(this);
	return score;
}

bool SyntaxNode::isGoto()
{
	return pbb && pbb->getType() == ONEWAY && !notGoto;
}

bool SyntaxNode::isBranch()
{
	return pbb && pbb->getType() == TWOWAY;
}

BlockSyntaxNode::BlockSyntaxNode()
{
}

BlockSyntaxNode::~BlockSyntaxNode()
{
	for (unsigned i = 0; i < statements.size(); i++)
		delete statements[i];
}

int BlockSyntaxNode::getNumOutEdges() {
	if (pbb)
		return pbb->getNumOutEdges();
	if (statements.size() == 0)
		return 0;
	return statements[statements.size()-1]->getNumOutEdges();
}

SyntaxNode *BlockSyntaxNode::getOutEdge(SyntaxNode *root, int n) {
	if (pbb)
		return root->findNodeFor(pbb->getOutEdge(n));
	if (statements.size() == 0)
		return NULL;
	return statements[statements.size()-1]->getOutEdge(root, n);
}

SyntaxNode *BlockSyntaxNode::findNodeFor(PBB bb)
{
	if (pbb == bb)
		return this;
	SyntaxNode *n = NULL;
	for (unsigned i = 0; i < statements.size(); i++) {
		n = statements[i]->findNodeFor(bb);
		if (n != NULL)
			break;
	}
	if (n && n == statements[0])
		return this;
	return n;
}

void BlockSyntaxNode::printAST(SyntaxNode *root, std::ostream &os)
{
	os << std::setw(4) << std::dec << nodenum << " ";
	os << "[label=\"";
	if (pbb) {
		switch(pbb->getType()) {
			case ONEWAY:	os << "Oneway";
							if (notGoto) os << " (ignored)"; break;
			case TWOWAY:	os << "Twoway"; break;
			case NWAY:		os << "Nway"; break;
			case CALL:		os << "Call"; break;
			case RET:		os << "Ret"; break;
			case FALL:		os << "Fall"; break;
			case COMPJUMP:	os << "Computed jump"; break;
			case COMPCALL:	os << "Computed call"; break;
			case INVALID:	os << "Invalid"; break;
		}
		os << " " << std::hex << pbb->getLowAddr();
	} else
		os << "block";
	os << "\"];" << std::endl;
	if (pbb) {
		for (int i = 0; i < pbb->getNumOutEdges(); i++) {
			PBB out = pbb->getOutEdge(i);
			os << std::setw(4) << std::dec << nodenum << " ";
			SyntaxNode *to = root->findNodeFor(out);
			assert(to);
			os << " -> " << to->getNumber() << " [style=dotted";
			if (pbb->getNumOutEdges() > 1)
				os << ",label=" << i;
			os << "];" << std::endl;
		}
	} else	{
		for (unsigned i = 0; i < statements.size(); i++)
			statements[i]->printAST(root, os);
		for (unsigned i = 0; i < statements.size(); i++) {
			os << std::setw(4) << std::dec << nodenum << " ";
			os << " -> " << statements[i]->getNumber()
						 << " [label=\"" << i << "\"];" << std::endl;
		}
	}
}

#define DEBUG_EVAL 0

int BlockSyntaxNode::evaluate(SyntaxNode *root)
{
#if DEBUG_EVAL
	if (this == root)
		std::cerr << "begin eval =============" << std::endl;
#endif
	if (pbb)
		return 1;
	int n = 1;
	if (statements.size() == 1) {
		SyntaxNode *out = statements[0]->getOutEdge(root, 0);
		if (out->getBB() != NULL && out->getBB()->getNumInEdges() > 1) {
#if DEBUG_EVAL
			std::cerr << "add 15" << std::endl;
#endif
			n += 15;
		} else {
#if DEBUG_EVAL
			std::cerr << "add 30" << std::endl;
#endif
			n += 30;
		}
	}
	for (unsigned i = 0; i < statements.size(); i++) {
		n += statements[i]->evaluate(root);
		if (statements[i]->isGoto()) {
			if (i != statements.size()-1) {
#if DEBUG_EVAL
				std::cerr << "add 100" << std::endl;
#endif
				n += 100;
			} else {
#if DEBUG_EVAL
				std::cerr << "add 50" << std::endl;
#endif
				n += 50;
			}
		} else if (statements[i]->isBranch()) {
			SyntaxNode *loop = root->getEnclosingLoop(this);
			std::cerr << "branch " << statements[i]->getNumber()
					  << " not in loop" << std::endl;
			if (loop) {
				std::cerr << "branch " << statements[i]->getNumber()
						  << " in loop " << loop->getNumber() << std::endl;
				// this is a bit C specific
				SyntaxNode *out = loop->getOutEdge(root, 0);
				if (out && statements[i]->getOutEdge(root, 0) == out) {
					std::cerr << "found break" << std::endl;
					n += 10;
				}
				if (statements[i]->getOutEdge(root, 0) == loop) {
					std::cerr << "found continue" << std::endl;
					n += 10;
				}
			} else {
#if DEBUG_EVAL
				std::cerr << "add 50" << std::endl;
#endif
				n += 50;
			}
		} else if (i < statements.size()-1 &&
				 statements[i]->getOutEdge(root, 0) != statements[i+1]) {
#if DEBUG_EVAL
			std::cerr << "add 25" << std::endl;
			std::cerr << statements[i]->getNumber() << " -> "
					  << statements[i]->getOutEdge(root, 0)->getNumber()
					  << " not " << statements[i+1]->getNumber() << std::endl;
#endif
			n += 25;
		}
	}
#if DEBUG_EVAL
	if (this == root)
		std::cerr << "end eval = " << n << " =============" << std::endl;
#endif
	return n;
}

void BlockSyntaxNode::addSuccessors(SyntaxNode *root,
									std::vector<SyntaxNode*> &successors)
{
	for (unsigned i = 0; i < statements.size(); i++) {
		if (statements[i]->isBlock()) {
			//BlockSyntaxNode *b = (BlockSyntaxNode*)statements[i];
			// can move previous statements into this block
			if (i > 0) {
				std::cerr << "successor: move previous statement into block"
						  << std::endl;
				SyntaxNode *n = root->clone();
				n->setDepth(root->getDepth() + 1);
				BlockSyntaxNode *b1 = (BlockSyntaxNode*)this->clone();
				BlockSyntaxNode *nb = (BlockSyntaxNode*)b1->getStatement(i);
				b1 = (BlockSyntaxNode*)b1->replace(statements[i-1], NULL);
				nb->prependStatement(statements[i-1]->clone());
				n = n->replace(this, b1);
				successors.push_back(n);
				//PRINT_BEFORE_AFTER
			}
		} else {
			if (statements.size() != 1) {
				// can replace statement with a block containing that statement
				std::cerr << "successor: replace statement with a block "
						  << "containing the statement" << std::endl;
				BlockSyntaxNode *b = new BlockSyntaxNode();
				b->addStatement(statements[i]->clone());
				SyntaxNode *n = root->clone();
				n->setDepth(root->getDepth() + 1);
				n = n->replace(statements[i], b);
				successors.push_back(n);
				//PRINT_BEFORE_AFTER
			}
		}
		// "jump over" style of if-then
		if (i < statements.size() - 2 && statements[i]->isBranch()) {
			SyntaxNode *b = statements[i];
			if (b->getOutEdge(root, 0) == statements[i+2] &&
				(statements[i+1]->getOutEdge(root, 0) == statements[i+2] ||
				 statements[i+1]->endsWithGoto())) {
					std::cerr << "successor: jump over style if then"
							  << std::endl;
					BlockSyntaxNode *b1 =
						(BlockSyntaxNode*)this->clone();
					b1 = (BlockSyntaxNode*)b1->replace(statements[i+1], NULL);
					IfThenSyntaxNode *nif = new IfThenSyntaxNode();
					Exp *cond = b->getBB()->getCond();
					cond = new Unary(opLNot, cond->clone());
					cond = cond->simplify();
					nif->setCond(cond);
					nif->setThen(statements[i+1]->clone());
					nif->setBB(b->getBB());
					b1->setStatement(i, nif);
					SyntaxNode *n = root->clone();
					n->setDepth(root->getDepth() + 1);
					n = n->replace(this, b1);
					successors.push_back(n);
					//PRINT_BEFORE_AFTER
			}
		}
		// if then else
		if (i < statements.size() - 2 && statements[i]->isBranch()) {
			SyntaxNode *tThen = statements[i]->getOutEdge(root, 0);
			SyntaxNode *tElse = statements[i]->getOutEdge(root, 1);

			assert(tThen && tElse);
			if (((tThen == statements[i+2] && tElse == statements[i+1]) ||
				 (tThen == statements[i+1] && tElse == statements[i+2])) &&
				tThen->getNumOutEdges() == 1 && tElse->getNumOutEdges() == 1) {
				SyntaxNode *else_out = tElse->getOutEdge(root, 0);
				SyntaxNode *then_out = tThen->getOutEdge(root, 0);

				if (else_out == then_out) {
					std::cerr << "successor: if then else" << std::endl;
					SyntaxNode *n = root->clone();
					n->setDepth(root->getDepth() + 1);
					n = n->replace(tThen, NULL);
					n = n->replace(tElse, NULL);
					IfThenElseSyntaxNode *nif = new IfThenElseSyntaxNode();
					nif->setCond(statements[i]->getBB()->getCond()->clone());
					nif->setBB(statements[i]->getBB());
					nif->setThen(tThen->clone());
					nif->setElse(tElse->clone());
					n = n->replace(statements[i], nif);
					successors.push_back(n);
					//PRINT_BEFORE_AFTER
				}
			}
		}

		// pretested loop
		if (i < statements.size() - 2 && statements[i]->isBranch()) {
			SyntaxNode *tBody = statements[i]->getOutEdge(root, 0);
			SyntaxNode *tFollow =  statements[i]->getOutEdge(root, 1);

			assert(tBody && tFollow);
			if (tBody == statements[i+1] && tFollow == statements[i+2] &&
				tBody->getNumOutEdges() == 1 &&
				tBody->getOutEdge(root, 0) == statements[i]) {
				std::cerr << "successor: pretested loop" << std::endl;
				SyntaxNode *n = root->clone();
				n->setDepth(root->getDepth() + 1);
				n = n->replace(tBody, NULL);
				PretestedLoopSyntaxNode *nloop = new PretestedLoopSyntaxNode();
				nloop->setCond(statements[i]->getBB()->getCond()->clone());
				nloop->setBB(statements[i]->getBB());
				nloop->setBody(tBody->clone());
				n = n->replace(statements[i], nloop);
				successors.push_back(n);
				//PRINT_BEFORE_AFTER
			}
		}

		// posttested loop
		if (i > 0 && i < statements.size()-1 && statements[i]->isBranch()) {
			SyntaxNode *tBody = statements[i]->getOutEdge(root, 0);
			SyntaxNode *tFollow =  statements[i]->getOutEdge(root, 1);

			assert(tBody && tFollow);
			if (tBody == statements[i-1] && tFollow == statements[i+1] &&
				tBody->getNumOutEdges() == 1 &&
				tBody->getOutEdge(root, 0) == statements[i]) {
				std::cerr << "successor: posttested loop" << std::endl;
				SyntaxNode *n = root->clone();
				n->setDepth(root->getDepth() + 1);
				n = n->replace(tBody, NULL);
				PostTestedLoopSyntaxNode *nloop =
												new PostTestedLoopSyntaxNode();
				nloop->setCond(statements[i]->getBB()->getCond()->clone());
				nloop->setBB(statements[i]->getBB());
				nloop->setBody(tBody->clone());
				n = n->replace(statements[i], nloop);
				successors.push_back(n);
				//PRINT_BEFORE_AFTER
			}
		}

		// infinite loop
		if (statements[i]->getNumOutEdges() == 1 &&
			statements[i]->getOutEdge(root, 0) == statements[i]) {
			std::cerr << "successor: infinite loop" << std::endl;
			SyntaxNode *n = root->clone();
			n->setDepth(root->getDepth() + 1);
			InfiniteLoopSyntaxNode *nloop = new InfiniteLoopSyntaxNode();
			nloop->setBody(statements[i]->clone());
			n = n->replace(statements[i], nloop);
			successors.push_back(n);
			PRINT_BEFORE_AFTER
		}

		statements[i]->addSuccessors(root, successors);
	}
}

SyntaxNode *BlockSyntaxNode::clone()
{
	BlockSyntaxNode *b = new BlockSyntaxNode();
	b->correspond = this;
	if (pbb)
		b->pbb = pbb;
	else
		for (unsigned i = 0; i < statements.size(); i++)
			b->addStatement(statements[i]->clone());
	return b;
}

SyntaxNode *BlockSyntaxNode::replace(SyntaxNode *from, SyntaxNode *to)
{
	if (correspond == from)
		return to;

	if (pbb == NULL) {
		std::vector<SyntaxNode*> news;
		for (unsigned i = 0; i < statements.size(); i++) {
			SyntaxNode *n = statements[i];
			if (statements[i]->getCorrespond() == from)
				n = to;
			else
				n = statements[i]->replace(from, to);
			if (n)
				news.push_back(n);
		}
		statements.resize(news.size());
		for (unsigned i = 0; i < news.size(); i++)
			statements[i] = news[i];
	}
	return this;
}

IfThenSyntaxNode::IfThenSyntaxNode() : pThen(NULL), cond(NULL)
{
}

IfThenSyntaxNode::~IfThenSyntaxNode()
{
	if (pThen)
		delete pThen;
}

SyntaxNode *IfThenSyntaxNode::getOutEdge(SyntaxNode *root, int n) {
	SyntaxNode *n1 = root->findNodeFor(pbb->getOutEdge(0));
	assert(n1 != pThen);
	return n1;
}

int IfThenSyntaxNode::evaluate(SyntaxNode *root)
{
	int n = 1;
	n += pThen->evaluate(root);
	return n;
}

void IfThenSyntaxNode::addSuccessors(SyntaxNode *root,
									 std::vector<SyntaxNode*> &successors)
{
	pThen->addSuccessors(root, successors);
}

SyntaxNode *IfThenSyntaxNode::clone()
{
	IfThenSyntaxNode *b = new IfThenSyntaxNode();
	b->correspond = this;
	b->pbb = pbb;
	b->cond = cond->clone();
	b->pThen = pThen->clone();
	return b;
}

SyntaxNode *IfThenSyntaxNode::replace(SyntaxNode *from, SyntaxNode *to)
{
	assert(correspond != from);
	if (pThen->getCorrespond() == from) {
		assert(to);
		pThen = to;
	} else
		pThen = pThen->replace(from, to);
	return this;
}

SyntaxNode *IfThenSyntaxNode::findNodeFor(PBB bb)
{
	if (pbb == bb)
		return this;
	return pThen->findNodeFor(bb);
}

void IfThenSyntaxNode::printAST(SyntaxNode *root, std::ostream &os)
{
	os << std::setw(4) << std::dec << nodenum << " ";
	os << "[label=\"if " << cond << " \"];" << std::endl;
	pThen->printAST(root, os);
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << pThen->getNumber() << " [label=then];" << std::endl;
	SyntaxNode *follows = root->findNodeFor(pbb->getOutEdge(0));
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << follows->getNumber() << " [style=dotted];" << std::endl;
}

IfThenElseSyntaxNode::IfThenElseSyntaxNode() : pThen(NULL), pElse(NULL),
	cond(NULL)
{
}

IfThenElseSyntaxNode::~IfThenElseSyntaxNode()
{
	if (pThen)
		delete pThen;
	if (pElse)
		delete pElse;
}

int IfThenElseSyntaxNode::evaluate(SyntaxNode *root)
{
	int n = 1;
	n += pThen->evaluate(root);
	n += pElse->evaluate(root);
	return n;
}

void IfThenElseSyntaxNode::addSuccessors(SyntaxNode *root,
										 std::vector<SyntaxNode*> &successors)
{
	// at the moment we can always ignore gotos at the end of
	// then and else, because we assume they have the same
	// follow
	if (pThen->getNumOutEdges() == 1 && pThen->endsWithGoto()) {
		std::cerr << "successor: ignoring goto at end of then of if then else"
				  << std::endl;
		SyntaxNode *n = root->clone();
		n->setDepth(root->getDepth() + 1);
		SyntaxNode *nThen = pThen->clone();
		nThen->ignoreGoto();
		n = n->replace(pThen, nThen);
		successors.push_back(n);
	}

	if (pElse->getNumOutEdges() == 1 && pElse->endsWithGoto()) {
		std::cerr << "successor: ignoring goto at end of else of if then else"
				  << std::endl;
		SyntaxNode *n = root->clone();
		n->setDepth(root->getDepth() + 1);
		SyntaxNode *nElse = pElse->clone();
		nElse->ignoreGoto();
		n = n->replace(pElse, nElse);
		successors.push_back(n);
	}

	pThen->addSuccessors(root, successors);
	pElse->addSuccessors(root, successors);
}

SyntaxNode *IfThenElseSyntaxNode::clone()
{
	IfThenElseSyntaxNode *b = new IfThenElseSyntaxNode();
	b->correspond = this;
	b->pbb = pbb;
	b->cond = cond->clone();
	b->pThen = pThen->clone();
	b->pElse = pElse->clone();
	return b;
}

SyntaxNode *IfThenElseSyntaxNode::replace(SyntaxNode *from, SyntaxNode *to)
{
	assert(correspond != from);
	if (pThen->getCorrespond() == from) {
		assert(to);
		pThen = to;
	} else
		pThen = pThen->replace(from, to);
	if (pElse->getCorrespond() == from) {
		assert(to);
		pElse = to;
	} else
		pElse = pElse->replace(from, to);
	return this;
}

SyntaxNode *IfThenElseSyntaxNode::findNodeFor(PBB bb)
{
	if (pbb == bb)
		return this;
	SyntaxNode *n = pThen->findNodeFor(bb);
	if (n == NULL)
		n = pElse->findNodeFor(bb);
	return n;
}

void IfThenElseSyntaxNode::printAST(SyntaxNode *root, std::ostream &os)
{
	os << std::setw(4) << std::dec << nodenum << " ";
	os << "[label=\"if " << cond << " \"];" << std::endl;
	pThen->printAST(root, os);
	pElse->printAST(root, os);
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << pThen->getNumber() << " [label=then];" << std::endl;
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << pElse->getNumber() << " [label=else];" << std::endl;
}

PretestedLoopSyntaxNode::PretestedLoopSyntaxNode() : pBody(NULL), cond(NULL)
{
}

PretestedLoopSyntaxNode::~PretestedLoopSyntaxNode()
{
	if (pBody)
		delete pBody;
	if (cond)
		delete cond;
}

SyntaxNode *PretestedLoopSyntaxNode::getOutEdge(SyntaxNode *root, int n) {
	return root->findNodeFor(pbb->getOutEdge(1));
}

int PretestedLoopSyntaxNode::evaluate(SyntaxNode *root)
{
	int n = 1;
	n += pBody->evaluate(root);
	return n;
}

void PretestedLoopSyntaxNode::addSuccessors(SyntaxNode *root,
										std::vector<SyntaxNode*> &successors)
{
	// we can always ignore gotos at the end of the body.
	if (pBody->getNumOutEdges() == 1 && pBody->endsWithGoto()) {
		std::cerr << "successor: ignoring goto at end of body of pretested "
				  << "loop" << std::endl;
		SyntaxNode *out = pBody->getOutEdge(root, 0);
		assert(out->startsWith(this));
		SyntaxNode *n = root->clone();
		n->setDepth(root->getDepth() + 1);
		SyntaxNode *nBody = pBody->clone();
		nBody->ignoreGoto();
		n = n->replace(pBody, nBody);
		successors.push_back(n);
	}

	pBody->addSuccessors(root, successors);
}

SyntaxNode *PretestedLoopSyntaxNode::clone()
{
	PretestedLoopSyntaxNode *b = new PretestedLoopSyntaxNode();
	b->correspond = this;
	b->pbb = pbb;
	b->cond = cond->clone();
	b->pBody = pBody->clone();
	return b;
}

SyntaxNode *PretestedLoopSyntaxNode::replace(SyntaxNode *from, SyntaxNode *to)
{
	assert(correspond != from);
	if (pBody->getCorrespond() == from) {
		assert(to);
		pBody = to;
	} else
		pBody = pBody->replace(from, to);
	return this;
}

SyntaxNode *PretestedLoopSyntaxNode::findNodeFor(PBB bb)
{
	if (pbb == bb)
		return this;
	return pBody->findNodeFor(bb);
}

void PretestedLoopSyntaxNode::printAST(SyntaxNode *root, std::ostream &os)
{
	os << std::setw(4) << std::dec << nodenum << " ";
	os << "[label=\"loop pretested ";
	os	<< cond << " \"];" << std::endl;
	pBody->printAST(root, os);
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << pBody->getNumber() << ";" << std::endl;
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << getOutEdge(root, 0)->getNumber()
				 << " [style=dotted];" << std::endl;
}

PostTestedLoopSyntaxNode::PostTestedLoopSyntaxNode() : pBody(NULL), cond(NULL)
{
}

PostTestedLoopSyntaxNode::~PostTestedLoopSyntaxNode()
{
	if (pBody)
		delete pBody;
	if (cond)
		delete cond;
}

SyntaxNode *PostTestedLoopSyntaxNode::getOutEdge(SyntaxNode *root, int n) {
	return root->findNodeFor(pbb->getOutEdge(1));
}

int PostTestedLoopSyntaxNode::evaluate(SyntaxNode *root)
{
	int n = 1;
	n += pBody->evaluate(root);
	return n;
}

void PostTestedLoopSyntaxNode::addSuccessors(SyntaxNode *root,
										std::vector<SyntaxNode*> &successors)
{
	// we can always ignore gotos at the end of the body.
	if (pBody->getNumOutEdges() == 1 && pBody->endsWithGoto()) {
		std::cerr << "successor: ignoring goto at end of body of posttested "
				  << "loop" << std::endl;
		assert(pBody->getOutEdge(root, 0) == this);
		SyntaxNode *n = root->clone();
		n->setDepth(root->getDepth() + 1);
		SyntaxNode *nBody = pBody->clone();
		nBody->ignoreGoto();
		n = n->replace(pBody, nBody);
		successors.push_back(n);
	}

	pBody->addSuccessors(root, successors);
}

SyntaxNode *PostTestedLoopSyntaxNode::clone()
{
	PostTestedLoopSyntaxNode *b = new PostTestedLoopSyntaxNode();
	b->correspond = this;
	b->pbb = pbb;
	b->cond = cond->clone();
	b->pBody = pBody->clone();
	return b;
}

SyntaxNode *PostTestedLoopSyntaxNode::replace(SyntaxNode *from, SyntaxNode *to)
{
	assert(correspond != from);
	if (pBody->getCorrespond() == from) {
		assert(to);
		pBody = to;
	} else
		pBody = pBody->replace(from, to);
	return this;
}

SyntaxNode *PostTestedLoopSyntaxNode::findNodeFor(PBB bb)
{
	if (pbb == bb)
		return this;
	SyntaxNode *n = pBody->findNodeFor(bb);
	if (n == pBody)
		return this;
	return n;
}

void PostTestedLoopSyntaxNode::printAST(SyntaxNode *root, std::ostream &os)
{
	os << std::setw(4) << std::dec << nodenum << " ";
	os << "[label=\"loop posttested ";
	os	<< cond << " \"];" << std::endl;
	pBody->printAST(root, os);
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << pBody->getNumber() << ";" << std::endl;
	os << std::setw(4) << std::dec << nodenum << " ";
	os << " -> " << getOutEdge(root, 0)->getNumber()
				 << " [style=dotted];" << std::endl;
}

InfiniteLoopSyntaxNode::InfiniteLoopSyntaxNode() : pBody(NULL)
{
}

InfiniteLoopSyntaxNode::~InfiniteLoopSyntaxNode()
{
	if (pBody)
		delete pBody;
}

int InfiniteLoopSyntaxNode::evaluate(SyntaxNode *root)
{
	int n = 1;
	n += pBody->evaluate(root);
	return n;
}

void InfiniteLoopSyntaxNode::addSuccessors(SyntaxNode *root,
										std::vector<SyntaxNode*> &successors)
{
	// we can always ignore gotos at the end of the body.
	if (pBody->getNumOutEdges() == 1 && pBody->endsWithGoto()) {
		std::cerr << "successor: ignoring goto at end of body of infinite "
				  << "loop" << std::endl;
		assert(pBody->getOutEdge(root, 0) == this);
		SyntaxNode *n = root->clone();
		n->setDepth(root->getDepth() + 1);
		SyntaxNode *nBody = pBody->clone();
		nBody->ignoreGoto();
		n = n->replace(pBody, nBody);
		successors.push_back(n);
	}

	pBody->addSuccessors(root, successors);
}

SyntaxNode *InfiniteLoopSyntaxNode::clone()
{
	InfiniteLoopSyntaxNode *b = new InfiniteLoopSyntaxNode();
	b->correspond = this;
	b->pbb = pbb;
	b->pBody = pBody->clone();
	return b;
}

SyntaxNode *InfiniteLoopSyntaxNode::replace(SyntaxNode *from, SyntaxNode *to)
{
	assert(correspond != from);
	if (pBody->getCorrespond() == from) {
		assert(to);
		pBody = to;
	} else
		pBody = pBody->replace(from, to);
	return this;
}

SyntaxNode *InfiniteLoopSyntaxNode::findNodeFor(PBB bb)
{
	if (pbb == bb)
		return this;
	SyntaxNode *n = pBody->findNodeFor(bb);
	if (n == pBody)
		return this;
	return n;
}

void InfiniteLoopSyntaxNode::printAST(SyntaxNode *root, std::ostream &os)
{
	os << std::setw(4) << std::dec << nodenum << " ";
	os << "[label=\"loop infinite\"];" << std::endl;
	if (pBody)
		pBody->printAST(root, os);
	if (pBody) {
		os << std::setw(4) << std::dec << nodenum << " ";
		os << " -> " << pBody->getNumber() << ";" << std::endl;
	}
}


text:
require "pry"
# RSpec set up - come to this by starting with basic setup
#

# Implement the block via `yield` or `&block` keywords

# `yield` (yield)
# `block.call()` via (&block)

# def event(name) #, &block)
#   puts "ALERT: #{name}" if yield
# end

def event(name, &block)
  # convert blocks to `Proc`s and stores them in a hash :-) #########
  # has is a top-level instance variable so it is visible

  # name is the "text we right" of the method
  @events[name] = block # still a proc...I haven't called `call()`
end

# def setup(when = :each, &block)
def setup(&block)
  @setups << block
end

# https://ruby-doc.org/core-1.9.3/Dir.html#method-c-glob
# load File.join(Dir.pwd,"metaprogramming", "blocks", "events.rb")
# Dir.glob("*")
Dir.glob("**/*events.rb").each do |rspec_file|
  @events = {}
  @setups = []
  load rspec_file

  @events.each_pair do |event_name, event_proc| # vs. `each`
    my_first_clean_room = Object.new # Scope protection

    @setups.each do |setup|
      # setup.call

      my_first_clean_room.instance_eval(&setup)
    end
    # @setups.each(&:call)
    # puts "ALERT: #{event_name}" if event_block.call
    puts "ALERT: #{event_name}" if my_first_clean_room.instance_eval(&event_proc)
  end
end

# Setting up sky
# Setting up mountains
# ALERT: the sky is falling
# Setting up sky
# Setting up mountains
# ALERT: it's getting closer


text: require "responsive_images/responsive_images"


text:
<link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/cymain.css" />

<li class="<if condition="ACTION_NAME EQ 'index'">current</if> tabli" id="tab0">$token))}">物业公司介绍

<li class="<if condition="ACTION_NAME EQ 'son' ">current</if> tabli" id="tab2">$token))}">小区

<li class="<if condition="ACTION_NAME EQ 'housetype' ">current</if> tabli" id="tab2">$token))}">业主服务

<li class="<if condition="ACTION_NAME EQ 'album' or ACTION_NAME EQ 'album_add'">current</if> tabli" id="tab5">$token))}">物业相册

<li class="<if condition="ACTION_NAME EQ 'expert'">current</if> tabli" id="tab5">$token))}">业主印象

<li class="<if condition="ACTION_NAME EQ 'wuyeindex'">current</if> tabli" id="tab6">$token))}">预约管理

<li class="<if condition="ACTION_NAME EQ 'aboutus'">current</if> tabli" id="tab6">$token))}">关于我们


text:
using System;
namespace OneSignal.Xamarin.Core {
   [Serializable]
   public sealed class DeviceState {

      public NotificationPermission notificationPermission;

      public bool areNotificationsEnabled;

      public bool isSubscribed;

      public string userId;

      public string pushToken;

      public bool isPushDisabled;

      public bool isEmailSubscribed;

      public string emailUserId;

      public string emailAddress;

      public bool isSMSSubscribed;

      public string smsNumber;

      public string smsUserId;
   }
}


text:
puts "Time for a 10 second nap!"

sleep(10)

puts "Nap time done!"


text:
'use strict';

module.exports = function(environment) {
  let ENV = {
    modulePrefix: 'ember-cli-diff',
    environment: environment
  };

  return ENV;
};


text:
import $ from 'jquery';
import 'ui/filters/short_dots';
import uiModules from 'ui/modules';
const module = uiModules.get('kibana');

module.directive('fieldName', function ($compile, $rootScope, $filter) {
  return {
    restrict: 'AE',
    scope: {
      'field': '=',
      'fieldName': '=',
      'fieldType': '='
    },
    link: function ($scope, $el) {

      const typeIcon = function (fieldType) {
        switch (fieldType) {
          case 'source':
            return '';
          case 'string':
            return 't';
          case 'murmur3':
            return 'h';
          case 'number':
            return '#';
          case 'date':
            return '';
          case 'ip':
            return '';
          case 'geo_point':
            return '';
          case 'boolean':
            return '';
          case 'conflict':
            return '';
          default:
            return '?';
        }
      };

      $rootScope.$watchMulti.call($scope, [
        'field',
        'fieldName',
        'fieldType',
        'field.rowCount'
      ], function () {

        const type = $scope.field ? $scope.field.type : $scope.fieldType;
        const name = $scope.field ? $scope.field.name : $scope.fieldName;
        const results = $scope.field ? !$scope.field.rowCount && !$scope.field.scripted : false;
        const scripted = $scope.field ? $scope.field.scripted : false;

        const displayName = $filter('shortDots')(name);

        $el
          .attr('title', name)
          .toggleClass('no-results', results)
          .toggleClass('scripted', scripted)
          .prepend(typeIcon(type))
          .append($('')
            .text(displayName)
            .addClass('discover-field-name')
          );
      });
    }
  };
});


text:
<!DOCTYPE html>

  <title>test of border-image</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="Content-Style-Type" content="text/css">

border.png
second longer longer longer longer longer longer line
third longer longer longer longer longer longer line


text:
define([
  'jquery',
  'underscore',
  'parse',
  'scripts/router' // Request router.js
], function($, _, Parse, Router){
  var initialize = function(){
    //Put your parse keys here!
    Parse.initialize("Application ID Key", "Javascript Key");
    // Pass in our Router module and call it's initialize function
    Router.initialize();
  }

  return {
    initialize: initialize
  };
});


text:
'use strict';

angular.module('PractitionerListApp.version', [
  'PractitionerListApp.version.interpolate-filter',
  'PractitionerListApp.version.version-directive'
])

.value('version', '0.1');


text:
<?php
namespace restful\modules\v1\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use yii\filters\VerbFilter;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;

/**
 * Get token.
 *
 * @author Jin Chen <jin.chen@startlight-sms.com>
 */
class Oauth2Controller extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ],
            'exceptionFilter' => [
                'class' => ErrorToExceptionFilter::className()
            ]
        ];
    }

    public function actionToken()
    {
        $server = $this->module->getServer();
        $request = $this->module->getRequest();
        $response = $server->handleTokenRequest($request);

        return $response->getParameters();
    }

    public function actionAuthorize()
    {
    	$server = $this->module->getServer();
    	$request = $this->module->getRequest();
    	$response = $this->module->getResponse();
	    if (!$server->validateAuthorizeRequest($request, $response)) {
		    return $server->getResponse();
		}

		$server->handleAuthorizeRequest($request, $response, true);
		$code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=') + 5, 40);

		return $code;
    }
}


text:
from django.conf import settings
from django.contrib.auth.models import User
from cms.tests.base import CMSTestCase
from cms.models import Page
from cms.menu import CMSMenu
from menus.templatetags.menu_tags import show_menu, show_sub_menu,\
    show_breadcrumb, language_chooser, page_language_url, show_menu_below_id
from menus.menu_pool import menu_pool
from menus.base import NavigationNode

class MenusTestCase(CMSTestCase):

    def setUp(self):
        settings.CMS_MODERATOR = False
        u = User(username="test", is_staff = True, is_active = True, is_superuser = True)
        u.set_password("test")
        u.save()
        self.login_user(u)
        if not menu_pool.discovered:
            menu_pool.discover_menus()
        self.old_menu = menu_pool.menus
        menu_pool.menus = {'CMSMenu':self.old_menu['CMSMenu']}
        menu_pool.clear(settings.SITE_ID)
        self.create_some_nodes()

    def tearDown(self):
        menu_pool.menus = self.old_menu

    def create_some_nodes(self):
        """
        Creates the following structure:

        + P1
        | + P2
        |   + P3
        + P4
        | + P5
        + P6 (not in menu)
          + P7
          + P8

        """
        self.page1 = self.create_page(parent_page=None, published=True, in_navigation=True)
        self.page2 = self.create_page(parent_page=self.page1, published=True, in_navigation=True)
        self.page3 = self.create_page(parent_page=self.page2, published=True, in_navigation=True)
        self.page4 = self.create_page(parent_page=None, published=True, in_navigation=True)
        self.page5 = self.create_page(parent_page=self.page4, published=True, in_navigation=True)
        self.page6 = self.create_page(parent_page=None, published=True, in_navigation=False)
        self.page7 = self.create_page(parent_page=self.page6, published=True, in_navigation=True)
        self.page8 = self.create_page(parent_page=self.page6, published=True, in_navigation=True)
        self.all_pages = [self.page1, self.page2, self.page3, self.page4,
                          self.page5, self.page6, self.page7, self.page8]
        self.top_level_pages = [self.page1, self.page4]
        self.level1_pages = [self.page2, self.page5,self.page7,self.page8]
        self.level2_pages = [self.page3]

    def test_01_basic_cms_menu(self):
        self.assertEqual(len(menu_pool.menus), 1)
        response = self.client.get("/")
        self.assertEquals(response.status_code, 200)
        request = self.get_request()

        # test the cms menu class
        menu = CMSMenu()
        nodes = menu.get_nodes(request)
        self.assertEqual(len(nodes), len(self.all_pages))

    def test_02_show_menu(self):

        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context)['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].selected, True)
        self.assertEqual(nodes[0].sibling, False)
        self.assertEqual(nodes[0].descendant, False)
        self.assertEqual(nodes[0].children[0].descendant, True)
        self.assertEqual(nodes[0].children[0].children[0].descendant, True)
        self.assertEqual(nodes[0].get_absolute_url(), "/")
        self.assertEqual(nodes[1].get_absolute_url(), self.page4.get_absolute_url())
        self.assertEqual(nodes[1].sibling, True)
        self.assertEqual(nodes[1].selected, False)

    def test_03_only_active_tree(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context, 0, 100, 0, 100)['children']
        self.assertEqual(len(nodes[1].children), 0)
        self.assertEqual(len(nodes[0].children), 1)
        self.assertEqual(len(nodes[0].children[0].children), 1)
        context = self.get_context(path=self.page4.get_absolute_url())
        nodes = show_menu(context, 0, 100, 0, 100)['children']
        self.assertEqual(len(nodes[1].children), 1)
        self.assertEqual(len(nodes[0].children), 0)

    def test_04_only_one_active_level(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context, 0, 100, 0, 1)['children']
        self.assertEqual(len(nodes[1].children), 0)
        self.assertEqual(len(nodes[0].children), 1)
        self.assertEqual(len(nodes[0].children[0].children), 0)

    def test_05_only_level_zero(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context, 0, 0, 0, 0)['children']
        for node in nodes:
            self.assertEqual(len(node.children), 0)

    def test_06_only_level_one(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context, 1, 1, 100, 100)['children']
        self.assertEqual(len(nodes), len(self.level1_pages))
        for node in nodes:
            self.assertEqual(len(node.children), 0)

    def test_07_only_level_one_active(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context, 1, 1, 0, 100)['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].descendant, True)
        self.assertEqual(len(nodes[0].children), 0)

    def test_08_level_zero_and_one(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_menu(context, 0, 1, 100, 100)['children']
        self.assertEqual(len(nodes), 2)
        for node in nodes:
            self.assertEqual(len(node.children), 1)

    def test_09_show_submenu(self):
        context = self.get_context()
        # test standard show_menu
        nodes = show_sub_menu(context)['children']
        self.assertEqual(nodes[0].descendant, True)
        self.assertEqual(len(nodes), 1)
        self.assertEqual(len(nodes[0].children), 1)

        nodes = show_sub_menu(context, 1)['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(len(nodes[0].children), 0)

    def test_10_show_breadcrumb(self):
        context = self.get_context(path=self.page3.get_absolute_url())
        nodes = show_breadcrumb(context)['ancestors']
        self.assertEqual(len(nodes), 3)
        nodes = show_breadcrumb(context, 1)['ancestors']
        self.assertEqual(len(nodes), 2)
        context = self.get_context()
        nodes = show_breadcrumb(context)['ancestors']
        self.assertEqual(len(nodes), 1)
        nodes = show_breadcrumb(context, 1)['ancestors']
        self.assertEqual(len(nodes), 0)

        page1 = Page.objects.get(pk=self.page1.pk)
        page1.in_navigation = False
        page1.save()
        page2 = Page.objects.get(pk=self.page2.pk)
        context = self.get_context(path=self.page2.get_absolute_url())
        nodes = show_breadcrumb(context)['ancestors']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].get_absolute_url(), "/")
        self.assertEqual(isinstance(nodes[0], NavigationNode), True)
        self.assertEqual(nodes[1].get_absolute_url(), page2.get_absolute_url())

    def test_11_language_chooser(self):
        # test simple language chooser with default args
        context = self.get_context(path=self.page3.get_absolute_url())
        new_context = language_chooser(context)
        self.assertEqual(len(new_context['languages']), len(settings.CMS_SITE_LANGUAGES[settings.SITE_ID]))
        self.assertEqual(new_context['current_language'], settings.LANGUAGE_CODE)
        # try a different template and some different args
        new_context = language_chooser(context, 'menu/test_language_chooser.html')
        self.assertEqual(new_context['template'], 'menu/test_language_chooser.html')
        new_context = language_chooser(context, 'short', 'menu/test_language_chooser.html')
        self.assertEqual(new_context['template'], 'menu/test_language_chooser.html')
        for lang in new_context['languages']:
            self.assertEqual(*lang)

    def test_12_page_language_url(self):
        context = self.get_context(path=self.page3.get_absolute_url())
        url = page_language_url(context, settings.LANGUAGES[0][0])['content']
        self.assertEqual( url, "/%s%s" % (settings.LANGUAGES[0][0], self.page3.get_absolute_url()))

    def test_13_show_menu_below_id(self):
        page2 = Page.objects.get(pk=self.page2.pk)
        page2.reverse_id = "hello"
        page2.save()
        page2 = Page.objects.get(pk=self.page2.pk)
        self.assertEqual(page2.reverse_id, "hello")
        context = self.get_context(path=self.page5.get_absolute_url())
        nodes = show_menu_below_id(context, "hello")['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), self.page3.get_absolute_url())
        page2.in_navigation = False
        page2.save()
        context = self.get_context(path=self.page5.get_absolute_url())
        nodes = show_menu_below_id(context, "hello")['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), self.page3.get_absolute_url())

    def test_14_unpublished(self):
        page2 = Page.objects.get(pk=self.page2.pk)
        page2.published = False
        page2.save()
        context = self.get_context()
        nodes = show_menu(context)['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(len(nodes[0].children), 0)

    def test_15_home_not_in_menu(self):
        page1 = Page.objects.get(pk=self.page1.pk)
        page1.in_navigation = False
        page1.save()
        page4 = Page.objects.get(pk=self.page4.pk)
        page4.in_navigation = False
        page4.save()
        context = self.get_context()
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), "/%s/" % self.page2.get_slug())
        self.assertEqual(nodes[0].children[0].get_absolute_url(), "/%s/%s/" % (self.page2.get_slug(), self.page3.get_slug()))
        page4 = Page.objects.get(pk=self.page4.pk)
        page4.in_navigation = True
        page4.save()
        menu_pool.clear(settings.SITE_ID)
        context = self.get_context()
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 2)

    def test_15_empty_menu(self):
        Page.objects.all().delete()
        request = self.get_request()
        nodes = menu_pool.get_nodes(request)
        context = self.get_context()
        nodes = show_menu(context, 0, 100, 100, 100)['children']

    def test_16_softroot(self):
        page2 = Page.objects.get(pk=self.page2.pk)
        page2.soft_root = True
        page2.save()
        context = self.get_context(path=page2.get_absolute_url())
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), page2.get_absolute_url())
        page3 = Page.objects.get(pk=self.page3.pk)
        context = self.get_context(path=page3.get_absolute_url())
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), page2.get_absolute_url())

        page1 = Page.objects.get(pk=self.page1.pk)
        context = self.get_context(path=page1.get_absolute_url())
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].get_absolute_url(), page1.get_absolute_url())
        self.assertEqual(len(nodes[0].children[0].children), 0)

        context = self.get_context(path="/no/real/path/")
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].get_absolute_url(), page1.get_absolute_url())
        self.assertEqual(len(nodes[0].children[0].children), 0)

        page5 = Page.objects.get(pk=self.page5.pk)
        context = self.get_context(path=page5.get_absolute_url())
        nodes = show_menu(context, 0, 100, 100, 100)['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].get_absolute_url(), page1.get_absolute_url())
        self.assertEqual(len(nodes[0].children[0].children), 0)

    def test_17_show_submenu_from_non_menu_page(self):
        page6 = Page.objects.get(pk=self.page6.pk)
        context = self.get_context(page6.get_absolute_url())
        nodes = show_menu(context, 1, 100, 0, 1)['children']
        self.assertEqual(len(nodes), len(page6.children.all()))
        page7 = Page.objects.get(pk=self.page7.pk)
        context = self.get_context(page7.get_absolute_url())
        nodes = show_menu(context, 1, 100, 0, 1)['children']
        self.assertEqual(len(nodes), len(page6.children.all()))
        nodes = show_menu(context, 2, 100, 0, 1)['children']
        self.assertEqual(len(nodes), len(page7.children.all()))


text:
@interface WKInterfaceObject ()

- (void)setImage:(UIImage *)image NS_REQUIRES_SUPER;
- (void)setImageData:(NSData *)imageData NS_REQUIRES_SUPER;
- (void)setImageNamed:(NSString *)imageName NS_REQUIRES_SUPER;

- (void)setTintColor:(UIColor *)tintColor NS_REQUIRES_SUPER;

- (void)startAnimating NS_REQUIRES_SUPER;
- (void)startAnimatingWithImagesInRange:(NSRange)imageRange
                               duration:(NSTimeInterval)duration
                            repeatCount:(NSInteger)repeatCount NS_REQUIRES_SUPER;
- (void)stopAnimating NS_REQUIRES_SUPER;

@end

@interface WKInterfaceImage ()

@property (nonatomic) UIImage *image;

@end

@implementation WKInterfaceImage

-(void)setImage:(id)image
{
    _image = [image isKindOfClass:[UIImage class]] ? image : [UIImage imageNamed:image];
    [super setImage:image];
}

- (void)setImageData:(NSData *)imageData
{
    [super setImageData:imageData];
}

- (void)setImageNamed:(NSString *)imageName
{
    [super setImageNamed:imageName];
}

- (void)startAnimating
{
    [super startAnimating];
}

- (void)startAnimatingWithImagesInRange:(NSRange)imageRange duration:(NSTimeInterval)duration repeatCount:(NSInteger)repeatCount
{
    [super startAnimatingWithImagesInRange:imageRange duration:duration repeatCount:repeatCount];
}

- (void)stopAnimating
{
    [super stopAnimating];
}

- (void)setTintColor:(UIColor *)tintColor
{
    [super setTintColor:tintColor];
}

@end


text:
<?xml version="1.0"?>
<project name="chapter03" default="dist">
  <property name="chapter" value="chapter03"/>
  <import file="../build.xml"/>
</project>


text:
package dta.pizzeria.model;

import java.lang.reflect.Field;

import javax.persistence.*;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import dta.pizzeria.exception.StockageException;

@Entity
@NamedQueries({ @NamedQuery(name = "pizza.findAll", query = "SELECT P FROM Pizza P"), @NamedQuery(name = "pizza.findByCode", query = "SELECT P FROM Pizza P WHERE P.code = :code") })
public class Pizza implements Comparable<Pizza> {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	@ToString
	@Column(name = "code", length = 5, nullable = false, unique = true)
	private String code;
	@ToString
	@Column(name = "nom", length = 50, nullable = false)
	private String nom;
	@ToString
	@Column(name = "prix", nullable = false)
	private double prix;
	@ToString
	@Enumerated(EnumType.STRING)
	@Column(name = "categorie", nullable = false)
	private CategoriePizza categorie;

	public Pizza() {
	}

	public Pizza(String code, String nom, double prix, CategoriePizza categorie) {
		this.code = code.toUpperCase();
		this.nom = nom;
		this.prix = prix;
		this.categorie = CategoriePizza.valueOf(categorie.toString().toUpperCase());
	}

	public String getCode() {
		return this.code;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Field field : this.getClass().getDeclaredFields()) {
			if (field.isAnnotationPresent(ToString.class)) {
				try {
					sb.append(field.get(this).toString());
					sb.append(" ");
				} catch (IllegalArgumentException | IllegalAccessException e) {
					throw new StockageException("ToString error", e);
				}
			}
		}
		return sb.toString();

	}

	@Override
	public int compareTo(Pizza o) {
		return this.code.compareTo(o.getCode());
	}

	public CategoriePizza getCategorie() {
		return this.categorie;
	}

	public double getPrix() {
		return this.prix;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj.getClass() != this.getClass()) {
			return false;
		}
		Pizza rhs = (Pizza) obj;
		return new EqualsBuilder().
						append(this.code, rhs.code).
						append(this.nom, rhs.nom).
						append(this.prix, rhs.prix).
						append(this.categorie, this.categorie).
						isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder(17, 37).
						append(this.code).
						append(this.nom).
						append(this.prix).
						append(this.categorie).
						toHashCode();
	}

	public String getNom() {
		return this.nom;
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setNom(String nom) {
		this.nom = nom;
	}

	public void setPrix(double prix) {
		this.prix = prix;
	}

	public void setCategorie(CategoriePizza categorie) {
		this.categorie = categorie;
	}
}


text:
package diameter.Dictionary

case class DictionaryAvpFlags(flagEncrypt:Boolean,
                              flagMadatory:DictionaryAvpFlagValue.Value,
                              flagProtected:DictionaryAvpFlagValue.Value,
                              flagVendorbit:DictionaryAvpFlagValue.Value) {
}


text:
#include <ostream>
#include <sstream>

namespace std {

basic_ostream<char, char_traits<char> > & __cdecl operator<< <char, char_traits<char>, allocator<char> >(
    basic_ostream<char, char_traits<char> > & a, basic_string<char, char_traits<char>, allocator<char> > const & b) // weolar ÎÞ¶¨Òå
{
    ostringstream aCopy;
    aCopy.write(b.c_str(), b.size());
    a << aCopy;
    return a;
}

basic_ostream<char, char_traits<char> > & __cdecl operator<< <char, struct std::char_traits<char> >(
    basic_ostream<char, char_traits<char> > & a, char const * b)
{
    ostringstream aCopy;
    aCopy.write(b, strlen(b));
    a << aCopy;
    return a;
}

}

#endif // USING_VC6RT


text:
"""
Examples for Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.

Project location : https://github.com/areski/python-nvd3
"""

from nvd3 import multiBarChart
import random

#Open File for test
output_file = open('test_multiBarChart.html', 'w')

type = "multiBarChart"
chart = multiBarChart(name=type, height=350)
chart.set_containerheader("\n\n<h2>" + type + "</h2>\n\n")
nb_element = 10
xdata = list(range(nb_element))
ydata = [random.randint(1, 10) for i in range(nb_element)]
ydata2 = [x * 2 for x in ydata]

extra_serie = {"tooltip": {"y_start": "", "y_end": " call"}}
chart.add_serie(name="Count", y=ydata, x=xdata, extra=extra_serie)
extra_serie = {"tooltip": {"y_start": "", "y_end": " min"}}
chart.add_serie(name="Duration", y=ydata2, x=xdata, extra=extra_serie)
chart.buildhtml()

output_file.write(chart.htmlcontent)
#---------------------------------------

#close Html file
output_file.close()


text:
import requests

from humanize import naturalsize
from bs4 import BeautifulSoup as BS
from models import Torrent
from provider import BaseProvider

class Kickass(BaseProvider):

    def __init__(self, base_url):
        super(Kickass, self).__init__(base_url)

    def search(self, query):
        payload = {'q': query, 'field': 'seeder', 'order': 'desc', 'page': '1'}
        search_url = self.base_url + '/json.php'
        data = requests.get(
            search_url, params=payload, headers=self.headers).json()
        torrents = []
        for movie in data['list']:
            t = Torrent()
            t.title = movie['title']
            t.seeds = int(movie['seeds'])
            t.size = naturalsize(movie['size'])
            t.torrent_url = movie['torrentLink']
            torrents.append(t)
        return torrents

    def get_top(self):
        search_url = self.base_url + '/movies'
        data = requests.get(search_url, headers=self.headers).text
        soup = BS(data, "lxml")
        torrents = []
        table = soup.find(class_="data")
        for row in table.find_all('tr')[1:]:
            cells = row.find_all('td')
            t = Torrent()
            t.title = cells[0].find(class_="cellMainLink").text
            t.torrent_url = cells[0].find_all("a")[3].get('href')
            t.size = cells[1].text
            t.seeds = int(cells[4].text)
            torrents.append(t)
        return torrents


text:
import { expect } from 'chai';
import fs from 'fs';

import validator from '../../lib';

describe('Image Validator', () => {
  const rules = {
    imageInput: ['image']
  };

  it('should fail on non image type', () => {
    const result = validator.validate(rules, {
      imageInput: 'README.md'
    });

    expect(result.success).to.equal(false);
    expect(result.messages.imageInput.image).to.equal('Image Input must be an image.');
  });

  it('should success on image buffer type', () => {
    const buffer = fs.readFileSync('test/fixtures/dummyimg.jpeg');
    const result = validator.validate(rules, {
      imageInput: buffer
    });

    expect(result.success).to.equal(true);
  });

  it('should failed on non image buffer type', () => {
    const buffer = fs.readFileSync('README.md');
    const result = validator.validate(rules, {
      imageInput: buffer
    });

    expect(result.success).to.equal(false);
  });

  it('should success on image type', () => {
    const result = validator.validate(rules, {
      imageInput: 'test/fixtures/dummyimg.jpeg'
    });

    expect(result.success).to.equal(true);
  });

  it('should fail on non image type (object input)', () => {
    const result = validator.validate(rules, {
      imageInput: {path: 'README.md'}
    });

    expect(result.success).to.equal(false);
    expect(result.messages.imageInput.image).to.equal('Image Input must be an image.');
  });

  it('should success on image type (object input)', () => {
    const result = validator.validate(rules, {
      imageInput: {path: 'test/fixtures/dummyimg.jpeg'}
    });

    expect(result.success).to.equal(true);
  });
});


text:
package com.example.nils.lec;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.nils.lec.ItemList;
import com.example.nils.lec.R;

import java.util.ArrayList;

/**
 * Created by nils on 02/01/15.
 */
public class ItemsAdapter extends ArrayAdapter<ItemList> {

    public ItemsAdapter(Context context, ArrayList<ItemList> appItems) {
        super(context, 0, appItems);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        ItemList app = getItem(position);

        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null)
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_main, parent, false);

        // Lookup view for data population
        ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
        TextView titre = (TextView) convertView.findViewById(R.id.titre);
        TextView description = (TextView) convertView.findViewById(R.id.description);

        // Populate the data into the template view using the data object
        titre.setText(app.getName());
        description.setText(app.getDescription());
        icon.setImageResource(app.getResId());

        // Return the completed view to render on screen
        return convertView;
    }
}


text:
'use strict';

describe('Ionic View', function() {
  var compile, scope, listElement, listCtrl;

  beforeEach(module('ionic.ui.viewState'));

  beforeEach(inject(function($compile, $rootScope, $controller) {
    compile = $compile;
    scope = $rootScope;
  }));

  it('should init a view', function() {
    var element = compile('<view>me view</view>')(scope);
    expect(element.html()).toEqual('me view');
  });

  it('should add pane classname and remove title from view', function() {
    var element = compile('<view title="\'Me Title\'"></view>')(scope);
    expect(element.attr('title')).toBeUndefined();
    expect(element.hasClass('pane')).toEqual(true);
  });

  it('should broacast view enter on link', function() {
    spyOn(scope, '$broadcast');
    var element = compile('<view title="\'Me Title\'"></view>')(scope);
    expect(scope.$broadcast).toHaveBeenCalledWith('viewState.viewEnter', { title: 'Me Title', navDirection: undefined });

    scope.$navDirection = 'forward';
    element = compile('<view title="\'Me Title\'"></view>')(scope);
    expect(scope.$broadcast).toHaveBeenCalledWith('viewState.viewEnter', { title: 'Me Title', navDirection: 'forward' });
  });

  it('should set hide back button', function() {
    spyOn(scope, '$broadcast');

    var element = compile('<view></view>')(scope);
    var viewScope = element.isolateScope();
    expect(viewScope.hideBackButton).toBeUndefined();
    expect(scope.$broadcast).not.toHaveBeenCalledWith('viewState.showBackButton', false);

    element = compile('<view hide-back-button="true"></view>')(scope);
    viewScope = element.isolateScope();
    expect(viewScope.hideBackButton).toEqual(true);
    expect(scope.$broadcast).toHaveBeenCalledWith('viewState.showBackButton', false);
  });

  it('should show/hide viewBack', function() {
    var element = compile('<button view-back>BUTTON</button>')(scope);
    expect(element.hasClass('hide')).toEqual(true);
    scope.$broadcast('viewState.showBackButton', true);
    expect(element.hasClass('hide')).toEqual(false);
    scope.$broadcast('$viewHistory.historyChange', { showBack: false });
    expect(element.hasClass('hide')).toEqual(true);
  });

  it('should show/hide navBar', function() {
    var element = compile('')(scope);
    expect(element.hasClass('invisible')).toEqual(true);
    scope.$broadcast('viewState.showNavBar', true);
    scope.$digest();
    expect(element.hasClass('invisible')).toEqual(false);
    scope.$broadcast('viewState.showNavBar', false);
    scope.$digest();
    expect(element.hasClass('invisible')).toEqual(true);
  });

  it('should hide navBar when using view attr', function() {
    var element = compile('
<view hide-nav-bar="true"></view>
')(scope);
    scope.$digest();
    var navBar = element.find('header')
    expect(navBar.hasClass('invisible')).toEqual(true);

    element = compile('
<view></view>
')(scope);
    scope.$digest();
    navBar = element.find('header')
    expect(navBar.hasClass('invisible')).toEqual(false);
  });

});


text:
<?xml version='1.0'?>
<test  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation="gYear_maxExclusive003.xsd" >
<!-- facet=maxExclusive and value=2002 and document value=2000 -->
  <foo>2000</foo>
</test>