text:
package uk.org.ngo.squeezer;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

import uk.org.ngo.squeezer.itemlist.action.PlayableItemAction;
import uk.org.ngo.squeezer.service.ISqueezeService;
import uk.org.ngo.squeezer.service.SqueezeService;
import uk.org.ngo.squeezer.util.Scrobble;
import uk.org.ngo.squeezer.util.ThemeManager;

public class SettingsActivity extends PreferenceActivity implements
        OnPreferenceChangeListener, OnSharedPreferenceChangeListener {

    private final String TAG = "SettingsActivity";

    private static final int DIALOG_SCROBBLE_APPS = 0;

    private ISqueezeService service = null;

    private Preference addressPref;

    private IntEditTextPreference fadeInPref;

    private ListPreference onSelectAlbumPref;

    private ListPreference onSelectSongPref;

    private ListPreference onSelectThemePref;

    private final ThemeManager mThemeManager = new ThemeManager();

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            SettingsActivity.this.service = (ISqueezeService) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            service = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mThemeManager.onCreate(this);
        super.onCreate(savedInstanceState);

        bindService(new Intent(this, SqueezeService.class), serviceConnection,
                Context.BIND_AUTO_CREATE);
        Log.d(TAG, "did bindService; service = " + service);

        getPreferenceManager().setSharedPreferencesName(Preferences.NAME);
        addPreferencesFromResource(R.xml.preferences);

        SharedPreferences preferences = getPreferenceManager().getSharedPreferences();
        preferences.registerOnSharedPreferenceChangeListener(this);

        addressPref = findPreference(Preferences.KEY_SERVER_ADDRESS);
        updateAddressSummary();

        fadeInPref = (IntEditTextPreference) findPreference(Preferences.KEY_FADE_IN_SECS);
        fadeInPref.setOnPreferenceChangeListener(this);
        updateFadeInSecondsSummary(preferences.getInt(Preferences.KEY_FADE_IN_SECS, 0));

        CheckBoxPreference autoConnectPref = (CheckBoxPreference) findPreference(
                Preferences.KEY_AUTO_CONNECT);
        autoConnectPref.setChecked(preferences.getBoolean(Preferences.KEY_AUTO_CONNECT, true));

        fillScrobblePreferences(preferences);

        fillPlayableItemSelectionPreferences();

        fillThemeSelectionPreferences();

        CheckBoxPreference startSqueezePlayerPref = (CheckBoxPreference) findPreference(
                Preferences.KEY_SQUEEZEPLAYER_ENABLED);
        startSqueezePlayerPref.setChecked(preferences.getBoolean(Preferences.KEY_SQUEEZEPLAYER_ENABLED, true));
    }

    private void fillScrobblePreferences(SharedPreferences preferences) {
        CheckBoxPreference scrobblePref = (CheckBoxPreference) findPreference(
                Preferences.KEY_SCROBBLE_ENABLED);
        scrobblePref.setOnPreferenceChangeListener(this);

        if (!Scrobble.canScrobble()) {
            scrobblePref.setSummaryOff(getString(R.string.settings_scrobble_noapp));
            scrobblePref.setChecked(false);
        } else {
            scrobblePref.setSummaryOff(getString(R.string.settings_scrobble_off));

            scrobblePref
                    .setChecked(preferences.getBoolean(Preferences.KEY_SCROBBLE_ENABLED, false));

            // If an old KEY_SCROBBLE preference exists, use it, delete it, and
            // upgrade it to the new KEY_SCROBBLE_ENABLED preference.
            if (preferences.contains(Preferences.KEY_SCROBBLE)) {
                boolean enabled = (Integer.parseInt(
                        preferences.getString(Preferences.KEY_SCROBBLE, "0")) > 0);
                scrobblePref.setChecked(enabled);
                Editor editor = preferences.edit();
                editor.putBoolean(Preferences.KEY_SCROBBLE_ENABLED, enabled);
                editor.remove(Preferences.KEY_SCROBBLE);
                editor.commit();
            }
        }
    }

    private void fillPlayableItemSelectionPreferences() {
        String noneLabel = getString(PlayableItemAction.Type.NONE.labelId);
        String addLabel = getString(PlayableItemAction.Type.ADD.labelId);
        String playLabel = getString(PlayableItemAction.Type.PLAY.labelId);
        String insertLabel = getString(PlayableItemAction.Type.INSERT.labelId);
        String browseLabel = getString(PlayableItemAction.Type.BROWSE.labelId);

        onSelectAlbumPref = (ListPreference) findPreference(Preferences.KEY_ON_SELECT_ALBUM_ACTION);
        onSelectAlbumPref.setEntryValues(new String[]{
                PlayableItemAction.Type.PLAY.name(),
                PlayableItemAction.Type.INSERT.name(),
                PlayableItemAction.Type.ADD.name(),
                PlayableItemAction.Type.BROWSE.name()
        });
        onSelectAlbumPref.setEntries(new String[]{playLabel, insertLabel,
                addLabel, browseLabel});
        onSelectAlbumPref.setDefaultValue(PlayableItemAction.Type.BROWSE.name());
        if (onSelectAlbumPref.getValue() == null) {
            onSelectAlbumPref.setValue(PlayableItemAction.Type.BROWSE.name());
        }
        onSelectAlbumPref.setOnPreferenceChangeListener(this);
        updateSelectAlbumSummary(onSelectAlbumPref.getValue());

        onSelectSongPref = (ListPreference) findPreference(Preferences.KEY_ON_SELECT_SONG_ACTION);
        onSelectSongPref.setEntryValues(new String[]{
                PlayableItemAction.Type.NONE.name(),
                PlayableItemAction.Type.PLAY.name(),
                PlayableItemAction.Type.INSERT.name(),
                PlayableItemAction.Type.ADD.name()
        });
        onSelectSongPref.setEntries(new String[]{noneLabel, playLabel,
                insertLabel, addLabel});
        onSelectSongPref.setDefaultValue(PlayableItemAction.Type.NONE.name());
        if (onSelectSongPref.getValue() == null) {
            onSelectSongPref.setValue(PlayableItemAction.Type.NONE.name());
        }
        onSelectSongPref.setOnPreferenceChangeListener(this);
        updateSelectSongSummary(onSelectSongPref.getValue());
    }

    private void fillThemeSelectionPreferences() {
        onSelectThemePref = (ListPreference) findPreference(Preferences.KEY_ON_THEME_SELECT_ACTION);
        ArrayList<String> entryValues = new ArrayList<String>();
        ArrayList<String> entries = new ArrayList<String>();

        for (ThemeManager.Theme theme : ThemeManager.Theme.values()) {
            entryValues.add(theme.name());
            entries.add(getString(theme.mLabelId));
        }

        onSelectThemePref.setEntryValues(entryValues.toArray(new String[entryValues.size()]));
        onSelectThemePref.setEntries(entries.toArray(new String[entries.size()]));
        onSelectThemePref.setDefaultValue(ThemeManager.getDefaultTheme().name());
        if (onSelectThemePref.getValue() == null) {
            onSelectThemePref.setValue(ThemeManager.getDefaultTheme().name());
        } else {
            try {
                ThemeManager.Theme t = ThemeManager.Theme.valueOf(onSelectThemePref.getValue());
            } catch (Exception e) {
                onSelectThemePref.setValue(ThemeManager.getDefaultTheme().name());
            }
        }
        onSelectThemePref.setOnPreferenceChangeListener(this);
        updateSelectThemeSummary(onSelectThemePref.getValue());
    }

    @Override
    public void onResume() {
        super.onResume();
        mThemeManager.onResume(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    private void updateAddressSummary() {
        Preferences preferences = new Preferences(this);
        String serverName = preferences.getServerName();
        if (serverName != null && serverName.length() > 0) {
            addressPref.setSummary(serverName);
        } else {
            addressPref.setSummary(R.string.settings_serveraddr_summary);
        }
    }

    private void updateFadeInSecondsSummary(int fadeInSeconds) {
        if (fadeInSeconds == 0) {
            fadeInPref.setSummary(R.string.disabled);
        } else {
            fadeInPref.setSummary(fadeInSeconds + " " + getResources()
                    .getQuantityString(R.plurals.seconds, fadeInSeconds));
        }
    }

    private void updateSelectAlbumSummary(String value) {
        CharSequence[] entries = onSelectAlbumPref.getEntries();
        int index = onSelectAlbumPref.findIndexOfValue(value);

        onSelectAlbumPref.setSummary(entries[index]);
    }

    private void updateSelectSongSummary(String value) {
        CharSequence[] entries = onSelectSongPref.getEntries();
        int index = onSelectSongPref.findIndexOfValue(value);

        onSelectSongPref.setSummary(entries[index]);
    }

    private void updateSelectThemeSummary(String value) {
        CharSequence[] entries = onSelectThemePref.getEntries();
        int index = onSelectThemePref.findIndexOfValue(value);

        onSelectThemePref.setSummary(entries[index]);
    }

    /**
     * A preference has been changed by the user, but has not yet been persisted.
     *
     * @param preference
     * @param newValue
     *
     * @return
     */
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        final String key = preference.getKey();
        Log.v(TAG, "preference change for: " + key);

        if (Preferences.KEY_FADE_IN_SECS.equals(key)) {
            updateFadeInSecondsSummary(Util.parseDecimalIntOrZero(newValue.toString()));
            return true;
        }

        if (Preferences.KEY_ON_SELECT_ALBUM_ACTION.equals(key)) {
            updateSelectAlbumSummary(newValue.toString());
            return true;
        }

        if (Preferences.KEY_ON_SELECT_SONG_ACTION.equals(key)) {
            updateSelectSongSummary(newValue.toString());
            return true;
        }

        if (Preferences.KEY_ON_THEME_SELECT_ACTION.equals(key)) {
            updateSelectThemeSummary(newValue.toString());
            return true;
        }

        // If the user has enabled Scrobbling but we don't think it will work
        // pop up a dialog with links to Google Play for apps to install.
        if (Preferences.KEY_SCROBBLE_ENABLED.equals(key)) {
            if (newValue.equals(true) && !Scrobble.canScrobble()) {
                showDialog(DIALOG_SCROBBLE_APPS);

                // User hit back, or similar (or maybe went to install an
                // app). Check again to see if scrobbling will work.
                if (!Scrobble.canScrobble()) {
                    return false;
                }
            }
            return true;
        }

        return false;
    }

    /**
     * A preference has been changed by the user and is going to be persisted.
     *
     * @param sharedPreferences
     * @param key
     */
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Log.v(TAG, "Preference changed: " + key);

        if (key.startsWith(Preferences.KEY_SERVER_ADDRESS)) {
            updateAddressSummary();
        }

        if (service != null) {
            service.preferenceChanged(key);
        } else {
            Log.v(TAG, "service is null!");
        }
    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;

        switch (id) {
            case DIALOG_SCROBBLE_APPS:
                final CharSequence[] apps = {
                        "Last.fm", "ScrobbleDroid", "SLS"
                };
                final CharSequence[] urls = {
                        "fm.last.android", "net.jjc1138.android.scrobbler",
                        "com.adam.aslfms"
                };

                final int[] icons = {
                        R.drawable.ic_launcher_lastfm,
                        R.drawable.ic_launcher_scrobbledroid, R.drawable.ic_launcher_sls
                };

                dialog = new Dialog(this);
                dialog.setContentView(R.layout.scrobbler_choice_dialog);
                dialog.setTitle("Scrobbling applications");

                ListView appList = (ListView) dialog.findViewById(R.id.scrobble_apps);
                appList.setAdapter(new IconRowAdapter(this, apps, icons));

                final Context context = dialog.getContext();
                appList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse("market://details?id=" + urls[position]));
                        try {
                            startActivity(intent);
                        } catch (ActivityNotFoundException e) {
                            Toast.makeText(context, R.string.settings_market_not_found,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        }

        return dialog;
    }

    public static void show(Context context) {
        final Intent intent = new Intent(context, SettingsActivity.class);
        context.startActivity(intent);
    }
}


text:
#ifndef FontConfigControl_DEFINED
#define FontConfigControl_DEFINED
#pragma once

// Sets the Skia FontHost to use the direct (non-IPC, requires filesystem
// access) FontConfig implementation. Any previously-set FontConfigInterface
// will be freed.
void SkiaFontConfigUseDirectImplementation();

// Sets the Skia FontHost to use the given implementation of FontConfig. This
// is normally used to configure the IPC-based implementation to get out of
// the sandbox.
//
// Ownership of the given pointer is transferred, and any previously-set
// FontConfigInterface will be freed.
void SkiaFontConfigSetImplementation(FontConfigInterface* font_config);

#endif  // FontConfigControl_DEFINED

redpajama_set_name: RedPajamaGithub


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

namespace DotVVM.Framework.Binding.HelperNamespace
{
    internal static class NetFrameworkExtensions
    {
        /// <summary>
        /// This is an extension method that allows using unavailable string.Split(..) overload in .NET Framework
        /// </summary>
        public static string[] Split(this string text, string delimiter, StringSplitOptions options = StringSplitOptions.None)
        {
            return text.Split(new[] { delimiter }, options);
        }

        /// <summary>
        /// This is an extension method that allows using unavailable string.Split(..) overload in .NET Framework
        /// </summary>
        public static string[] Split(this string text, char delimiter, StringSplitOptions options = StringSplitOptions.None)
        {
            return text.Split(new[] { delimiter }, options);
        }

        /// <summary>
        /// This is an extension method that allows using unavailable string.Contains(..) overload in .NET Framework
        /// </summary>
        public static bool Contains(this string haystack, string needle, StringComparison options)
        {
            return haystack.IndexOf(needle, options) != -1;
        }

        /// <summary>
        /// This is an extension method that allows using unavailable string.Trim(..) overload in .NET Framework
        /// </summary>
        public static string Trim(this string text, char character)
        {
            return text.Trim(character);
        }

        /// <summary>
        /// This is an extension method that allows using unavailable string.TrimStart(..) overload in .NET Framework
        /// </summary>
        public static string TrimStart(this string text)
        {
            return string.Concat(text.SkipWhile(c => char.IsWhiteSpace(c)));
        }

        /// <summary>
        /// This is an extension method that allows using unavailable string.TrimEnd(..) overload in .NET Framework
        /// </summary>
        public static string TrimEnd(this string text)
        {
            return string.Concat(text.Reverse().SkipWhile(c => char.IsWhiteSpace(c)).Reverse());
        }
    }
}


text:
/**
* @author Vera Y. Petrashkova
* @version $Revision$
*/

package org.apache.harmony.security.tests.javax.security.cert.serialization;

import javax.security.cert.CertificateEncodingException;

import org.apache.harmony.testframework.serialization.SerializationTest;

/**
 * Test for CertificateEncodingException serialization
 *
 */

public class CertificateEncodingExceptionTest extends SerializationTest {

    public static String[] msgs = {
            "New message",
            "Long message for Exception. Long message for Exception. Long message for Exception." };

    protected Object[] getData() {
        return new Object[] { new CertificateEncodingException(),
                new CertificateEncodingException(null),
                new CertificateEncodingException(msgs[0]),
                new CertificateEncodingException(msgs[1]) };
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(CertificateEncodingExceptionTest.class);
    }
}


text:
'use strict';

var mysql = require('mysql')
  , Q     = require('q')
  , params = require('../../params')
  ;

/**
 * There isn't actually an exported API, as all the action is in the setup
 * itself.
 */
module.exports = function setup(options, imports, register) {
  var logger    = options.logger
    , username  = options.db.user
    , dbname    = options.db.name
    , tablename = options.db.table
    ;

  function run(client, commands) {
    return commands.reduce(
      function (last, next) { return last.then(next); },
      Q.resolve(client)
    );
  }

  function query(client, sql, successMessage) {
    return Q.ninvoke(client, 'query', sql).then(function cb_then() {
      logger.debug(successMessage);

      return client;
    });
  }

  function end(client) {
    return Q.ninvoke(client, 'end').then(function cb_then() {
      logger.debug("Connection as %s destroyed.", client.user);
    });
  }

  function createUser(client) {
    return query(
      client,
      "CREATE USER '" + username + "'",
      "User '" + username + "' created successfully."
    );
  }

  function grantPermissions(client) {
    return query(
      client,
      "GRANT ALL ON " + dbname + ".* TO '" + username + "'",
      "Access granted to user '" + username + "'."
    );
  }

  function createDB(client) {
    return query(
      client,
      "CREATE DATABASE IF NOT EXISTS " + dbname,
      "Database '" + dbname + "' created."
    );
  }

  function connectAsTestUser() {
    logger.debug("Reconnecting as %s.", username);

    return Q.resolve(mysql.createClient({
      user     : username,
      database : dbname,
      host     : params.mysql_host,
      port     : params.mysql_port
    }));
  }

  function createTestTable(client) {
    return query(
      client,
      "CREATE TABLE IF NOT EXISTS " + tablename +
        "(" +
        "  id         INTEGER(10) PRIMARY KEY AUTO_INCREMENT," +
        "  test_value VARCHAR(255)" +
        ")",
      "Table '" + tablename + "' created."
    );
  }

  function truncateTable(client) {
    return query(
      client,
      'TRUNCATE TABLE ' + tablename,
      "Table '" + tablename + "' truncated.'"
    );
  }

  function createSeedData(client) {
    return query(
      client,
      "INSERT INTO " + tablename + " (test_value) VALUE (\"hamburgefontstiv\")",
      "Test data seeded into table '" + tablename + "'."
    );
  }

  function ensureTable(client) {
    var sql = "SELECT table_name " +
              "  FROM information_schema.tables " +
              " WHERE table_schema = ? " +
              "   AND table_name = ?";

    /* A weird side effect of Q.ninvoke: more than just one non-error
     * parameter expected on the callback, get back an array of all of
     * them. Q.get(0) will grab the first parameter.
     */
    return Q.ninvoke(client, 'query', sql, [dbname, tablename])
      .get(0)
      .get('length')
      .then(function cb_then(length) {
        logger.debug("%s test table(s) found.", length);
        if (length > 0) return client;

        throw new Error("Test table missing. Test database not initialized.");
      });
  }

  function ensureData(client) {
    var sql = "SELECT COUNT(*) AS counted " +
              "  FROM " + dbname + "." + tablename;

    return Q.ninvoke(client, 'query', sql)
      .get(0)
      .then(function cb_then(result) {
        if (result.length !== 1) throw new Error("Test table query failed.");

        var count = result[0].counted;
        logger.debug("%s test data row(s).", count);
        if (count > 0) return client;

        throw new Error("No test data seeded. Only partially initialized.");
      });
  }

  function succeeded() {
    logger.info("Test database initialized.");
    return register(null, {mysqlBootstrap : {}});
  }

  function failed(error) {
    return register(error);
  }

  var client = mysql.createClient({
    user     : 'root',
    database : 'mysql',
    host     : params.mysql_host,
    port     : params.mysql_port
  });

  // actually run the initializer
  var isInitialized = run(client, [ensureTable, end, connectAsTestUser, truncateTable, createSeedData, ensureData, end]);
  isInitialized.then(
    succeeded,
    function notYetBootstrapped(error) {
      logger.debug(error.message);

      // reuse the first connection because why not
      var bootstrap = run(client,
        [
          createUser, grantPermissions, createDB, end,
          connectAsTestUser,
          createTestTable, createSeedData,
          ensureTable, ensureData, end
        ]
      );
      bootstrap.then(succeeded, failed).done();
    }
  );
};


text:
sub usage {
  print <<EOF;
Usage: $0 [--nohup] [--parallel]
--nohup causes the output of all compiles to go into nohup.out
--parallel causes all compiles to be run in parallel

Usage: $0 --clean
--clean erases the build directories and recreates them from scratch

Combinations of nohup and parallel:
no args: serial compile, output goes to stdout
--nohup:  serial compile, output goes into individual nohup.out files
--nohup --parallel: parallel compile, output goes to individual nohup.out files
--parallel: parallel compile, spawn an xterm for each configuration
EOF
}

$DEBUG=0;

$TEST_STANDARD = 1;
$TEST_GUIS = 1;
$TEST_CPU = 1;
$TEST_SMP = 1;
$TEST_IODEV = 1;
$TEST_PCI = 1;
$TEST_X86_64 = 1;
$TEST_SSE = 1;
$TEST_PLUGINS = 1;
$TEST_DEVICES = 1;

$pwd = `pwd`;
chop $pwd;

# create all the configurations that we should test.  The first argument
# is the configuration name, which must be a valid directory name.  To be
# safe, don't put spaces, slashes, ".", or ".." in here.
if ($TEST_STANDARD) {
  add_configuration ('normal',
    '');
  add_configuration ('dbg',
    '--enable-debugger');
}

if ($TEST_PLUGINS) {
add_configuration ('plug',
  '--enable-plugins');
add_configuration ('plug-d',
  '--enable-plugins --enable-debugger');
add_configuration ('plug-allgui',
  '--enable-plugins --with-all-libs');
add_configuration ('plug-allgui-d',
  '--enable-plugins --with-all-libs --enable-debugger');
add_configuration ('plug-smp',
  '--enable-plugins --enable-smp');
add_configuration ('plug-smp-d',
  '--enable-plugins --enable-smp --enable-debugger');
add_configuration ('plug-x86-64',
  '--enable-plugins --enable-x86-64');
add_configuration ('plug-wx',
  '--enable-plugins --with-wx');
}

if ($TEST_DEVICES) {
add_configuration ('alldev',
  '--enable-ne2000 --enable-pci --enable-port-e9-hack --enable-cdrom --enable-iodebug');
add_configuration ('ne2000',
  '--enable-ne2000');
add_configuration ('pci',
  '--enable-pci');
add_configuration ('port-e9-hack',
  '--enable-port-e9-hack');
add_configuration ('cdrom',
  '--enable-cdrom');
add_configuration ('gdbstub',
  '--enable-gdbstub');
add_configuration ('iodebug',
  '--enable-iodebug');
}

if ($TEST_GUIS) {
  # test with various gui options
  add_configuration ('wx',
    '--with-wx');
  add_configuration ('wx-d',
    '--with-wx --enable-debugger');
  add_configuration ('sdl',
    '--with-sdl');
  add_configuration ('sdl-d',
    '--with-sdl --enable-debugger');
  add_configuration ('term',
    '--with-term');
  add_configuration ('term-d',
    '--with-term --enable-debugger');
  add_configuration ('rfb',
    '--with-rfb');
  add_configuration ('rfb-d',
    '--with-rfb --enable-debugger');
  add_configuration ('nogui',
    '--with-nogui');
  add_configuration ('nogui-d',
    '--with-nogui --enable-debugger');
}

if ($TEST_CPU) {
# test with various cpu options
add_configuration ('i386',
  '--enable-cpu-level=3 --disable-mmx');
add_configuration ('i486',
  '--enable-cpu-level=4 --disable-mmx');
add_configuration ('i586',
  '--enable-cpu-level=5');
add_configuration ('i686',
  '--enable-cpu-level=6');
add_configuration ('large-pages',
  '--enable-large-pages');
add_configuration ('pae',
  '--enable-pae');
add_configuration ('g2h-tlb',
  '--enable-guest2host-tlb');
add_configuration ('repeat',
  '--enable-repeat-speedups');
add_configuration ('globalpg',
  '--enable-global-pages');
add_configuration ('icache',
  '--enable-icache');
add_configuration ('cpuall',
  '--enable-large-pages --enable-pae --enable-global-pages --enable-all-optimizations');
}

if ($TEST_SMP) {
# smp
add_configuration ('smp',
  '--enable-smp');
add_configuration ('smp-d',
  '--enable-smp --enable-debugger');
add_configuration ('smp-wx',
  '--enable-smp --with-wx');
add_configuration ('smp-wx-d',
  '--enable-smp --with-wx --enable-debugger');
}

if ($TEST_X86_64) {
# test x86-64
add_configuration ('64bit',
  '--enable-x86-64');
add_configuration ('64bit-d',
  '--enable-x86-64 --enable-debugger');
add_configuration ('64bit-wx',
  '--enable-x86-64 --with-wx');
add_configuration ('64bit-wx-d',
  '--enable-x86-64 --with-wx --enable-debugger');
}

if ($TEST_SSE) {
# test SSE configurations
add_configuration ('sse1',
  '--enable-sse=1');
add_configuration ('sse2',
  '--enable-sse=2');
add_configuration ('sse2-dbg',
  '--enable-sse=2 --enable-debugger');
add_configuration ('sse2-x86-64-wx-d',
  '--enable-sse=2 --enable-x86-64 --with-wx --enable-debugger');
}

my $nohup = 0;
my $parallel = 0;
my $clean = 0;
foreach my $arg (@ARGV) {
  if ($arg eq '--clean') {
    $clean = 1;
  } elsif ($arg eq '--nohup') {
    $nohup = 1;
  } elsif ($arg eq '--parallel') {
    $parallel = 1;
  } else {
    usage(); exit 1;
  }
}

# this script may be run from various directories, and this affects
# the path to the configure command.  Try to figure out where the configure
# command is found, and set up the build.sh scripts accordingly.  If it
# can't be found, spit out an error now instead of later.
my @configurepath_tries = ("configure", "../configure", "../../configure");
my $configurepath;
foreach my $trypath (@configurepath_tries) {
  if (-x $trypath) {
    print "Found configure at $configurepath.\n" if $DEBUG;
    $configurepath = $trypath;
  }
}
if (!defined $configurepath) {
  print <<EOF;
ERROR I could not locate the configure script.  This script is intended
to be run from the bochs main directory or a subdirectory of it.  Examples:
 1) cd $BOCHS; ./build/batch-build.perl
 2) cd $BOCHS/build; ./batch-build.perl

Here are the places that I tried to find the configure script:
EOF
  foreach (@configurepath_tries) {
    print "  $_\n";
  }
  exit 1;
}

$x = 50; $y = 50;
$xinc = 30;
$yinc = 30;

for (my $i=0; $i <= $#config_names; $i++) {
  my $name = "build-$config_names[$i]";
  my $options = $config_opts[$i];
  die if (!defined $name || !defined $options);
  print "Compiling '$name' with opts '$options'\n" if $DEBUG;
  if ($clean) {
    my $rmcmd = "rm -rf $name";
    print "Removing directory $name\n";
    system $rmcmd;
    next;
  }
  if (! -d $name) { mkdir $name, 0755; }
  $maybe_nohup = $nohup? "nohup" : "";
  open (BUILD, ">$name/build.sh");
  print BUILD <<BUILD_EOF;
#!/bin/bash
echo Running the configure script
export CFLAGS='-g -O2 -Wall'
export CXXFLAGS='-g -O2 -Wall'
$maybe_nohup ../$configurepath $options
if test $? != 0; then
  echo Configure failed.
  exit 1
fi
echo Running make
$maybe_nohup make
if test $? != 0; then
  echo Make failed.
  exit 1
fi
BUILD_EOF
  close BUILD;
  chmod 0755, "$name/build.sh";
  $gotodir = "cd $name";
  $startcmd = "nice $maybe_nohup ./build.sh";
  $header = <<HEADER_EOF;
====================================================================
Configuration name: $name
Directory: $pwd/$name
Config Options: $options
====================================================================
HEADER_EOF
  print $header;

  if ($parallel && !$nohup) {
    # special case for parallel without nohup.  If you're not careful,
    # all output from all compiles will go into the window at once, which
    # is impossible to read.  Also very hard to kill them until they have
    # run their course.  Instead, start each compile in a different xterm!
    # What's even more useful is that after the compile stops it goes into
    # a bash shell so that you can fix things, run the make again, etc.
    #
    # To do this, put the start command in a little shell script called
    # xterm-init.sh.  Start the xterm with "-e xterm-init.sh" so that it
    # runs the script as it starts.

    open (XTI, ">$name/xterm-init.sh");
    print XTI <<XTI_EOF;
#!/bin/bash
cat <<EOF
$header
EOF
$startcmd
bash
exit 0
XTI_EOF
    close XTI;
    chmod 0755, "$name/xterm-init.sh";
    $geometry = "-geom +$x+$y";
    $x+=$xinc;
    $y+=$yinc;
    $startcmd = "xterm -title $name -name $name $geometry -e ./xterm-init.sh";
  }

  $cmd = "$gotodir && $startcmd";
  $cmd .= "&" if $parallel;
  print "Executing '$cmd'\n" if $DEBUG;
  system $cmd;
}

print "\n"x2;
print "batch-build script is done.\n";
exit 0;

sub add_configuration {
  my ($name, $opts) = @_;
  push @config_names, $name;
  push @config_opts, $opts;
}


text:
	function PlayerCar() {
		this.context = undefined,
		this.height= 120,
		this.line= 100;
		this.score = 0;
	}

	PlayerCar.prototype._buildCar = function (line) {
		var squareSize = 7,
			left = (squareSize * 1),
			center = (squareSize * 2),
			right = (squareSize * 3);

		//car head
		this.context.rect(center + line, this.height, squareSize, squareSize);
		this.context.rect(left + line, this.height + squareSize, squareSize, squareSize);
		this.context.rect(center + line, this.height + squareSize, squareSize, squareSize);
		this.context.rect(right + line, this.height + squareSize, squareSize, squareSize);
		//car body
		this.context.rect(center + line, this.height + (squareSize * 2), squareSize, squareSize);
		//car wings
		this.context.rect(left + line, this.height + (squareSize * 3), squareSize, squareSize);
		this.context.rect(right + line, this.height + (squareSize * 3), squareSize, squareSize);

		this.context.fillStyle = '#888888';
		this.context.fill();
		this.context.strokeStyle = 'black';
		this.context.lineWidth = 2;
		this.context.stroke();
	};

	PlayerCar.prototype.init = function (canvas) {
		this.context = canvas.getContext("2d");
		this._buildCar(this.line);
		return this;
	};

	function ReverseCar() {
		this.context = undefined,
		this.height = 0,
		this.line= 100;
		this.speed = 0.1;
		this.lines = [0, 30, 60];
	};

	ReverseCar.prototype.init = function (canvas) {
		this.context = canvas.getContext("2d");
		this.line = this.lines[Math.floor(Math.random() * (2 - 0 + 1)) ];
		return this;
	};

	ReverseCar.prototype._buildCar= function () {
		var squareSize = 7,
			left = (squareSize * 1),
			center = (squareSize * 2),
			right = (squareSize * 3);

		this.context.rect(center + this.line, this.height , squareSize, squareSize);
		this.context.rect(left + this.line, this.height + squareSize, squareSize, squareSize);
		this.context.rect(center + this.line, this.height + squareSize, squareSize, squareSize);
		this.context.rect(right + this.line, this.height + squareSize, squareSize, squareSize);
		this.context.rect(center + this.line, this.height + (squareSize * 2), squareSize, squareSize);
		this.context.rect(left + this.line, this.height + (squareSize * 3), squareSize, squareSize);
		this.context.rect(right + this.line, this.height + (squareSize * 3), squareSize, squareSize);

		this.context.fillStyle = '#888888';
		this.context.fill();
		this.context.strokeStyle = 'black';
		this.context.lineWidth = 2;
		this.context.stroke();
		if (miniRacer.running){
			if(this.height > 100){
				if (miniRacer.line == this.line) {
					miniRacer.running = false;
					console.log("Your escore in MiniRacer is " + miniRacer.playerCar.score + ".");
					alert("Your escore in MiniRacer is " + miniRacer.playerCar.score + ".");
				}
			}

			if (this.height > 145){
				this.height = -10;
				this.line = this.lines[Math.floor(Math.random() * (this.lines.length + 1))];
				miniRacer.playerCar.score += 1;
			} else {
				this.height += this.speed;
				this.speed += .001;
			}
		}
	};

	ReverseCar.prototype._resetCar = function (){
		this.height = 0;
		this.speed = Math.random();
		this.line = this.lines[Math.floor(Math.random() * (2 - 0 + 1)) ];
	};

var miniRacer = ({
		context: null,
		canvas: null,
		LEFTLINE: 0,
		CENTERLINE: 30,
		RIGHTLINE: 60,
		quantityEnemyCars: 0,
		heightReverseCars: 0,
		playerCar: null,
		reverseCars: [],
		running: true,

	changeLine: function (event) {
		switch(event.keyCode) {
			case 97: // A
				if (miniRacer.running){
					switch(this.line) {
						case this.LEFTLINE:
							break;
						case this.CENTERLINE:
							this.line = this.LEFTLINE;
							break;
						case this.RIGHTLINE:
							this.line = this.CENTERLINE;
							break;
					}
					this._clearCanvas();
					this.playerCar._buildCar(this.line);
					for (i = 0; i < miniRacer.reverseCars.length; i++) {
						this.reverseCars[i]._buildCar();
					}
				}
				break;
			case 100: // D
				if (miniRacer.running){
					switch(this.line) {
						case this.LEFTLINE:
							this.line = this.CENTERLINE;
							break;
						case this.CENTERLINE:
							this.line = this.RIGHTLINE;
							break;
						case this.RIGHTLINE:
							break;
					}
					this._clearCanvas();
					this.playerCar._buildCar(this.line);
					for (i = 0; i < miniRacer.reverseCars.length; i++) {
						this.reverseCars[i]._buildCar();
					}
				}
				break;

				case 114: // R
					this._clearCanvas();
					this.playerCar._buildCar(this.line);
					for (i = 0; i < miniRacer.reverseCars.length; i++) {
						this.reverseCars[i]._resetCar();
					}
					miniRacer.playerCar.score = 0;
					miniRacer.running = true;
					break;
			default: return;
		}

	},

	_clearCanvas: function() {
		this.context.beginPath();
		this.context.clearRect(0 ,0, this.canvas.width, this.canvas.height );
	},

	_clearCanvasTop: function(width, height) {
		this.context.beginPath();
		this.context.clearRect(0 ,0, width, height );
	},

	_startMoviment: function() {
		setInterval(function() {
			miniRacer._clearCanvas();
			miniRacer.playerCar._buildCar(miniRacer.line);
			for (i = 0; i < miniRacer.reverseCars.length; i++) {
					miniRacer.reverseCars[i]._buildCar();
			}
		}, 15);

		setInterval(function () {
			if (miniRacer.quantityEnemyCars < 2){
				miniRacer.reverseCars.push(new ReverseCar().init(miniRacer.canvas));
				miniRacer.quantityEnemyCars += 1;
			}
			if (miniRacer.quantityEnemyCars == 2){
				clearInterval(this);
			}
		}, 3000);

	},

	init: function () {
		this.canvas = document.getElementById("miniRacerCanvas");
		this.context = this.canvas.getContext("2d");
		this.line = this.CENTERLINE,
		this.playerCar = new PlayerCar().init(this.canvas);
		this._startMoviment();
		return this;
	}

}).init();

var canvas = document.getElementById("miniRacerCanvas");
canvas.focus();

canvas.addEventListener('keypress', function(e){
	miniRacer.changeLine(e);
});


text:
BuildingManager::BuildingManager(CCBot & bot)
    : m_bot(bot)
    , m_buildingPlacer(bot)
    , m_debugMode(false)
    , m_reservedMinerals(0)
    , m_reservedGas(0)
{

}

void BuildingManager::onStart()
{
    m_buildingPlacer.onStart();
}

// gets called every frame from GameCommander
void BuildingManager::onFrame()
{
    for (auto & unit : m_bot.UnitInfo().getUnits(Players::Self))
    {
        // filter out units which aren't buildings under construction
        if (m_bot.Data(unit.unit_type).isBuilding)
        {
            std::stringstream ss;
            ss << unit.tag;
            m_bot.Map().drawText(unit.pos, ss.str());
        }
    }

    validateWorkersAndBuildings();          // check to see if assigned workers have died en route or while constructing
    assignWorkersToUnassignedBuildings();   // assign workers to the unassigned buildings and label them 'planned'
    constructAssignedBuildings();           // for each planned building, if the worker isn't constructing, send the command
    checkForStartedConstruction();          // check to see if any buildings have started construction and update data structures
    checkForDeadTerranBuilders();           // if we are terran and a building is under construction without a worker, assign a new one
    checkForCompletedBuildings();           // check to see if any buildings have completed and update data structures

    drawBuildingInformation();
}

bool BuildingManager::isBeingBuilt(sc2::UnitTypeID type)
{
    for (auto & b : m_buildings)
    {
        if (b.type == type)
        {
            return true;
        }
    }

    return false;
}

// STEP 1: DO BOOK KEEPING ON WORKERS WHICH MAY HAVE DIED
void BuildingManager::validateWorkersAndBuildings()
{
    // TODO: if a terran worker dies while constructing and its building
    //       is under construction, place unit back into buildingsNeedingBuilders

    std::vector<Building> toRemove;

    // find any buildings which have become obsolete
    for (auto & b : m_buildings)
    {
        if (b.status != BuildingStatus::UnderConstruction)
        {
            continue;
        }

        auto buildingUnit = m_bot.GetUnit(b.buildingUnitTag);

        // TODO: || !b.buildingUnit->getType().isBuilding()
        if (!buildingUnit || (buildingUnit->health <= 0))
        {
            toRemove.push_back(b);
        }
    }

    removeBuildings(toRemove);
}

// STEP 2: ASSIGN WORKERS TO BUILDINGS WITHOUT THEM
void BuildingManager::assignWorkersToUnassignedBuildings()
{
    // for each building that doesn't have a builder, assign one
    for (Building & b : m_buildings)
    {
        if (b.status != BuildingStatus::Unassigned)
        {
            continue;
        }

        BOT_ASSERT(b.builderUnitTag == 0, "Error: Tried to assign a builder to a building that already had one ");

        if (m_debugMode) { printf("Assigning Worker To: %s", sc2::UnitTypeToName(b.type)); }

        // grab a worker unit from WorkerManager which is closest to this final position
        sc2::Point2D testLocation = getBuildingLocation(b);
        if (!m_bot.Map().isValid(testLocation))
        {
            continue;
        }

        b.finalPosition = testLocation;

        // grab the worker unit from WorkerManager which is closest to this final position
        UnitTag builderUnitTag = m_bot.Workers().getBuilder(b);
        b.builderUnitTag = builderUnitTag;
        if (!b.builderUnitTag)
        {
            continue;
        }

        // reserve this building's space
        m_buildingPlacer.reserveTiles((int)b.finalPosition.x, (int)b.finalPosition.y, Util::GetUnitTypeWidth(b.type, m_bot), Util::GetUnitTypeHeight(b.type, m_bot));

        b.status = BuildingStatus::Assigned;
    }
}

// STEP 3: ISSUE CONSTRUCTION ORDERS TO ASSIGN BUILDINGS AS NEEDED
void BuildingManager::constructAssignedBuildings()
{
    for (auto & b : m_buildings)
    {
        if (b.status != BuildingStatus::Assigned)
        {
            continue;
        }

        // TODO: not sure if this is the correct way to tell if the building is constructing
        sc2::AbilityID buildAbility = m_bot.Data(b.type).buildAbility;
        const sc2::Unit * builderUnit = m_bot.GetUnit(b.builderUnitTag);

        bool isConstructing = false;

        // if we're zerg and the builder unit is null, we assume it morphed into the building
        if (m_bot.GetPlayerRace(Players::Self) == sc2::Race::Zerg)
        {
            if (!builderUnit)
            {
                isConstructing = true;
            }
        }
        else
        {
            BOT_ASSERT(builderUnit, "null builder unit");
            isConstructing = (builderUnit->orders.size() > 0) && (builderUnit->orders[0].ability_id == buildAbility);
        }

        // if that worker is not currently constructing
        if (!isConstructing)
        {
            // if we haven't explored the build position, go there
            if (!isBuildingPositionExplored(b))
            {
                Micro::SmartMove(*builderUnit, b.finalPosition, m_bot);
            }
            // if this is not the first time we've sent this guy to build this
            // it must be the case that something was in the way of building
            else if (b.buildCommandGiven)
            {
                // TODO: in here is where we would check to see if the builder died on the way
                //       or if things are taking too long, or the build location is no longer valid
            }
            else
            {
                // if it's a refinery, the build command has to be on the geyser unit tag
                if (Util::IsRefineryType(b.type))
                {
                    // first we find the geyser at the desired location
                    UnitTag geyserTag = 0;
                    for (auto & unit : m_bot.Observation()->GetUnits())
                    {
                        if (Util::IsGeyser(unit) && Util::Dist(b.finalPosition, unit.pos) < 3)
                        {
                            geyserTag = unit.tag;
                            break;
                        }
                    }

                    if (geyserTag)
                    {
                        Micro::SmartBuildTag(b.builderUnitTag, b.type, geyserTag, m_bot);
                    }
                    else
                    {
                        std::cout << "WARNING: NO VALID GEYSER UNIT FOUND TO BUILD ON, SKIPPING REFINERY\n";
                    }
                }
                // if it's not a refinery, we build right on the position
                else
                {
                    Micro::SmartBuild(b.builderUnitTag, b.type, b.finalPosition, m_bot);
                }

                // set the flag to true
                b.buildCommandGiven = true;
            }
        }
    }
}

// STEP 4: UPDATE DATA STRUCTURES FOR BUILDINGS STARTING CONSTRUCTION
void BuildingManager::checkForStartedConstruction()
{
    // for each building unit which is being constructed
    for (auto & buildingStarted : m_bot.UnitInfo().getUnits(Players::Self))
    {
        // filter out units which aren't buildings under construction
        if (!m_bot.Data(buildingStarted.unit_type).isBuilding || buildingStarted.build_progress == 0.0f || buildingStarted.build_progress == 1.0f)
        {
            continue;
        }

        // check all our building status objects to see if we have a match and if we do, update it

        for (auto & b : m_buildings)
        {
            if (b.status != BuildingStatus::Assigned)
            {
                continue;
            }

            // check if the positions match
            float dx = b.finalPosition.x - buildingStarted.pos.x;
            float dy = b.finalPosition.y - buildingStarted.pos.y;

            if (dx*dx + dy*dy < 1)
            {
                if (b.buildingUnitTag != 0)
                {
                    std::cout << "Building mis-match somehow\n";
                }

                // the resources should now be spent, so unreserve them
                m_reservedMinerals -= Util::GetUnitTypeMineralPrice(buildingStarted.unit_type, m_bot);
                m_reservedGas      -= Util::GetUnitTypeGasPrice(buildingStarted.unit_type, m_bot);

                // flag it as started and set the buildingUnit
                b.underConstruction = true;
                b.buildingUnitTag = buildingStarted.tag;

                // if we are zerg, the buildingUnit now becomes nullptr since it's destroyed
                if (m_bot.GetPlayerRace(Players::Self) == sc2::Race::Zerg)
                {
                    b.builderUnitTag = 0;
                }
                else if (m_bot.GetPlayerRace(Players::Self) == sc2::Race::Protoss)
                {
                    m_bot.Workers().finishedWithWorker(b.builderUnitTag);
                    b.builderUnitTag = 0;
                }

                // put it in the under construction vector
                b.status = BuildingStatus::UnderConstruction;

                // free this space
                m_buildingPlacer.freeTiles((int)b.finalPosition.x, (int)b.finalPosition.y, Util::GetUnitTypeWidth(b.type, m_bot), Util::GetUnitTypeHeight(b.type, m_bot));

                // only one building will match
                break;
            }
        }
    }
}

// STEP 5: IF WE ARE TERRAN, THIS MATTERS, SO: LOL
void BuildingManager::checkForDeadTerranBuilders() {}

// STEP 6: CHECK FOR COMPLETED BUILDINGS
void BuildingManager::checkForCompletedBuildings()
{
    std::vector<Building> toRemove;

    // for each of our buildings under construction
    for (auto & b : m_buildings)
    {
        if (b.status != BuildingStatus::UnderConstruction)
        {
            continue;
        }

        // if the unit has completed
        if (m_bot.GetUnit(b.buildingUnitTag)->build_progress == 1.0f)
        {
            // if we are terran, give the worker back to worker manager
            if (m_bot.GetPlayerRace(Players::Self) == sc2::Race::Terran)
            {
                m_bot.Workers().finishedWithWorker(b.builderUnitTag);
            }

            // remove this unit from the under construction vector
            toRemove.push_back(b);
        }
    }

    removeBuildings(toRemove);
}

// add a new building to be constructed
void BuildingManager::addBuildingTask(const sc2::UnitTypeID & type, const sc2::Point2D & desiredPosition)
{
    m_reservedMinerals  += Util::GetUnitTypeMineralPrice(type, m_bot);
    m_reservedGas	    += Util::GetUnitTypeGasPrice(type, m_bot);

    Building b(type, desiredPosition);
    b.status = BuildingStatus::Unassigned;

    m_buildings.push_back(b);
}

// TODO: may need to iterate over all tiles of the building footprint
bool BuildingManager::isBuildingPositionExplored(const Building & b) const
{
    return m_bot.Map().isExplored(b.finalPosition);
}

char BuildingManager::getBuildingWorkerCode(const Building & b) const
{
    return b.builderUnitTag == 0 ? 'X' : 'W';
}

int BuildingManager::getReservedMinerals()
{
    return m_reservedMinerals;
}

int BuildingManager::getReservedGas()
{
    return m_reservedGas;
}

void BuildingManager::drawBuildingInformation()
{
    m_buildingPlacer.drawReservedTiles();

    if (!m_bot.Config().DrawBuildingInfo)
    {
        return;
    }

    std::stringstream ss;
    ss << "Building Information " << m_buildings.size() << "\n\n\n";

    int yspace = 0;

    for (const auto & b : m_buildings)
    {
        std::stringstream dss;

        if (b.builderUnitTag)
        {
            dss << "\n\nBuilder: " << b.builderUnitTag << "\n";
        }

        if (b.buildingUnitTag)
        {
            dss << "Building: " << b.buildingUnitTag << "\n" << m_bot.GetUnit(b.buildingUnitTag)->build_progress;
            m_bot.Map().drawText(m_bot.GetUnit(b.buildingUnitTag)->pos, dss.str());
        }

        if (b.status == BuildingStatus::Unassigned)
        {
            ss << "Unassigned " << sc2::UnitTypeToName(b.type) << "    " << getBuildingWorkerCode(b) << "\n";
        }
        else if (b.status == BuildingStatus::Assigned)
        {
            ss << "Assigned " << sc2::UnitTypeToName(b.type) << "    " << b.builderUnitTag << " " << getBuildingWorkerCode(b) << " (" << b.finalPosition.x << "," << b.finalPosition.y << ")\n";

            float x1 = b.finalPosition.x;
            float y1 = b.finalPosition.y;
            float x2 = b.finalPosition.x + Util::GetUnitTypeWidth(b.type, m_bot);
            float y2 = b.finalPosition.y + Util::GetUnitTypeHeight(b.type, m_bot);

            m_bot.Map().drawSquare(x1, y1, x2, y2, sc2::Colors::Red);
            //m_bot.Map().drawLine(b.finalPosition, m_bot.GetUnit(b.builderUnitTag)->pos, sc2::Colors::Yellow);
        }
        else if (b.status == BuildingStatus::UnderConstruction)
        {
            ss << "Constructing " << sc2::UnitTypeToName(b.type) << "    " << b.builderUnitTag << " " << b.buildingUnitTag << " " << getBuildingWorkerCode(b) << "\n";
        }
    }

    m_bot.Map().drawTextScreen(sc2::Point2D(0.05f, 0.05f), ss.str());
}

std::vector<sc2::UnitTypeID> BuildingManager::buildingsQueued() const
{
    std::vector<sc2::UnitTypeID> buildingsQueued;

    for (const auto & b : m_buildings)
    {
        if (b.status == BuildingStatus::Unassigned || b.status == BuildingStatus::Assigned)
        {
            buildingsQueued.push_back(b.type);
        }
    }

    return buildingsQueued;
}

sc2::Point2D BuildingManager::getBuildingLocation(const Building & b)
{
    size_t numPylons = m_bot.UnitInfo().getUnitTypeCount(Players::Self, Util::GetSupplyProvider(m_bot.GetPlayerRace(Players::Self)), true);

    // TODO: if requires psi and we have no pylons return 0

    if (Util::IsRefineryType(b.type))
    {
        return m_buildingPlacer.getRefineryPosition();
    }

    if (Util::IsTownHallType(b.type))
    {
        // TODO: fix this so we can actually expand
        //return m_bot.Bases().getNextExpansion(Players::Self);
    }

    // get a position within our region
    // TODO: put back in special pylon / cannon spacing
    return m_buildingPlacer.getBuildLocationNear(b, m_bot.Config().BuildingSpacing);
}

void BuildingManager::removeBuildings(const std::vector<Building> & toRemove)
{
    for (auto & b : toRemove)
    {
        const auto & it = std::find(m_buildings.begin(), m_buildings.end(), b);

        if (it != m_buildings.end())
        {
            m_buildings.erase(it);
        }
    }
}


text:
/** Module dependencies
*/
var BANNER, CSON, OptionParser, SWITCHES, VERSION, basename, coffee, extname, fs, main, path;

require('colors');

fs = require('fs');

path = require('path');

coffee = require('coffee-script');

OptionParser = require('coffee-script/lib/coffee-script/optparse').OptionParser;

CSON = require('./CSON');

extname = path.extname, basename = path.basename;

VERSION = "0.1";

BANNER = 'Usage: cson [options] path/to/json/file';

SWITCHES = [['-o', '--output [FILE*]', 'output file'], ['-u', '--uglify', 'compact print'], ['-c', '--cson', 'convert JSON to CSON'], ['-s', '--stdout', 'print to stdout'], ['-v', '--version', 'show version'], ['-h', '--help', 'display this help message']];

/** Entry point
*/

main = function() {
  var cson, i, input, json, o, optParser, output, _len, _ref, _results;
  optParser = new OptionParser(SWITCHES, BANNER);
  o = optParser.parse(process.argv.slice(2));
  if (o.help) {
    console.log(optParser.help());
    return;
  }
  if (o.version) {
    console.log("CSON v" + VERSION + "\nCopyright(c) 2012 vol4ok <admin@vol4ok.net ");
    return;
  }
  if (o.arguments.length === 0) {
    console.log('Error: no input file!'.red);
    console.log(optParser.help());
    return;
  }
  _ref = o.arguments;
  _results = [];
  for (i = 0, _len = _ref.length; i < _len; i++) {
    input = _ref[i];
    cson = fs.readFileSync(input, 'utf-8');
    json = o.cson ? CSON.toCSON(cson) : CSON.toJSON(cson, o.uglify);
    if (o.stdout) console.log(json);
    output = o.output && o.output[i] ? o.output[i] : basename(input, extname(input)) + (o.cson ? '.cson' : '.json');
    _results.push(fs.writeFileSync(output, json, 'utf-8'));
  }
  return _results;
};

main();


text:
import {LineVector, FillVector, HatchVector} from "core/property_mixins"
import {Arrayable, Rect} from "core/types"
import {Anchor} from "core/enums"
import {Line, Fill, Hatch} from "core/visuals"
import {SpatialIndex} from "core/util/spatial"
import {Context2d} from "core/util/canvas"
import {Glyph, GlyphView, GlyphData} from "./glyph"
import {generic_area_legend} from "./utils"
import {PointGeometry, SpanGeometry, RectGeometry} from "core/geometry"
import * as hittest from "core/hittest"
import {Selection} from "../selections/selection"
import * as p from "core/properties"

export interface BoxData extends GlyphData {
  _right: Arrayable<number>
  _bottom: Arrayable<number>
  _left: Arrayable<number>
  _top: Arrayable<number>

  sright: Arrayable<number>
  sbottom: Arrayable<number>
  sleft: Arrayable<number>
  stop: Arrayable<number>
}

export interface BoxView extends BoxData {}

export abstract class BoxView extends GlyphView {
  model: Box
  visuals: Box.Visuals

  get_anchor_point(anchor: Anchor, i: number, _spt: [number, number]): {x: number, y: number} | null {
    const left = Math.min(this.sleft[i], this.sright[i])
    const right = Math.max(this.sright[i], this.sleft[i])
    const top = Math.min(this.stop[i], this.sbottom[i])     // screen coordinates !!!
    const bottom = Math.max(this.sbottom[i], this.stop[i])  //

    switch (anchor) {
      case "top_left":      return {x: left,             y: top             }
      case "top_center":    return {x: (left + right)/2, y: top             }
      case "top_right":     return {x: right,            y: top             }
      case "bottom_left":   return {x: left,             y: bottom          }
      case "bottom_center": return {x: (left + right)/2, y: bottom          }
      case "bottom_right":  return {x: right,            y: bottom          }
      case "center_left":   return {x: left,             y: (top + bottom)/2}
      case "center":        return {x: (left + right)/2, y: (top + bottom)/2}
      case "center_right":  return {x: right,            y: (top + bottom)/2}
      default:              return null
    }
  }

  protected abstract _lrtb(i: number): [number, number, number, number]

  protected _index_box(len: number): SpatialIndex {
    const points = []

    for (let i = 0; i < len; i++) {
      const [l, r, t, b] = this._lrtb(i)
      if (isNaN(l + r + t + b) || !isFinite(l + r + t + b))
        continue
      points.push({
        x0: Math.min(l, r),
        y0: Math.min(t, b),
        x1: Math.max(r, l),
        y1: Math.max(t, b),
        i,
      })
    }

    return new SpatialIndex(points)
  }

  protected _render(ctx: Context2d, indices: number[],
                    {sleft, sright, stop, sbottom}: BoxData): void {
    for (const i of indices) {
      if (isNaN(sleft[i] + stop[i] + sright[i] + sbottom[i]))
        continue

      ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i])

      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i)
        ctx.beginPath()
        ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i])
        ctx.fill()
      }

      this.visuals.hatch.doit2(ctx, i, () => {
        ctx.beginPath()
        ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i])
        ctx.fill()
      }, () => this.renderer.request_render())

      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i)
        ctx.beginPath()
        ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i])
        ctx.stroke()
      }

    }
  }

  // We need to clamp the endpoints inside the viewport, because various browser canvas
  // implementations have issues drawing rects with enpoints far outside the viewport
  protected _clamp_viewport(): void {
    const hr = this.renderer.plot_view.frame.bbox.h_range
    const vr = this.renderer.plot_view.frame.bbox.v_range
    const n = this.stop.length
    for (let i = 0; i < n; i++) {
      this.stop[i] = Math.max(this.stop[i], vr.start)
      this.sbottom[i] = Math.min(this.sbottom[i], vr.end)
      this.sleft[i] = Math.max(this.sleft[i], hr.start)
      this.sright[i] = Math.min(this.sright[i], hr.end)
    }
  }

  protected _hit_rect(geometry: RectGeometry): Selection {
    return this._hit_rect_against_index(geometry)
  }

  protected _hit_point(geometry: PointGeometry): Selection {
    const {sx, sy} = geometry
    const x = this.renderer.xscale.invert(sx)
    const y = this.renderer.yscale.invert(sy)

    const hits = this.index.indices({x0: x, y0: y, x1: x, y1: y})

    const result = hittest.create_empty_hit_test_result()
    result.indices = hits
    return result
  }

  protected _hit_span(geometry: SpanGeometry): Selection {
    const {sx, sy} = geometry

    let hits: number[]
    if (geometry.direction == 'v') {
      const y = this.renderer.yscale.invert(sy)
      const hr = this.renderer.plot_view.frame.bbox.h_range
      const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end)
      hits = this.index.indices({x0, y0: y, x1, y1: y})
    } else {
      const x = this.renderer.xscale.invert(sx)
      const vr = this.renderer.plot_view.frame.bbox.v_range
      const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end)
      hits = this.index.indices({x0: x, y0, x1: x, y1})
    }

    const result = hittest.create_empty_hit_test_result()
    result.indices = hits
    return result
  }

  draw_legend_for_index(ctx: Context2d, bbox: Rect, index: number): void {
    generic_area_legend(this.visuals, ctx, bbox, index)
  }
}

export namespace Box {
  export type Attrs = p.AttrsOf<Props>

  export type Props = Glyph.Props & LineVector & FillVector & HatchVector

  export type Visuals = Glyph.Visuals & {line: Line, fill: Fill, hatch: Hatch}
}

export interface Box extends Box.Attrs {}

export abstract class Box extends Glyph {
  properties: Box.Props

  constructor(attrs?: Partial<Box.Attrs>) {
    super(attrs)
  }

  static initClass(): void {
    this.mixins(['line', 'fill', 'hatch'])
  }
}
Box.initClass()


text:
#ifndef LIBITM_CACHELINE_H
#define LIBITM_CACHELINE_H 1

// Minimum cacheline size is 32, due to both complex long double and __m256.
// There's no requirement that 64-bit use a 64-byte cacheline size, but do
// so for now to make sure everything is parameterized properly.
#ifdef __x86_64__
# define CACHELINE_SIZE 64
#else
# define CACHELINE_SIZE 32
#endif

namespace GTM HIDDEN {

// A gtm_cacheline_mask stores a modified bit for every modified byte
// in the cacheline with which it is associated.
typedef sized_integral<CACHELINE_SIZE / 8>::type gtm_cacheline_mask;

union gtm_cacheline
{
  // Byte access to the cacheline.
  unsigned char b[CACHELINE_SIZE] __attribute__((aligned(CACHELINE_SIZE)));

  // Larger sized access to the cacheline.
  uint16_t u16[CACHELINE_SIZE / sizeof(uint16_t)];
  uint32_t u32[CACHELINE_SIZE / sizeof(uint32_t)];
  uint64_t u64[CACHELINE_SIZE / sizeof(uint64_t)];
  gtm_word w[CACHELINE_SIZE / sizeof(gtm_word)];

#ifdef __MMX__
  __m64 m64[CACHELINE_SIZE / sizeof(__m64)];
#endif
#ifdef __SSE__
  __m128 m128[CACHELINE_SIZE / sizeof(__m128)];
#endif
#ifdef __SSE2__
  __m128i m128i[CACHELINE_SIZE / sizeof(__m128i)];
#endif
#ifdef __AVX__
  __m256 m256[CACHELINE_SIZE / sizeof(__m256)];
  __m256i m256i[CACHELINE_SIZE / sizeof(__m256i)];
#endif

#if defined(__SSE__) || defined(__AVX__)
  // Copy S to D; only bother defining if we can do this more efficiently
  // than the compiler-generated default implementation.
  gtm_cacheline& operator= (const gtm_cacheline &s);
#endif // SSE, AVX
};

#if defined(__SSE__) || defined(__AVX__)
inline gtm_cacheline& ALWAYS_INLINE
gtm_cacheline::operator= (const gtm_cacheline & __restrict s)
{
#ifdef __AVX__
# define CP	m256
# define TYPE	__m256
#else
# define CP	m128
# define TYPE	__m128
#endif

  TYPE w, x, y, z;

  // ??? Wouldn't it be nice to have a pragma to tell the compiler
  // to completely unroll a given loop?
  switch (CACHELINE_SIZE / sizeof(TYPE))
    {
    case 1:
      this->CP[0] = s.CP[0];
      break;
    case 2:
      x = s.CP[0];
      y = s.CP[1];
      this->CP[0] = x;
      this->CP[1] = y;
      break;
    case 4:
      w = s.CP[0];
      x = s.CP[1];
      y = s.CP[2];
      z = s.CP[3];
      this->CP[0] = w;
      this->CP[1] = x;
      this->CP[2] = y;
      this->CP[3] = z;
      break;
    default:
      __builtin_trap ();
    }

  return *this;

#undef CP
#undef TYPE
}
#endif

} // namespace GTM

#endif // LIBITM_CACHELINE_H


text:
package nl.vu_compmedchem.klifs.interactions;

import org.knime.core.node.NodeView;

/**
 * NodeView for the "InteractionsGetIFP" Node.
 * Knime node to retrieve the interaction fingerprints (IFPs) from specific structures from KLIFS
 *
 * @author 3D-e-Chem (Albert J. Kooistra)
 */
public class InteractionsGetIFPNodeView extends NodeView<InteractionsGetIFPNodeModel> {

    /**
     * Creates a new view.
     *
     * @param nodeModel The model (class: {@link InteractionsGetIFPNodeModel})
     */
    protected InteractionsGetIFPNodeView(final InteractionsGetIFPNodeModel nodeModel) {
        super(nodeModel);

        // TODO instantiate the components of the view here.

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void modelChanged() {

        // TODO retrieve the new model from your nodemodel and
        // update the view.
        InteractionsGetIFPNodeModel nodeModel =
            (InteractionsGetIFPNodeModel)getNodeModel();
        assert nodeModel != null;

        // be aware of a possibly not executed nodeModel! The data you retrieve
        // from your nodemodel could be null, emtpy, or invalid in any kind.

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onClose() {

        // TODO things to do when closing the view
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onOpen() {

        // TODO things to do when opening the view
    }

}


text:
{% extends "layout.html" %}
{% block content %}

 {{ asset.entity_asset_path }}

      <audio controls tabindex="0">
        <source type="audio/mpeg" src="{{ url_for('static',filename='uploads/') }}{{ asset.entity_asset_path }}"/>
      </audio>

{% endblock %}


text:
*** This file contains the following structure of data files stored under it ***

--/data/
--------/original_poems_index.json
--------/poem_uid.json (* 1 json file per poem including the ones generated)
--------/user_stats.json (* file which might contain user info/statistics for the application)

***** Structure of the poem_uid json file *****

{
   "pid"      : <unique poem ID>
   "title"    : <title of the poem>
   "text"     : <poem text>
   "child"    : [ {"pid": <pid of neighbor poem>, "dist": <Levenshtein's (edit) distance> },
                  {"pid": <pid of neighbor poem>, "dist": <Levenshtein's (edit) distance> },
                  ...
                  ...
                  {"pid": <pid of neighbor poem>, "dist": <Levenshtein's (edit) distance> }
                ]
   "orig_src" : <pid of the original source poem from which this poem was derived>
   "poem_num" : <the poem number present in the Emily Dickinson poems collection>
}

***** Structure of the orginal_poems_index.json file *****

{
	"poem_num" : <the poem number present in the Emily Dickinson poems collection>
	"pid"      : <the randomly generated unique Poem ID>
}


text:
package kieker.analysis.generic.sink.graph.graphml;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.function.Function;

import kieker.analysis.generic.graph.IGraph;
import kieker.analysis.generic.graph.mapping.SimpleFileNameMapper;

/**
 * @author Sören Henning
 *
 * @since 1.14
 */
public class GraphMLFileWriterStage extends GraphMLWriterStage {

	private static final String GRAPHML = "graphml";

	public GraphMLFileWriterStage(final Function<IGraph, Path> fileNameMapper) {
		super(fileNameMapper.andThen(fileName -> {
			try {
				return Files.newOutputStream(fileName, StandardOpenOption.CREATE);
			} catch (final IOException e) {
				throw new IllegalArgumentException(e);
			}
		}));
	}

	public GraphMLFileWriterStage(final Path outputDirectory) {
		this(new SimpleFileNameMapper(outputDirectory, GRAPHML));
	}

}


text:
package nineChap8_DSA;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * Created at 2:31 PM on 11/25/15.
 */
public class TopKFrequentWords {
  public static void main(String[] args) {
    String[] words = new String[]{
        //"yes", "lint", "code",
        //"yes", "code", "baby",
        //"you", "baby", "chrome",
        //"safari", "lint", "code",
        //"body", "lint", "code"
        "B", "B" ,
        "C",
        "A", "A",
        "D", "D",
    };
    int k = 3;
    String[] ans = new TopKFrequentWords().topKFrequentWords(words, k);
    for (String word : ans) {
      System.out.println(word);
    }
  }

  class Pair implements Comparable<Pair> {
    String word;
    int count;
    Pair(String w, int c) {
      word = w;
      count = c;
    }

    @Override public int compareTo(Pair other) {
      if (this.count == other.count) {
        return this.word.compareTo(other.word);
      }
      return other.count - this.count;
    }
  }

  /**
   * @param words an array of string
   * @param k an integer
   * @return an array of string
   */
  public String[] topKFrequentWords(String[] words, int k) {
    // Write your code here
    if (words == null || words.length == 0) {
      return null;
    }

    PriorityQueue<Pair> maxPQ = new PriorityQueue<>();
    Map<String, Integer> map = new HashMap<>();
    for (String word : words) {
      if (!map.containsKey(word)) {
        map.put(word, 0);
      }
      map.put(word, map.get(word)+1);
    }

    for (String word : map.keySet()) {
      maxPQ.offer(new Pair(word, map.get(word)));
    }

    List<String> result = new ArrayList<>();
    String[] ans = new String[k];
    for (int i = 0; i < k; ++i) {
      //result.add(maxPQ.poll().word);
      ans[i] = maxPQ.poll().word;
    }
    return ans;
  }
}


text:
use [HYCP Inventory];
go

drop table [dbo].[DatesAndRates];
go

CREATE TABLE [dbo].[DatesAndRates]
(
    [YearMonth]          VARCHAR (7) not NULL primary key,
    [LastDayofMonth]     DATE NULL,
    [SemesterManagerial] VARCHAR (14) NULL,
    [YearNum]            VARCHAR (4) NULL,
    [MonthNum]           VARCHAR (2) NULL,
    [QuarterNum]         VARCHAR (12) NULL,
    [YearQuarter]        VARCHAR (17) NULL,
    [YearSemester]       VARCHAR (19) NULL,
    [Reval Period]       VARCHAR (19) NULL,
    [M]                  decimal (20,5) NULL,
    [A]                  decimal (20,5) NULL,
    [VI]                 decimal (20,5) NULL,
    [VB]                 decimal (20,5) NULL,
    [CC]                 decimal (20,5) NULL
);
go

truncate table datesandrates
insert into DatesAndRates
select * from [Data-DatesAndRates]

update dbo.DatesAndRates
set
	[SemesterManagerial] =
		case
			when [MonthNum] between 1 and 3 then 'Sem1(JanToJun)'
			when [MonthNum] between 4 and 6 then 'Sem1(JanToJun)'
			when [MonthNum] between 7 and 9 then 'Sem2(JulToDec)'
			when [MonthNum] between 10 and 12 then 'Sem2(JulToDec)'
		end,
	[QuarterNum] =
		case
			when [MonthNum] between 1 and 3 then 'Q1(JanToMar)'
			when [MonthNum] between 4 and 6 then 'Q2(AprToJun)'
			when [MonthNum] between 7 and 9 then 'Q3(JulToSep)'
			when [MonthNum] between 10 and 12 then 'Q4(OctToDec)'
		end,
	[YearSemester] =
		case
			when [MonthNum] between 1 and 3 then [YearNum] + '-Sem1(JanToJun)'
			when [MonthNum] between 4 and 6 then [YearNum] + '-Sem1(JanToJun)'
			when [MonthNum] between 7 and 9 then [YearNum] + '-Sem2(JulToDec)'
			when [MonthNum] between 10 and 12 then [YearNum] + '-Sem2(JulToDec)'
		end,
	[YearQuarter] =
		case
			when [MonthNum] between 1 and 3 then [YearNum] + '-Q1(JanToMar)'
			when [MonthNum] between 4 and 6 then [YearNum] + '-Q2(AprToJun)'
			when [MonthNum] between 7 and 9 then [YearNum] + '-Q3(JulToSep)'
			when [MonthNum] between 10 and 12 then [YearNum] + '-Q4(OctToDec)'
		end,
	[Reval Period] =
		case
			when [MonthNum] between 1 and 5 then [YearNum] + '-Sem1(JanToJun)'
			when [MonthNum] between 6 and 11 then [YearNum] + '-Sem2(JulToDec)'
			when [MonthNum] = 12 then [YearNum] + '-Sem1(JanToJun)'
		end


text:
Given a number n, determine what the nth prime is.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that
the 6th prime is 13.

If your language provides methods in the standard library to deal with prime
numbers, pretend they don't exist and implement them yourself.

## Setup

Go through the setup instructions for JavaScript to install the
 necessary dependencies:

http://exercism.io/languages/javascript/installation

## Running the test suite

The provided test suite uses [Jasmine](https://jasmine.github.io/).
You can install it by opening a terminal window and running the
following command:

```sh
npm install -g jasmine
```

Run the test suite from the exercise directory with:

```sh
jasmine nth-prime.spec.js
```

In many test suites all but the first test have been marked "pending".
Once you get a test passing, activate the next one by changing `xit` to `it`.

## Source

A variation on Problem 7 at Project Euler [http://projecteuler.net/problem=7](http://projecteuler.net/problem=7)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
"""Add a new file to the xpacsdb.patient_info table.

Usage:
    add_patient.py [options] <patientid> <file>
    add_patient.py -h

Arguments:
    patientid   PatientID to attach with the file.
                Error if there is no such PatientID.
                Use add_patient.py to add new patient to the database.
    file        File to be added to the database

Options:
    -h, --help              Show this screen
    -d, --debug             Show some debug information
    -s <host>               The MySQL server host IP address.
    -p <port>               MySQL port. Default is 3306.
    -u <user>               User name.
    --password=<password>   User password.
    --db=<database>         Database name. Default is xpacs.

Author: Avan Suinesiaputra - University of Auckland (2017)
"""

# Docopt is a library for parsing command line arguments
import docopt
import getpass
import mysql.connector
import termutils as tu
import datetime
import magic

def read_file(filename):
    with open(filename, 'rb') as f:
        contents = f.read()
    return contents

if __name__ == '__main__':

    try:
        # Parse arguments, use file docstring as a parameter definition
        arguments = docopt.docopt(__doc__)

        # Default values
        if not arguments['-s']:
            arguments['-s'] = '127.0.0.1'

        if not arguments['-p']:
            arguments['-p'] = 3306

        if not arguments['--db']:
            arguments['--db'] = 'xpacs'

        # Check user & password
        if not arguments['-u']:
            arguments['-u'] = raw_input('Username: ')

        if arguments['--password'] is None:
            arguments['--password'] = getpass.getpass('Password: ')

        # print arguments for debug
        if arguments['--debug']:
            tu.debug(str(arguments))

    # Handle invalid options
    except docopt.DocoptExit as e:
        tu.error(e.message)
        exit()

# connecting
print 'Connecting to mysql://' + arguments['-s'] + ':' + str(arguments['-p']) + ' ...'

try:
    cnx = mysql.connector.connect(user=arguments['-u'],
                                  host=arguments['-s'],
                                  port=arguments['-p'],
                                  password=arguments['--password'],
                                  database=arguments['--db'])

except mysql.connector.Error as err:
    print(err)
    exit()

# check the patient
# This should be unique. Have to check it first.
query = "SELECT * FROM patient_info WHERE patient_id = '" + arguments['<patientid>'] + "'"
if arguments['--debug']:
    tu.debug(query)

cursor = cnx.cursor(buffered=True, named_tuple=True)
cursor.execute(query)
isexist = cursor.rowcount>0
if arguments['--debug']:
    tu.debug("Number of rows = " + str(cursor.rowcount))

# get the row id of the patient
id = cursor.fetchone().id
if arguments['--debug']:
    tu.debug("The id row for " + arguments['<patientid>'] + " is " + str(id))

cursor.close()

if not isexist:
    tu.error("Patient " + arguments['<patientid>'] + " does not exist. Run add_patient.py to add a new patient.")

else:
    # creation_date = today
    dd = datetime.date.today()

    # ask for description
    desc = raw_input('Description [press <enter> to skip]: ')

    # build the query
    add_file = ("INSERT INTO aux_file "
                "(patient_infofk_id, creation_date, description, file, file_content_type) "
                "VALUES (%(pat_id)s, %(date)s, %(desc)s, %(file)s, %(content_type)s)")

    new_file = {
        'pat_id': id,
        'date': dd,
        'desc': desc,
        'file': read_file(arguments['<file>']),
        'content_type': magic.from_file(arguments['<file>'])
    }

    try:
        cursor = cnx.cursor()
        cursor.execute(add_file, new_file)
        cnx.commit()
        cursor.close()

    except mysql.connector.Error as err:
        tu.error(str(err))
        exit()

    tu.ok("File " + arguments['<file>'] + " added to the database")


text:
from font_util import *
from rgb_matrix import *
from rgb_colors import *

DISPLAY_WIDTH = 32
TEXT_HEIGHT = 8

# Put line of text
def write_line(text, line_no, fg_rgb, bg_rgb=None, center=False):
    if bg_rgb is None:
        bg_rgb = COLOR_BLACK
    # Set X offset at left, or maybe center
    x = 0
    if center:
        space = DISPLAY_WIDTH - get_word_width(text)
        x = int(space/2)
    cmd_SET_TEXT_COLOR(fg_rgb, bg_rgb)
    cmd_SET_TEXT_CURSOR(x, TEXT_HEIGHT * line_no)
    cmd_WRITE_BITCOLS(get_word_bitcols(text))
    cmd_PING()

# Clear line of text
def clear_line(line_no, bg_rgb=None):
    if bg_rgb is None:
        bg_rgb = COLOR_BLACK
    cmd_DRAW_RECT(0, TEXT_HEIGHT * line_no, DISPLAY_WIDTH, TEXT_HEIGHT, bg_rgb, True, 0)


text:
The purpose of this ARM Template is **deploy an IoT Hub** with an **Ubuntu Edge Simulator**.

The Linux Ubuntu virtual machine is configured to be an IoT Edge device

For this task you will:

1. Create an IoT Hub.
2. Register an IoT Edge device to your IoT hub.
3. Install and start the IoT Edge runtime on your virtual device.

To register the IoT Edge you will need to use PowerShell. You can either install the PowerShell extension on Visual Code or use the Cloud PowerShell on the AzurePortal.

For the extension, click [here](https://docs.microsoft.com/powershell/scripting/components/vscode/using-vscode?view=powershell-6)
For a quick start on the Cloud PowerShell click [here](https://docs.microsoft.com/azure/cloud-shell/quickstart-powershell)

Now, let's understand a bit better how **IOT Hub** and **IoT Edge Device** work.

## Overview

### What is Azure IoT Edge

Azure IoT Edge moves cloud analytics and custom business logic to devices so that your organization can focus on business insights instead of data management. Scale-out your IoT solution by packaging your business logic into standard containers, then you can deploy those containers to any of your devices and monitor it all from the cloud.

Azure IoT Edge is made up of three components:

- **IoT Edge modules** are containers that run Azure services, third-party services, or your code. Modules are deployed to IoT Edge devices and execute locally on those devices.
- The **IoT Edge runtime** runs on each IoT Edge device and manages the modules deployed to each device.
- A cloud-based interface enables you to remotely monitor and manage **IoT Edge devices**.

### IoT Edge modules

IoT Edge modules are units of execution, implemented as Docker compatible containers, that run your business logic at the edge. Multiple modules can be configured to communicate with each other, creating a pipeline of data processing. You can develop custom modules or package certain Azure services into modules that provide insights offline and at the edge.

### IoT Edge runtime

The Azure IoT Edge runtime enables custom and cloud logic on IoT Edge devices. The runtime sits on the IoT Edge device and performs management and communication operations. The runtime performs several functions:

- Installs and updates workloads on the device.
- Maintains Azure IoT Edge security standards on the device.
- Ensures that IoT Edge modules are always running.
- Reports module health to the cloud for remote monitoring.
- Manages communication between downstream leaf devices and an IoT Edge device, between modules on an IoT Edge device, and between an IoT Edge device and the cloud.

![Screen](./images/runtime.png)

### IoT Edge cloud interface

It's difficult to manage the software life cycle for millions of IoT devices that are often different makes and models or geographically scattered. Workloads are created and configured for a particular type of device, deployed to all of your devices, and monitored to catch any misbehaving devices. These activities can't be done on a per device basis and must be done at scale.

Azure IoT Edge integrates seamlessly with Azure IoT solution accelerators to provide one control plane for your solution's needs. Cloud services allow you to:

- Create and configure a workload to be run on a specific type of device.
- Send a workload to a set of devices.
- Monitor workloads running on devices in the field.

## Pre Deployment Steps

Before proceeding to the deployment of the AADDS template, we need to perform the following steps.

### PowerShell commands

Open the PowerShell terminal of your choice and run the following commands:

Log in to Azure:

#### az login

![Screen](./images/azlogin.png)

You will be redirected to the Azure Portal where you can insert your credentials and log in.

After logged in, you will see your credentials on the terminal.

To set the right subscription, type following command:

#### az account set --subscription "your subscription id"

![Screen](./images/azsetsub.png)

You use the Azure CLI to complete many of the steps in this quickstart, and Azure IoT has an extension to enable additional functionality.

Add the Azure IoT extension to the cloud shell instance.

#### az extension add --name azure-cli-iot-ext

![Screen](./images/azextension.png)

IoT Edge device: A Linux device or virtual machine to act as your IoT Edge device. You should use the Microsoft-provided Azure IoT Edge on Ubuntu virtual machine, which preinstalls everything you need to run IoT Edge on a device. For that you need to accept the terms of use:

#### az vm image accept-terms --urn microsoft_iot_edge:iot_edge_vm_ubuntu:ubuntu_1604_edgeruntimeonly:latest

![Screen](./images/azterms.png)

It will return a nice json, like this:

![Screen](./images/azterms2.png)

Now we can look at the template file:

## The Template

Don't let the size of the template scares you. The structure is very intuitive and once that you get the gist of it, you will see how easier your life will be regarding deploying resources to Azure.

These are the parameters on the template, most of them already have values inserted, the ones that you need to inform are: **adminUsername**, **adminPassword**, **resourceGroup** and the size of your Virtual Machine.

Here the list of all parameters:

Parameter | Suggested value | Description
:--------------- | :------------- |:---------------------
**vmName** | EdgeVM | The name of you Ubuntu Edge Virtual Machine.
**IoTHubname** | [concat('IoThub', resourceGroup().name)] | Name for your IoTHub.
**Location**| The default location | Select the geographic location for your resource group.
**Resource Group**| yourresourcegroup | That is the Resource Group that you need to deploy your resources.
**VmSize** | Standard_B1ls | The size of the VM. If you are running in a test or dev environment, it's recommended use a small Virtual Machine.
**adminUsername** | adminusername | Usernames can be a maximum of 20 characters and cannot end in a period (".").
**adminPassword** | Complex Password | Password requirements between 12 to 72 characters and have lower and upper characters, a digit and a special character (Regex match [\W_])
**virtualNetworkName** | vNet | Name of the Virtual Network.
**subnetName** | Subnet | Name of the Subnet.
**networkSecurityGroupName** | SecGroupNet | Name of the Network Security Group.
**IoTsku_name** | F1 | The name of the SKU. - F1, S1, S2, S3, B1, B2, B3. (F1 is the free tier.)
**IoTsku_units** | 1 | The number of provisioned IoT Hub units. See [here](https://docs.microsoft.com/azure/azure-subscription-service-limits#iot-hub-limits). 1 is the free tier.
**IoTsku_partitions** | 2 | This is linked to the SKU.For more information, click [here](https://docs.microsoft.com/azure/templates/microsoft.devices/2019-03-22/iothubs)
**IoTfeatures** | none | This is linked to the SKU. For more information, click [here](https://docs.microsoft.com/azure/templates/microsoft.devices/2019-03-22/iothubs)
**Resource Group**| myResourceGroup | That is the Resource Group that you need to deploy your resources.

## Deployment

There are a few ways to deploy this template.
You can use [PowerShell](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-template-deploy), [Azure CLI](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-template-deploy-cli), [Azure Portal](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-template-deploy-portal) or your favorite SDK.

For Azure CLI I'm the Visual Code with Azure CLI and PowerShell extensions. Check the Pre Steps session for more information. Or click [here](https://code.visualstudio.com/docs/azure/extensions).

### Resource Group

Now you need a Resource Group for our deployment. If you haven't yet created a Resource Group, you can do it now. If you are new on Azure and wonder what is a Resource Group? Bare with me! A Resource Group is a container that holds related resources for an Azure solution. The resource group includes those resources that you want to manage as a group. Simply saying, it's like a folder that contains files. Simple as that.

To create a Resource Group, you need a name and a location for your Resource Group.

For a list of locations, type: **az account list-locations**

To create the Resource group, type the command:

#### az group create --name IoTEdgeResources --location your_location

![Screen](./images/azgroup.png)

Super simple, right? Now that we have our **Resource Group** created, let's deploy the **IOT Hub** and **IOT Edge VM**.

#### az group deployment create --name "IOTdeployment" --resource-group "IoTEdgeResources" --template-file "./azuredeploy.json"

Insert the values for the parameters.
As you can see, it's running.

![Screen](./images/azdeploy.png)

Go grab a cup of coffee, have some fresh air. Before you come back you will have your **IOT Hub** and **IOT Edge VM**.

And there we go, your deployment is Succeeded:

![Screen](./images/azdeploy2.png)

Let's go and check the resource at the [Azure Portal](https://portal.azure.com).

On the portal, go to Resource Groups. On this blade, you can see the Resource Group we've created.

![Screen](./images/azdeployportal.png)

Click on the Resource Group and there it's the resources **Resources**:

- Virtual machine
- Disk
- Network interface
- Public IP address
- IoT Hub
- Network security group
- Network interface

Copy the name of the **IOT Hub**.

To have your IoT Hub connected with your IoT Device, we need to perform another task: register the IoT device.

### Register an IoT Edge device

Register an IoT Edge device with your newly created IoT hub.

Create a device identity for your IoT Edge device so that it can communicate with your IoT hub. The device identity lives in the cloud, and you use a unique device connection string to associate a physical device to a device identity.

#### az iot hub device-identity create --hub-name {hub_name} --device-id myEdgeDevice --edge-enabled

![Screen](./images/aziotdev.png)

### Connection String

Retrieve the connection string for your device, which links your physical device with its identity in IoT Hub.

#### az iot hub device-identity show-connection-string --device-id myEdgeDevice --hub-name {hub_name}

Copy the connection string.

![Screen](./images/azstring.png)

### Set the connection string on the IoT Edge device

If you're using the Azure IoT Edge on Ubuntu virtual machine as described in the prerequisites, then your device already has the IoT Edge runtime installed. You just need to configure your device with the device connection string that you retrieved in the previous section. You can do this remotely without having to connect to the virtual machine. Run the following command, replacing {device_connection_string} with your string.

#### az vm run-command invoke -g IoTEdgeResources -n EdgeVM --command-id RunShellScript --script "/etc/iotedge/configedge.sh '{device_connection_string}'"

![Screen](./images/azruncmd.png)

As you can see, the command was successful.

![Screen](./images/azruncmd2.png)

Here you have an overview of your **IOT Hub**.

![Screen](./images/azpreview.png)

Congratulations, you just deployed an **IoT Hub** and **Ubuntu VM edge simulator**.

Don't forget to have fun!

**p.s.: Pretty easy to create resources on Azure, right? But if you are the sort of IT guy that always loves automation, here is the surprise. Just click on the button below and it will automatically deploy the IoT Hub and Ubuntu VM edge simulator.**

#### Important disclaimer: Azure charges you for the resources you are using, and you don't want to finish all your credits at once, right? So, don't forget to stop the Ubuntu VM edge simulator at the portal or even delete the Resource Group you have created to avoid unnecessary charges

### How to shutdown your resources

#### Using the portal

On the portal, open your Resource Group, look for the Virtual Machine and you can either stop it or delete it.

![Screen](./images/off1.png)

You can also delete the Resource Group.

![Screen](./images/off2.png)

Just refresh your screen and you are good to go.


text:
source "$DATADIR/modules/utils.sh"

hook_module_add() {
	hook_once_after_config_change "service_restart_delete_retained wb-homa-gpio /devices/wb-gpio/#"
}

hook_module_del() {
	systemctl stop wb-mqtt-gpio || true
	wb_gpio_del $GPIO_PIN1_SCL
	wb_gpio_del $GPIO_PIN2_SDA
	hook_once_after_config_change "service_restart_delete_retained wb-homa-gpio /devices/wb-gpio/#"
}


text:
package threads;

/**
 * @auther xzl on 14:18 2018/3/6
 */
public class TestSyncWait1 implements Runnable{
    int b = 100;
    public static void main(String[] args) throws InterruptedException {
        TestSyncWait1 wait = new TestSyncWait1();
        new Thread(wait).start();
        wait.m2();
        System.out.println("主线程 b :"+wait.b);
    }
    void m1() throws InterruptedException {
        synchronized(this){
            b = 1000;   Thread.sleep(1000);
            System.out.println("m1==="+b);
        }
    }
    void m2() throws InterruptedException {
        synchronized(this){
            Thread.sleep(250); b = 2000;
            System.out.println("m2-----"+b);
        }
    }
    @Override
    public void run() {
        try {
            m1();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
require 'test_helper'

class G5BuildpackRakeTasksTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, G5BuildpackRakeTasks
  end
end


text:
import {IStateProvider} from 'angular-ui-router';
import {PlacesController} from './places.controller.ts';
import {PlacesService} from './places.service.ts';
const templateUrl = require('./places.html');

module Places {

    /*@ngInject*/
    export function routes($stateProvider:IStateProvider) {
        $stateProvider
            .state('places', {
                url: '/places',
                templateUrl: templateUrl,
                controller: PlacesController,
                controllerAs: "placesController",
                resolve: {
                    places: (placesService : PlacesService) => {
                        return placesService.all();
                    }
                }
            });
    }
}

export = Places;


text:
"""Support for freedompro."""
from __future__ import annotations

from datetime import timedelta
import logging
from typing import Final

from pyfreedompro import get_list, get_states

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

PLATFORMS: Final[list[Platform]] = [
    Platform.BINARY_SENSOR,
    Platform.CLIMATE,
    Platform.COVER,
    Platform.FAN,
    Platform.LIGHT,
    Platform.LOCK,
    Platform.SENSOR,
    Platform.SWITCH,
]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Freedompro from a config entry."""
    hass.data.setdefault(DOMAIN, {})
    api_key = entry.data[CONF_API_KEY]

    coordinator = FreedomproDataUpdateCoordinator(hass, api_key)
    await coordinator.async_config_entry_first_refresh()

    entry.async_on_unload(entry.add_update_listener(update_listener))

    hass.data[DOMAIN][entry.entry_id] = coordinator

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unload_ok

async def update_listener(hass, config_entry):
    """Update listener."""
    await hass.config_entries.async_reload(config_entry.entry_id)

class FreedomproDataUpdateCoordinator(DataUpdateCoordinator):
    """Class to manage fetching Freedompro data API."""

    def __init__(self, hass, api_key):
        """Initialize."""
        self._hass = hass
        self._api_key = api_key
        self._devices = None

        update_interval = timedelta(minutes=1)
        super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)

    async def _async_update_data(self):
        if self._devices is None:
            result = await get_list(
                aiohttp_client.async_get_clientsession(self._hass), self._api_key
            )
            if result["state"]:
                self._devices = result["devices"]
            else:
                raise UpdateFailed()

        result = await get_states(
            aiohttp_client.async_get_clientsession(self._hass), self._api_key
        )

        for device in self._devices:
            dev = next(
                (dev for dev in result if dev["uid"] == device["uid"]),
                None,
            )
            if dev is not None and "state" in dev:
                device["state"] = dev["state"]
        return self._devices


text:
package component.customisation;

import com.flextrade.jfixture.JFixture;
import com.flextrade.jfixture.customisation.TracingCustomisation;
import org.junit.Test;
import testtypes.TypeWithProperties;

import static org.junit.Assert.assertFalse;

public class TestTracingCustomisation {

    @Test
    public void populates_appendable_instance_with_tracing_data() {
        Appendable stringBuilder = new StringBuilder();
        JFixture fixture = new JFixture();
        fixture.customise(new TracingCustomisation(stringBuilder));

        fixture.create(TypeWithProperties.class);
        String trace = stringBuilder.toString();
        assertFalse(trace.isEmpty());
    }
}


text:
package com.esri.core.geometry;

import junit.framework.TestCase;
import org.junit.Test;

public class TestFailed extends TestCase {
	@Override
	protected void setUp() throws Exception {
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	@Test
	public void testCenterXY() {
		Envelope env = new Envelope(-130, 30, -70, 50);
		assertEquals(-100, env.getCenterX(), 0);
		assertEquals(40, env.getCenterY(), 0);
	}

	@Test
	public void testGeometryOperationSupport() {
		Geometry baseGeom = new Point(-130, 10);
		Geometry comparisonGeom = new Point(-130, 10);
		SpatialReference sr = SpatialReference.create(4326);

		@SuppressWarnings("unused")
		Geometry diffGeom = null;
		int noException = 1; // no exception
		try {
			diffGeom = GeometryEngine.difference(baseGeom, comparisonGeom, sr);

		} catch (IllegalArgumentException ex) {
			noException = 0;
		} catch (GeometryException ex) {
			noException = 0;
		}
		assertEquals(noException, 1);
	}

	@Test
	public void TestIntersection() {
		OperatorIntersects op = (OperatorIntersects) OperatorFactoryLocal
				.getInstance().getOperator(Operator.Type.Intersects);
		Polygon polygon = new Polygon();
		// outer ring1
		polygon.startPath(0, 0);
		polygon.lineTo(10, 10);
		polygon.lineTo(20, 0);

		Point point1 = new Point(15, 10);
		Point point2 = new Point(2, 10);
		Point point3 = new Point(5, 5);
		boolean res = op.execute(polygon, point1, null, null);
		assertTrue(!res);
		res = op.execute(polygon, point2, null, null);
		assertTrue(!res);
		res = op.execute(polygon, point3, null, null);
		assertTrue(res);
	}
}


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");

?>

<form method="post" id="entities-settings-form" action="<?= $view->action('update_entity_settings') ?>">
    <?= $this->controller->token->output('update_entity_settings') ?>

    <fieldset style="margin-bottom:15px;">
        <legend><?= t('Settings') ?></legend>

        <label class="launch-tooltip" data-placement="right" title="<?= t('Defines whether the Doctrine proxy classes are created on the fly. On the fly generation is active when development mode is enabled.') ?>"><?= t('Doctrine Development Mode') ?>

                <input type="radio" name="DOCTRINE_DEV_MODE" value="1" <?php if (Config::get('concrete.cache.doctrine_dev_mode')) {
    ?> checked <?php
} ?> />
                <?=t('On - Proxy classes will be generated on the fly. Good for development.')?>

                <input type="radio" name="DOCTRINE_DEV_MODE" value="0" <?php if (!Config::get('concrete.cache.doctrine_dev_mode')) {
    ?> checked <?php
} ?> />
                <?= t('Off - Proxy classes need to be manually generated. Helps speed up a live site.') ?>

    </fieldset>

        <?= $interface->submit(t('Save'), 'entities-settings-form', 'right', 'btn-primary') ?>

</form>

<form method="post" id="entities-refresh-form" action="<?= $view->action('refresh_entities') ?>">
    <?= $this->controller->token->output('refresh_entities') ?>

    <fieldset>
        <legend><?=t("Entities")?></legend>

<?= t("Search for application and package-specific entities, refresh their database schema and generate their proxy classes.") ?>

        <?= $interface->submit(tc('Doctrine', 'Refresh Entities'), 'entities-refresh-form', 'left', 'btn-default') ?>
    </fieldset>
</form>


text:
var rootUrl = "../service.html";
	    var xmlData = {};

	    var guestKey = "75A7659CCA1FCB4C485A83D3BC022AFB";

        function encode(xmlText) {
            xmlText = xmlText.replace(/</g, "<");
            xmlText = xmlText.replace(/>/g, ">");
            xmlText = xmlText.replace(/\"/g, """);
            return xmlText;
        }

        function callAjax(xmlData, reqDiv, sucessF){
	        reqDiv.innerHTML = "
Processing...
";
			$.ajax({
			    type: "POST",
			    url: rootUrl,
			    data: xmlData,
			    cache:false,
			    dataType: "text",
			    success: sucessF
            });
        }

		function showSucess(header, reqDiv, resData, resDiv) {
            var requestXml = "

" + header +
                " Request Details
URL: " + rootUrl +
	                "
POST Parameters" ;
	        $.each(xmlData,
	            function(key, value) {
                    requestXml = requestXml + "
" + key + "=" + encode(value);
                }
            );

            requestXml = requestXml + "
";

		    reqDiv.innerHTML = "
" + header + "
" + requestXml;

		    var isError = (resData.indexOf("<error>") != -1) ;
		    var fontStyle = "";
		    if ( isError) fontStyle = "";

		    var headerText = "
" + header + " Response Details
";
		    if ( isError) headerText = "
" + header + " Processing Error
";

		    resDiv.innerHTML = "
" + fontStyle +
			    headerText + encode(resData) + "
";
		}