text:
using System;
using System.IO;
using HelperSharp;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SpecFlowHelper.Configuration;
using SpecFlowHelper.Helpers;
using SpecFlowHelper.Integrations;
using TechTalk.SpecFlow;
using TestSharp;

namespace SpecFlowHelper.Steps
{
    [Binding]
    public class JobSteps : StepsBase
    {
        [When(@"executo o job '(.*)' e aguardo pelo texto '(.*)' no log")]
        public void QuandoExecutoOJob(string name, string text)
        {
            QuandoExecutoOJobSegundos(name, text, Convert.ToInt32(AppConfig.ScenarioTimeout.TotalSeconds));
        }

        [When(@"executo o job '(.*)' e aguardo pelo texto '(.*)' no log durante '(.*)' segundos")]
        public void QuandoExecutoOJobSegundos(string name, string text, int segundos)
        {
            var exeFileName = GetExeFileName();
            var logFileName = GetLogFileName();

            StepHelper.Log("Executable filename: {0}", exeFileName);
            StepHelper.Log("Log filename: {0}", logFileName);

            var processName = AppConfig.JobsProcessName;

            QuandoEncerroOJob(name);

            StepHelper.Sleep(1000, "aguardando job liberar arquivo de log");
            StepHelper.Log("Deleting log files");
            FileHelper.DeleteFiles(logFileName);

            StepHelper.Wait("Aguardando job....");

            StepHelper.Log("Running job");

            if (string.IsNullOrEmpty(name))
                ProcessHelper.Run(exeFileName, string.Empty, false);
            else
                ProcessHelper.Run(exeFileName, "-job:{0}".With(name), false);

            EntaoExisteOTextoNoLogDoJobSegundos(text, segundos);
            QuandoEncerroOJob(name);
        }

        [When(@"executo o job e aguardo pelo texto '(.*)' no log")]
        public void QuandoExecutoOJob(string text)
        {
            QuandoExecutoOJob(null, text);
        }

        [When(@"executo o job e aguardo pelo texto '(.*)' na saída")]
        public void QuandoExecutoOJobEAguardoPeloTextoNaSaida(string text)
        {
            QuandoExecutoOJobEAguardoPeloTextoNaSaida(text, Convert.ToInt32(AppConfig.ScenarioTimeout.TotalSeconds));
        }

        [When(@"executo o job e aguardo pelo texto '(.*)' na saída por '(.*)' segundos")]
        public void QuandoExecutoOJobEAguardoPeloTextoNaSaida(string text, int timeoutSeconds)
        {
            if (AppConfig.JobsEnabled)
            {
                var exeFileName = GetExeFileName();

                StepHelper.Log("Executable filename: {0}", exeFileName);

                var processName = AppConfig.JobsProcessName;

                QuandoEncerroOJob(null);

                StepHelper.Wait("Waiting job....");
                StepHelper.Log("Running job");

                ProcessHelperEx.Run(exeFileName, string.Empty, text, timeoutSeconds);

                QuandoEncerroOJob(null);
            }
            else
            {
                StepHelper.Log($"Job disabled: {AppConfig.JobsEnabledInfo}");
            }
        }

        [When(@"executo o job")]
        public void QuandoExecutoOJob()
        {
            if (AppConfig.JobsEnabled)
            {
                var exeFileName = GetExeFileName();

                StepHelper.Log("Executable filename: {0}", exeFileName);

                var processName = AppConfig.JobsProcessName;

                QuandoEncerroOJob(null);

                StepHelper.Wait("Waiting job....");
                StepHelper.Log("Running job");

                ProcessHelperEx.Run(exeFileName, string.Empty);
            }
            else
            {
                StepHelper.Log($"Job disabled: {AppConfig.JobsEnabledInfo}");
            }
        }

        [Then(@"existe o texto '(.*)' no log do job")]
        public void EntaoExisteOTextoNoLogDoJob(string text)
        {
            EntaoExisteOTextoNoLogDoJobSegundos(text, Convert.ToInt32(AppConfig.ScenarioTimeout.TotalSeconds));
        }

        [Then(@"existe o texto '(.*)' no log do job e aguardo por '(.*)' segundos")]
        public void EntaoExisteOTextoNoLogDoJobSegundos(string text, int segundos)
        {
            StepHelper.Log("Waiting for text '{0}' on job's log file", text); ;

            var logFileName = GetLogFileName();

            FileHelper.WaitForFileContentContains(logFileName, text, segundos);
            ProcessHelper.KillAll(AppConfig.JobsProcessName);

            FileAssert.ContainsContent(text, logFileName);
        }

        [Then(@"não existe o texto '(.*)' no log do job")]
        public void EntaoNaoExisteOTextoNoLogDoJob(string text)
        {
            var logFileName = GetLogFileName();
            ProcessHelper.KillAll(AppConfig.JobsProcessName);

            Assert.IsFalse(FileHelper.ContainsContent(logFileName, text));
        }

        [When(@"encerro o job '(.*)'")]
        public void QuandoEncerroOJob(string name)
        {
            var processName = AppConfig.JobsProcessName;

            if (String.IsNullOrEmpty(name))
                StepHelper.Log("Kiling {0} process", processName);
            else
                StepHelper.Log("Kiling {0} process for job '{1}'", processName, name);

            ProcessHelper.KillAll(processName);
            ProcessHelper.WaitForExit(processName);
        }

        [When(@"encerro o job")]
        public void QuandoEncerroOJob() => QuandoEncerroOJob("");

        public static string GetLogFileName()
        {
            var logFileName = Path.Combine(GetRootPath(), AppConfig.JobsLogFileName);
            return logFileName;
        }

        public static string GetExeFileName()
        {
            var exeFileName = Path.Combine(GetConfigPath(), "{0}.exe".With(AppConfig.JobsProcessName));

            return exeFileName;
        }

        private static string GetConfigPath()
        {
            var configPath = Path.Combine(GetBinPath(), AppConfig.Configuration);
            return configPath;
        }

        private static string GetBinPath()
        {
            var binPath = Path.Combine(GetRootPath(), "bin");
            return binPath;
        }

        private static string GetRootPath()
        {
            var backgroundWorkerPath = VSProjectHelper.GetProjectFolderPath(AppConfig.JobsProjectFolderName);
            return backgroundWorkerPath;
        }
    }
}


text:
<?php

use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;

class AddCannedEmails extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('canned_message', [ 'signed' => false ]);
      $table
        ->addColumn('slug', 'string', [ 'limit' => 50 ])
        ->addColumn('subject', 'string', [ 'limit' => 255, 'null' => true ])
        ->addColumn('content', 'text', [
                      'limit' => MysqlAdapter::TEXT_MEDIUM,
                      'null' => true,
                    ])
        /* Ideally would be same enum as txn table, but oh well */
        ->addColumn('new_status', 'string', [ 'limit' => 50 ])
        ->addColumn('created', 'datetime', [
                      'default' => 'CURRENT_TIMESTAMP'
                    ])
        ->addColumn('modified', 'datetime', [
                      'default' => 'CURRENT_TIMESTAMP',
                      'update' => 'CURRENT_TIMESTAMP'
                    ])
        ->addColumn('active', 'integer', [
                      'limit' => MysqlAdapter::INT_TINY,
                      'default' => 1,
                    ])
        ->create();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import argparse

class CowfileAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):

        # Check cowfile flag

        _cowfile = values[0].strip()
        print("COWFILE changed: " + _cowfile)

        setattr(namespace, self.dest, _cowfile)


text:
// put everything into a local scope:
(function ($, undefined) {

    // -------------------------------------------
    //                  Main flow
    // -------------------------------------------
    //
    // calculate the widget files URLs:
    //
    var url_js = calcThisScriptSrc();
    var url_css = url_js.replace(".js", ".css");
    var url_html = url_js.replace(".js", ".html");
    //
    // add widget css:
    //
    addStyleSheet(url_css);
    //
    // Now we will start to load the widget HTML code, and wait for both the HTML and page DOM ready state
    //
    var dom_ready = $.Deferred(); // to wait when the page DOM is ready
    var html_ready = $.Deferred(); // to wait when the widget HTML is loaded
    //
    // setup the DOM waiting:
    $(document).ready(function () { dom_ready.resolve(); });
    //
    // start to load the widget HTML text:
    loadText(url_html).done(function (html) { html_ready.resolve(html); });
    //
    // start the waiting
    // when both async operations are completed, do further processing (call the replaceSelectTagsToWidgets() function):
    $.when(dom_ready, html_ready).done(function (dom_result, html_result) {
        replaceSelectTagsToWidgets($.trim(html_result));
    });
    //
    // all done!

    //#region Process <select> tags

    // -------------------------------------------
    //          Process <select> tags
    // -------------------------------------------

    // process all the <select> tags:
    function replaceSelectTagsToWidgets(html) {
        $("select").each(function () {
            var $original_select = $(this);
            //
            if ($original_select.hasClass("myselect-skip")) return; // skip the explicitly omitted tags
            if ($original_select.prop("multiple")) return; // skip the listboxes
            //
            processSelectTag($(this), html); // process the tag
        });
    }

    // process the current <select> tag:
    function processSelectTag($original_select, html) {
        // hide the <select> tag:
        if (!$original_select.hasClass("myselect-debug")) {
            $original_select.css("position", "fixed");
            $original_select.css("left", "-1000px");
            $original_select.attr("tabindex", "-1"); // remove the tag from the TAB sequence
        }
        //
        var widget = createWidget(html, $original_select); // create the widget
        //
        $original_select.after(widget.dom); // insert the widget after the <select> tag
        //
        widget.adjust();
    }

    //#endregion

    //#region Create Widget

    // -------------------------------------------
    //                  Create Widget
    // -------------------------------------------

    function createWidget(html, $original_select) {
        //
        // setup the part_ variables:
        //
        var html_dom = $.parseHTML(html);
        var $part_main = $(".part_main", html_dom).first();
        var $part_text = $(".part_text", html_dom).first();
        var $part_popup = $(".part_popup", html_dom).first();
        //
        // fill the popup list:
        //
        $("> option", $original_select).each(function (index, element) {
            $part_popup.append('
' + $(element).text() + '
');
        });
        var $popup_items = $("> li", $part_popup);
        //
        // setup the initial selected index:
        //
        setIndex(getOriginalSelectedIndex());

        //
        // to adjust the widget when inserted into the page DOM:
        //

        function adjust() {
            // adjust the width:
            adjust_main_width();
            // close the popup
            $part_popup.slideUp(0);
        }

        $(window).on("load", function () {
            adjust_main_width();
        });

        function adjust_main_width() {
            var main_width = $part_main.width();
            var main_innerWidth = $part_main.innerWidth();
            var main_outerWidth = $part_main.outerWidth();
            //
            if ((main_width === main_innerWidth) && (main_width === main_outerWidth)) {
                return; // Chrome, Firefox, Safary: adjust() call when the DOM is not good yet
            }
            //
            var popup_width = $part_popup.width();
            var popup_outerWidth = $part_popup.outerWidth();
            //
            var main_delta = main_outerWidth - main_width;
            var popup_delta = popup_outerWidth - popup_width;
            //
            if ((main_width + main_delta) < popup_outerWidth) {
                $part_main.width(popup_outerWidth - main_delta);
            } else {
                $part_popup.width(main_outerWidth - popup_delta);
            }
        }

        //
        // setup the UI event handlers:
        //

        $original_select.change(function () {
            setIndex(getOriginalSelectedIndex());
        });

        $part_main.click(function () {
            $part_main.focus();
            toggle();
        });

        $part_main.blur(function () {
            close();
        });

        $part_main.keydown(function (event) {
            var Key = { Space: 32, Esc: 27, Enter: 13, Left: 37, Up: 38, Right: 39, Down: 40, PgUp: 33, PgDn: 34, Home: 36, End: 35 };
            //
            switch (event.which) {
                case Key.Space: open(); break;
                case Key.Esc: close(); break;
                case Key.Enter: close(); break;
                case Key.Home: goFirst(); break;
                case Key.PgUp: goFirst(); break;
                case Key.End: goLast(); break;
                case Key.PgDn: goLast(); break;
                case Key.Left: goPrev(); break;
                case Key.Right: goNext(); break;
                case Key.Up: if (event.altKey) { open(); } else { goPrev(); } break;
                case Key.Down: if (event.altKey) { open(); } else { goNext(); } break;
            }
        });

        $part_popup.on("click", "li", function () {
            var index = Number($(this).attr("data-index"));
            setIndex(index);
            $part_main.focus();
        });

        //
        //  utility functions:
        //

        function getOriginalSelectedIndex() {
            return $original_select.prop("selectedIndex");
        }

        function setOriginalSelectedIndex(value) {
            $original_select.prop("selectedIndex", value);
        }

        function setIndex(index) {
            setOriginalSelectedIndex(index);
            //
            $popup_items.removeClass("selected");
            if (index >= 0) {
                var $item = $popup_items.eq(index);
                $item.addClass("selected");
                $part_text.text($item.text());
            }
        };

        function goPrev() {
            var index = getOriginalSelectedIndex();
            if (index > 0) setIndex(index - 1);
        }

        function goNext() {
            var index = getOriginalSelectedIndex();
            if (index < $popup_items.length - 1) setIndex(index + 1);
        }

        function goFirst() {
            setIndex(0);
        }

        function goLast() {
            setIndex($popup_items.length - 1);
        }

        function open() {
            $part_main.addClass("open");
            $part_popup.slideDown("slow");
        }

        function close() {
            $part_popup.slideUp("slow", function () { $part_main.removeClass("open"); });
        }

        function toggle() {
            if ($part_main.hasClass("open")) {
                close();
            } else {
                open();
            }
        }

        //
        // return the widget object:
        //

        return { dom: html_dom, adjust: adjust };
    }

    //#endregion

    //#region Utils

    // -------------------------------------------
    //                  Utils
    // -------------------------------------------

    // returns src property of the


text:
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
dbLogin();
sec_session_start();
?>
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="description" content="">
	<meta name="author" content="Brandon Morris">
	<title>Select List</title>

	<link rel="stylesheet" href="css/bootstrap.min.css">

	<link rel="stylesheet" href="css/sb-admin.css">
	<link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">

	<link rel="stylesheet" href="css/highlight.css">
	<link rel="stylesheet" href="css/bootstrap-switch.css">
	<link rel="stylesheet" href="css/main.css">

      Home

				<? buttons() ?>
				<button class='btn-lg btn btn-default'>Test Map</button>

<? include 'includes/modal.php'; ?>


text:
package in.showoffs.mobidb.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import icepick.State;
import in.showoffs.mobidb.R;
import in.showoffs.mobidb.activities.MovieDetails;
import in.showoffs.mobidb.apapters.MovieListAdapter;
import in.showoffs.mobidb.listeners.MovieListListener;
import in.showoffs.mobidb.models.movies.Movie;
import in.showoffs.mobidb.models.movies.MoviesResult;
import in.showoffs.mobidb.presenters.MovieListImpl;
import in.showoffs.mobidb.presenters.MovieListPresenter;
import in.showoffs.mobidb.utils.Constants;
import in.showoffs.mobidb.utils.SharedPrefUtils;

public class DashboardFragment extends Fragment implements MovieListListener,
        MovieListAdapter.MovieListAdapterListener {

    private static final String SAVED_LAYOUT_MANAGER = "RECYCLER_POSITION";
    private static final String SAVED_MOVIE_RESULTS = "MOVIE_RESULT";
    private static final String PAGE = "PAGE";
    private static final String TOTAL_PAGE = "TOTAL_PAGES";
    private static final String SORT_BY = "SORT_BY";
    @BindView(R.id.movie_list_recycler)
    RecyclerView movieListRecycler;
    @BindView(R.id.loader)
    ProgressBar loader;
    @BindView(R.id.error)
    LinearLayout error;
    @State
    int page = 0;
    @State
    int totalPages = 0;
    @State
    boolean mIsLoading = true;
    DashboardInteractionListener interactionListener;
    private String sortBy = Constants.SORT_BY_POPULARITY_DESC;
    private GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3, LinearLayoutManager.VERTICAL,
            false);
    private MovieListAdapter adapter = new MovieListAdapter();
    private MovieListPresenter movieListP;
    private RecyclerView.OnScrollListener mRecyclerViewOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount = layoutManager.getChildCount();
            int totalItemCount = layoutManager.getItemCount();
            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

            if (!mIsLoading) {
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0) {
                    if (page < totalPages) {
                        mIsLoading = true;
                        movieListP.loadMovieList(page + 1, sortBy);
                    } else {
                        mIsLoading = false;
                    }
                }
            }
        }
    };

    public DashboardFragment() {
    }

    @OnClick(R.id.error)
    public void retry(View view) {
        movieListP.loadMovieList(0, sortBy);
    }

    @Override
    public void showMovieDetails(View view, Movie movie) {
        Intent intent = new Intent(view.getContext(), MovieDetails.class);
        intent.putExtra(Constants.TITLE, movie.getTitle());
        intent.putExtra(Constants.MOVIE, movie);
        intent.putExtra(MovieDetails.URI, (String.format("%s%s", "http://image.tmdb.org/t/p/w342", movie.getPosterPath())));
        Pair<View, String> p1 = Pair.create(view, "poster");
        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), p1);
        getActivity().startActivity(intent, options.toBundle());
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof DashboardInteractionListener) {
            interactionListener = (DashboardInteractionListener) context;
        } else {
            throw new ClassCastException(context.getClass().getName() + "Must implement DashboardInteractionListener");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        ButterKnife.bind(this, view);
        adapter.setMListener(this);
        movieListRecycler.setAdapter(adapter);
        if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            layoutManager = new GridLayoutManager(getContext(), 3);
        } else {
            layoutManager = new GridLayoutManager(getContext(), 5);
        }
        movieListRecycler.setLayoutManager(layoutManager);
        movieListRecycler.addOnScrollListener(mRecyclerViewOnScrollListener);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        movieListP = new MovieListImpl(this);
        sortBy = SharedPrefUtils.getSortValue();
        if (savedInstanceState == null) {
            movieListP.loadMovieList(0, sortBy);
            mIsLoading = true;
        } else {
            mIsLoading = false;
        }
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            showLoading(false);
            page = savedInstanceState.getInt(PAGE);
            totalPages = savedInstanceState.getInt(TOTAL_PAGE);
            sortBy = savedInstanceState.getString(SORT_BY);
            Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(SAVED_LAYOUT_MANAGER);
            List<Movie> savedMovies = savedInstanceState.getParcelableArrayList(SAVED_MOVIE_RESULTS);
            adapter.clear();
            adapter.add(savedMovies);
            movieListRecycler.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(SAVED_LAYOUT_MANAGER, movieListRecycler.getLayoutManager().onSaveInstanceState());
        outState.putParcelableArrayList(SAVED_MOVIE_RESULTS, (ArrayList<Movie>) adapter.getMovies());
        outState.putInt(PAGE, page);
        outState.putInt(TOTAL_PAGE, totalPages);
        outState.putString(SORT_BY, sortBy);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        if (sortBy.equals(Constants.SORT_BY_POPULARITY_DESC)) {
            menu.getItem(0).getSubMenu().getItem(0).setChecked(true);
            setTitle(Constants.POPULAR_MOVIES);
        } else if (sortBy.equals(Constants.SORT_BY_VOTE_AVERAGE_DESC)) {
            menu.getItem(0).getSubMenu().getItem(1).setChecked(true);
            setTitle(Constants.TOP_RATED);
        }
    }

    @Override
    public void showLoading(boolean show) {
        if (show) {
            if (adapter.getItemCount() > 0) return;
            loader.setVisibility(View.VISIBLE);
        } else {
            loader.setVisibility(View.GONE);
        }
    }

    private void setTitle(String title) {
        if (interactionListener != null) {
            interactionListener.setTitle(title);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.popular_menu: {
                item.setChecked(true);
                SharedPrefUtils.setSortValue(Constants.SORT_BY_POPULARITY_DESC);
                sortBy = Constants.SORT_BY_POPULARITY_DESC;
                adapter.clear();
                adapter.notifyDataSetChanged();
                movieListP.loadMovieList(0, sortBy);
                setTitle(Constants.POPULAR_MOVIES);
                break;
            }
            case R.id.rated_menu: {
                item.setChecked(true);
                SharedPrefUtils.setSortValue(Constants.SORT_BY_VOTE_AVERAGE_DESC);
                sortBy = Constants.SORT_BY_VOTE_AVERAGE_DESC;
                adapter.clear();
                adapter.notifyDataSetChanged();
                movieListP.loadMovieList(0, sortBy);
                setTitle(Constants.TOP_RATED);
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    public interface DashboardInteractionListener {
        void setTitle(String title);
    }

    @Override
    public void showError(boolean show) {
        if (adapter.getItemCount() > 0) return;
        if (show) {
            error.setVisibility(View.VISIBLE);
        } else {
            error.setVisibility(View.GONE);
        }
    }

    @Override
    public void onMovieListLoaded(MoviesResult moviesResult) {
        mIsLoading = false;
        showLoading(false);
        showError(false);
        page = moviesResult.getPage();
        totalPages = moviesResult.getTotalPages();
        adapter.add(moviesResult.getMovies());
    }

    @Override
    public void onErrorLoading(Exception e) {
        mIsLoading = false;
        showError(true);
    }

    @Override
    public Context getTheContext() {
        return getContext();
    }
}


text:
package endtoend

import (
	"fmt"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	"github.com/stretchr/testify/require"

	"context"

	"vitess.io/vitess/go/mysql"
)

// TestKill opens a connection, issues a command that
// will sleep for a few seconds, waits a bit for MySQL to start
// executing it, then kills the connection (using another
// connection). We make sure we get the right error code.
func TestKill(t *testing.T) {
	ctx := context.Background()
	conn, err := mysql.Connect(ctx, &connParams)
	if err != nil {
		t.Fatal(err)
	}

	// Create the kill connection first. It sometimes takes longer
	// than 10s
	killConn, err := mysql.Connect(ctx, &connParams)
	if err != nil {
		t.Fatal(err)
	}
	defer killConn.Close()

	errChan := make(chan error)
	go func() {
		_, err = conn.ExecuteFetch("select sleep(10) from dual", 1000, false)
		errChan <- err
		close(errChan)
	}()

	// Give extra time for the query to start executing.
	time.Sleep(2 * time.Second)
	if _, err := killConn.ExecuteFetch(fmt.Sprintf("kill %v", conn.ConnectionID), 1000, false); err != nil {
		t.Fatalf("Kill(%v) failed: %v", conn.ConnectionID, err)
	}

	// The error text will depend on what ExecuteFetch in the go
	// routine managed to do. Two cases:
	// 1. the connection was closed before the go routine's ExecuteFetch
	//   entered the ReadFull call. Then we get an error with
	//   'connection reset by peer' in it.
	// 2. the connection was closed while the go routine's ExecuteFetch
	//   was stuck on the read. Then we get io.EOF.
	// The code and sqlState needs to be right in any case, the text
	// will differ.
	err = <-errChan
	if strings.Contains(err.Error(), "EOF") {
		assertSQLError(t, err, mysql.CRServerLost, mysql.SSUnknownSQLState, "EOF", "select sleep(10) from dual")
	} else {
		assertSQLError(t, err, mysql.CRServerLost, mysql.SSUnknownSQLState, "", "connection reset by peer")
	}
}

// TestKill2006 opens a connection, kills the
// connection from the server side, then waits a bit, and tries to
// execute a command. We make sure we get the right error code.
func TestKill2006(t *testing.T) {
	ctx := context.Background()
	conn, err := mysql.Connect(ctx, &connParams)
	if err != nil {
		t.Fatal(err)
	}

	// Kill the connection from the server side.
	killConn, err := mysql.Connect(ctx, &connParams)
	if err != nil {
		t.Fatal(err)
	}
	defer killConn.Close()

	if _, err := killConn.ExecuteFetch(fmt.Sprintf("kill %v", conn.ConnectionID), 1000, false); err != nil {
		t.Fatalf("Kill(%v) failed: %v", conn.ConnectionID, err)
	}

	// Now we should get a CRServerGone.  Since we are using a
	// unix socket, we will get a broken pipe when the server
	// closes the connection and we are trying to write the command.
	_, err = conn.ExecuteFetch("select sleep(10) from dual", 1000, false)
	assertSQLError(t, err, mysql.CRServerGone, mysql.SSUnknownSQLState, "broken pipe", "select sleep(10) from dual")
}

// TestDupEntry tests a duplicate key is properly raised.
func TestDupEntry(t *testing.T) {
	ctx := context.Background()
	conn, err := mysql.Connect(ctx, &connParams)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	if _, err := conn.ExecuteFetch("create table dup_entry(id int, name int, primary key(id), unique index(name))", 0, false); err != nil {
		t.Fatalf("create table failed: %v", err)
	}
	if _, err := conn.ExecuteFetch("insert into dup_entry(id, name) values(1, 10)", 0, false); err != nil {
		t.Fatalf("first insert failed: %v", err)
	}
	_, err = conn.ExecuteFetch("insert into dup_entry(id, name) values(2, 10)", 0, false)
	assertSQLError(t, err, mysql.ERDupEntry, mysql.SSConstraintViolation, "Duplicate entry", "insert into dup_entry(id, name) values(2, 10)")
}

// TestClientFoundRows tests if the CLIENT_FOUND_ROWS flag works.
func TestClientFoundRows(t *testing.T) {
	params := connParams
	params.EnableClientFoundRows()

	ctx := context.Background()
	conn, err := mysql.Connect(ctx, &params)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	if _, err := conn.ExecuteFetch("create table found_rows(id int, val int, primary key(id))", 0, false); err != nil {
		t.Fatalf("create table failed: %v", err)
	}
	if _, err := conn.ExecuteFetch("insert into found_rows(id, val) values(1, 10)", 0, false); err != nil {
		t.Fatalf("insert failed: %v", err)
	}
	qr, err := conn.ExecuteFetch("update found_rows set val=11 where id=1", 0, false)
	require.NoError(t, err)
	assert.EqualValues(t, 1, qr.RowsAffected, "RowsAffected")

	qr, err = conn.ExecuteFetch("update found_rows set val=11 where id=1", 0, false)
	require.NoError(t, err)
	assert.EqualValues(t, 1, qr.RowsAffected, "RowsAffected")
}

func doTestMultiResult(t *testing.T, disableClientDeprecateEOF bool) {
	ctx := context.Background()
	connParams.DisableClientDeprecateEOF = disableClientDeprecateEOF

	conn, err := mysql.Connect(ctx, &connParams)
	expectNoError(t, err)
	defer conn.Close()

	qr, more, err := conn.ExecuteFetchMulti("select 1 from dual; set autocommit=1; select 1 from dual", 10, true)
	expectNoError(t, err)
	expectFlag(t, "ExecuteMultiFetch(multi result)", more, true)
	assert.EqualValues(t, 1, len(qr.Rows))

	qr, more, _, err = conn.ReadQueryResult(10, true)
	expectNoError(t, err)
	expectFlag(t, "ReadQueryResult(1)", more, true)
	assert.EqualValues(t, 0, len(qr.Rows))

	qr, more, _, err = conn.ReadQueryResult(10, true)
	expectNoError(t, err)
	expectFlag(t, "ReadQueryResult(2)", more, false)
	assert.EqualValues(t, 1, len(qr.Rows))

	qr, more, err = conn.ExecuteFetchMulti("select 1 from dual", 10, true)
	expectNoError(t, err)
	expectFlag(t, "ExecuteMultiFetch(single result)", more, false)
	assert.EqualValues(t, 1, len(qr.Rows))

	qr, more, err = conn.ExecuteFetchMulti("set autocommit=1", 10, true)
	expectNoError(t, err)
	expectFlag(t, "ExecuteMultiFetch(no result)", more, false)
	assert.EqualValues(t, 0, len(qr.Rows))

	// The ClientDeprecateEOF protocol change has a subtle twist in which an EOF or OK
	// packet happens to have the status flags in the same position if the affected_rows
	// and last_insert_id are both one byte long:
	//
	// https://dev.mysql.com/doc/internals/en/packet-EOF_Packet.html
	// https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html
	//
	// It turns out that there are no actual cases in which clients end up needing to make
	// this distinction. If either affected_rows or last_insert_id are non-zero, the protocol
	// sends an OK packet unilaterally which is properly parsed. If not, then regardless of the
	// negotiated version, it can properly send the status flags.
	//
	result, err := conn.ExecuteFetch("create table a(id int, name varchar(128), primary key(id))", 0, false)
	require.NoError(t, err)
	assert.Zero(t, result.RowsAffected, "create table RowsAffected ")

	for i := 0; i < 255; i++ {
		result, err := conn.ExecuteFetch(fmt.Sprintf("insert into a(id, name) values(%v, 'nice name %v')", 1000+i, i), 1000, true)
		require.NoError(t, err)
		assert.EqualValues(t, 1, result.RowsAffected, "insert into returned RowsAffected")
	}

	qr, more, err = conn.ExecuteFetchMulti("update a set name = concat(name, ' updated'); select * from a; select count(*) from a", 300, true)
	expectNoError(t, err)
	expectFlag(t, "ExecuteMultiFetch(multi result)", more, true)
	assert.EqualValues(t, 255, qr.RowsAffected)

	qr, more, _, err = conn.ReadQueryResult(300, true)
	expectNoError(t, err)
	expectFlag(t, "ReadQueryResult(1)", more, true)
	assert.EqualValues(t, 255, len(qr.Rows), "ReadQueryResult(1)")

	qr, more, _, err = conn.ReadQueryResult(300, true)
	expectNoError(t, err)
	expectFlag(t, "ReadQueryResult(2)", more, false)
	assert.EqualValues(t, 1, len(qr.Rows), "ReadQueryResult(1)")

	_, err = conn.ExecuteFetch("drop table a", 10, true)
	require.NoError(t, err)
}

func TestMultiResultDeprecateEOF(t *testing.T) {
	doTestMultiResult(t, false)
}
func TestMultiResultNoDeprecateEOF(t *testing.T) {
	doTestMultiResult(t, true)
}

func expectNoError(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

func expectFlag(t *testing.T, msg string, flag, want bool) {
	t.Helper()
	if flag != want {
		// We cannot continue the test if flag is incorrect.
		t.Fatalf("%s: %v, want: %v", msg, flag, want)
	}
}

// TestTLS tests our client can connect via SSL.
func TestTLS(t *testing.T) {
	params := connParams
	params.EnableSSL()

	// First make sure the official 'mysql' client can connect.
	output, ok := runMysql(t, &params, "status")
	if !ok {
		t.Fatalf("'mysql -e status' failed: %v", output)
	}
	if !strings.Contains(output, "Cipher in use is") {
		t.Fatalf("cannot connect via SSL: %v", output)
	}

	// Now connect with our client.
	ctx := context.Background()
	conn, err := mysql.Connect(ctx, &params)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	result, err := conn.ExecuteFetch("SHOW STATUS LIKE 'Ssl_cipher'", 10, true)
	if err != nil {
		t.Fatalf("SHOW STATUS LIKE 'Ssl_cipher' failed: %v", err)
	}
	if len(result.Rows) != 1 || result.Rows[0][0].ToString() != "Ssl_cipher" ||
		result.Rows[0][1].ToString() == "" {
		t.Fatalf("SHOW STATUS LIKE 'Ssl_cipher' returned unexpected result: %v", result)
	}
}

func TestReplicationStatus(t *testing.T) {
	params := connParams
	ctx := context.Background()
	conn, err := mysql.Connect(ctx, &params)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()

	status, err := conn.ShowReplicationStatus()
	if err != mysql.ErrNotReplica {
		t.Errorf("Got unexpected result for ShowReplicationStatus: %v %v", status, err)
	}
}

func TestSessionTrackGTIDs(t *testing.T) {
	ctx := context.Background()
	params := connParams
	params.Flags |= mysql.CapabilityClientSessionTrack
	conn, err := mysql.Connect(ctx, &params)
	require.NoError(t, err)

	qr, err := conn.ExecuteFetch(`set session session_track_gtids='own_gtid'`, 1000, false)
	require.NoError(t, err)
	require.Empty(t, qr.SessionStateChanges)

	qr, err = conn.ExecuteFetch(`create table vttest.t1(id bigint primary key)`, 1000, false)
	require.NoError(t, err)
	require.NotEmpty(t, qr.SessionStateChanges)

	qr, err = conn.ExecuteFetch(`insert into vttest.t1 values (1)`, 1000, false)
	require.NoError(t, err)
	require.NotEmpty(t, qr.SessionStateChanges)
}

func TestCachingSha2Password(t *testing.T) {
	ctx := context.Background()

	// connect as an existing user to create a user account with caching_sha2_password
	params := connParams
	conn, err := mysql.Connect(ctx, &params)
	expectNoError(t, err)
	defer conn.Close()

	qr, err := conn.ExecuteFetch(`select true from information_schema.PLUGINS where PLUGIN_NAME='caching_sha2_password' and PLUGIN_STATUS='ACTIVE'`, 1, false)
	if err != nil {
		t.Errorf("select true from information_schema.PLUGINS failed: %v", err)
	}

	if len(qr.Rows) != 1 {
		t.Skip("Server does not support caching_sha2_password plugin")
	}

	// create a user using caching_sha2_password password
	if _, err = conn.ExecuteFetch(`create user 'sha2user'@'localhost' identified with caching_sha2_password by 'password';`, 0, false); err != nil {
		t.Fatalf("Create user with caching_sha2_password failed: %v", err)
	}
	conn.Close()

	// connect as sha2user
	params.Uname = "sha2user"
	params.Pass = "password"
	params.DbName = "information_schema"
	conn, err = mysql.Connect(ctx, &params)
	expectNoError(t, err)
	defer conn.Close()

	if qr, err = conn.ExecuteFetch(`select user()`, 1, true); err != nil {
		t.Fatalf("select user() failed: %v", err)
	}

	if len(qr.Rows) != 1 || qr.Rows[0][0].ToString() != "sha2user@localhost" {
		t.Errorf("Logged in user is not sha2user")
	}
}


text:
<?php

namespace Rx\Observable;

use Rx\Disposable\EmptyDisposable;
use Rx\Observable;
use Rx\ObserverInterface;
use Rx\Scheduler\ImmediateScheduler;
use Rx\SchedulerInterface;

class EmptyObservable extends Observable
{

    public function subscribe(ObserverInterface $observer, SchedulerInterface $scheduler = null)
    {
        $scheduler = $scheduler?: new ImmediateScheduler();

        return $scheduler->schedule(function () use ($observer) {
            $observer->onCompleted();
        });
    }
}


text:
_[www.codever.land/bookmarks/t/url-manipulation](https://www.codever.land/bookmarks/t/url-manipulation)_
---
#### [furl](https://github.com/gruns/furl)
_https://github.com/gruns/furl_

A small Python library that makes parsing and manipulating URLs easy.
* **tags**: [python](../tagged/python.md), [url-manipulation](../tagged/url-manipulation.md)
* :octocat: **[source code](https://github.com/gruns/furl)**
---
#### [purl](https://github.com/codeinthehole/purl)
_https://github.com/codeinthehole/purl_

A simple, immutable URL class with a clean API for interrogation and manipulation.
* **tags**: [python](../tagged/python.md), [url-manipulation](../tagged/url-manipulation.md)
* :octocat: **[source code](https://github.com/codeinthehole/purl)**
---
#### [pyshorteners](https://github.com/ellisonleao/pyshorteners)
_https://github.com/ellisonleao/pyshorteners_

A pure Python URL shortening lib.
* **tags**: [python](../tagged/python.md), [url-manipulation](../tagged/url-manipulation.md)
* :octocat: **[source code](https://github.com/ellisonleao/pyshorteners)**
---
#### [webargs](https://github.com/marshmallow-code/webargs)
_https://github.com/marshmallow-code/webargs_

A friendly library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, and Pyramid.
* **tags**: [python](../tagged/python.md), [url-manipulation](../tagged/url-manipulation.md)
* :octocat: **[source code](https://github.com/marshmallow-code/webargs)**
---


text:
'use strict';

import angular from 'angular';

import uiRouter from 'angular-ui-router';

import routing from './account.routes';
import login from './login';
import settings from './settings';
import signup from './signup';

export default angular.module('bshmApp.account', [uiRouter, login, settings, signup])
  .config(routing)
  .run(function($rootScope) {
    'ngInject';

    $rootScope.$on('$stateChangeStart', function(event, next, nextParams, current) {
      if (next.name === 'logout' && current && current.name && !current.authenticate) {
        next.referrer = current.name;
      }
    });
  })
  .name;


text:
package net.collaud.fablab.api.rest.v1.model;

/**
 *
 * @author Gaetan Collaud <gaetancollaud@gmail.com> Collaud <gaetancollaud@gmail.com>
 */
public class ErrorModel extends BaseModel {

	private String developerMessage;
	private int status = 200;

	public String getDeveloperMessage() {
		return developerMessage;
	}

	public void setDeveloperMessage(String developerMessage) {
		this.developerMessage = developerMessage;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

}


text:
@interface SCVideoPlayerViewController ()

@end

@implementation SCVideoPlayerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {
        // Custom initialization
    }

    return self;
}

- (void) dealloc {
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    SCPlayer *player = self.videoPlayerView.player;
	[player setSmoothLoopItemByUrl:self.videoUrl smoothLoopCount:10];

	player.shouldLoop = YES;
	[player play];
}

- (void) viewWillAppear:(BOOL)animated {
	self.navigationController.navigationBarHidden = NO;
}

- (void) viewDidDisappear:(BOOL)animated {
	self.navigationController.navigationBarHidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
``root directory```

## Where am I ?

The API directory, controllers, models, and all your custom logic and datastructure should be contained there.

### Path:

> controllers/

> models/

> policies/

> services/

> index.js


text:
{-
    Teak synthesiser for the Balsa language
    Copyright (C) 2007-2010 The University of Manchester

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Andrew Bardsley <bardsley@cs.man.ac.uk> (and others, see AUTHORS)
    School of Computer Science, The University of Manchester
    Oxford Road, MANCHESTER, M13 9PL, UK
-}

{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}

module Main (
    main
    ) where

    import Bind
    import Context
    import Eval
    import Finish
    import Gen
    import Misc
    import NetParts
    import Gui
    import Options
    import ParseTree
    import Report
    import Print
    import Sim
    import SimTypes
    import Teak
    import Config
    import Latch
    import Plot
    import Layout
    import Balsa
    import Rule
    import Optim
    import Monitor
    import ToolOptions
    import SimPN
    import State
    import Dot

    import System.Environment
    import System.Exit
    import System.Time
    import System.FilePath
    import Data.List hiding (group)
    import System.Directory
    import Control.Monad
    import System.IO
    import System.IO.Error
    import Data.Maybe
    import Control.Monad.Trans
    import qualified Data.Map as DM
    import qualified Network

    type TeakNetwork = Network.Network

    main :: IO ()
    main = do
        args <- getArgs
        --print "renhongguang-have-fun-with-teak"
        --args <- return ["add.balsa"]
        --print args
        mainWithArgs args

    data CommandLineState = CommandLineState {
        -- Flow changing options
        clDoSimulate :: Bool,
        clDoOptimUsage :: Bool,
        clDoOptimise :: Bool,
        clDoGui :: Bool,
        clDoPlot :: Bool,
        clDoGates :: Bool,
        clDoPNTestCard :: Maybe String,
        clDoRulesTestCard :: Maybe (FilePath, String),
        -- Miscellaneous options
        clNetworkFile :: Maybe String,
        clOptimPasses :: Int,
        clReadDefaultRules :: Bool,
        clTopLevel :: Maybe String,
        clPrettyNetwork :: Bool,
        -- Flat command line
        clFlat :: String,
        -- All other options
        clOpts :: ToolOptions TeakNetwork,
        clEventFiles :: [FilePath]
        }

    defaultCommandLineState :: CommandLineState
    defaultCommandLineState = CommandLineState {
        clDoSimulate = False,
        clDoOptimUsage = False,
        clDoOptimise = False,
        clDoGui = False,
        clDoPlot = False,
        clDoGates = False,
        clDoPNTestCard = Nothing,
        clDoRulesTestCard = Nothing,
        clNetworkFile = Nothing,
        clOptimPasses = 10,
        clReadDefaultRules = False,
        clTopLevel = Nothing,
        clPrettyNetwork = False,
        clFlat = "",
        clOpts = defaultToolOptions,
        clEventFiles = []
        }

    modifyToolOptions :: CommandLineState -> (ToolOptions TeakNetwork -> ToolOptions TeakNetwork) -> CommandLineState
    modifyToolOptions state f = state { clOpts = f (clOpts state) }

    onClOpts :: (ToolOptions TeakNetwork -> [String] -> IO (ToolOptions TeakNetwork)) -> CommandLineState -> [String]
        -> IO CommandLineState
    onClOpts f state args = do
        opts' <- f (clOpts state) args
        return $ state { clOpts = opts' }

    clOptions :: CommandLineOptions CommandLineState
    clOptions = CommandLineOptions usage [
        -- General options
        CommandLineOption "verbose" 'v' [] "verbose output (for simulation, prints state changes)"
            (onClOpts $ \opts [] -> return $ opts { optVerbose = True }),
        CommandLineOption "top-level" 't' ["procedure"] "top most procedure for simulation, initial-opt"
            (\state [top] -> return $ state { clTopLevel = Just top }),
        CommandLineOption "include" 'I' ["directory"] "add <directory> to Balsa module path"
            (onClOpts $ \opts [path] -> return $ opts { optBalsaSearchPath = path:(optBalsaSearchPath opts) }),
        CommandLineOption "teak-opt" 'k' ["opt"] "component-generation sub-options"
            (onClOpts $ \opts [opt] -> do
                teakOpts' <- parseSubOptionsString teakOptionUsage teakUsage (optTeak opts) opt
                return $ opts { optTeak = teakOpts' }
                ),
        CommandLineOption "teak-usage" ' ' [] "display component-generation options usage"
            (\state [] -> teakUsage (optTeak $ clOpts state) "" >> return state),
        CommandLineOption "dump-parse-trees" ' ' [] "dump parse trees to .tree{,-bind,-eval,-finish} files"
            (onClOpts $ \opts [] -> return $ opts { optDumpParseTree = True }),
        -- Simulation
        CommandLineSeparator "",
        CommandLineOption "simulate" 'S' [] "simulate the last/top level procedure"
            (\state [] -> return $ state { clDoSimulate = True }),
        CommandLineOption "define" 'D' ["name", "value"] "bind <value> to <name> as a simulation defn."
            (onClOpts $ \opts [name, value] -> return $
                opts { optSimDefines = (name, value):(optSimDefines opts) }),
        CommandLineOption "pn-test-card" ' ' ["file"] "generate Petri net `test card' Dot file and exit"
            (\state [file] -> return $ state { clDoPNTestCard = Just file }),
        CommandLineOption "sim-opt" 's' ["opt"] "simulation sub-options"
            (onClOpts $ \opts [opt] -> do
                simOpts' <- parseSubOptionsString simOptionUsage simUsage (optSim opts) opt
                return $ opts { optSim = simOpts' }
                ),
        CommandLineOption "sim-usage" ' ' [] "display simulation sub-options usage"
            (\state [] -> simUsage (optSim $ clOpts state) "" >> return state),
        -- Network read/write
        CommandLineSeparator "",
        CommandLineOption "network-file" 'n' ["file"] "input network file name (rather than Balsa compilation)"
            (\state [file] -> return $ state { clNetworkFile = Just file }),
        CommandLineOption "output" 'o' ["file"] "output file name prefix (rather than using input file)"
            (onClOpts $ \opts [file] -> return $ opts { optBaseName = Just file }),
        CommandLineOption "pretty-network" ' ' [] "use `pretty' network format"
            (\state [] -> return $ state { clPrettyNetwork = True }),
        CommandLineSeparator "",
        -- Optimisation
        CommandLineOption "optimise" 'O' [] "optimise teak components."
            (\state [] -> return $ state { clDoOptimise = True }),
        CommandLineOption "named-opt" 'q' ["opt"]
            "apply named optimisation (`all' adds all, `none' removes all)"
            (\state [opt] -> do
                Why comp state' <- runWhyT $ do
                    state' <- readDefaultRules state
                    (otherOpts, enabledOptims) <- lift $ parseOptimSubOptions state' opt
                    return $ modifyToolOptions state' $ \opts -> opts
                        { optOptim = otherOpts, optEnabledOptims = enabledOptims }
                stop <- printCompleteness noPosContext comp
                when stop exitFailure
                return state'),
        CommandLineOption "rules" 'r' ["file"] "load (another) optimisation rules file (drops default rules)"
            (\state [file] -> do
                Why comp opts' <- runWhyT $ appendRulesFile (clOpts state) file
                stop <- printCompleteness noPosContext comp
                when stop exitFailure
                return $ state { clOpts = opts', clReadDefaultRules = True }
                ),
        CommandLineOption "rules-test-card" ' ' ["file", "sectionword"] "print rules test card"
            (\state [file, sectionWord] -> return state { clDoRulesTestCard = Just (file, sectionWord) }),
        CommandLineOption "optim-passes" ' ' ["int"] "perform this many optimisation passes"
            (\state [passes] -> return $ state { clOptimPasses = (read passes :: Int) }),
        CommandLineOption "optim-usage" ' ' [] "display optimisation usage"
            (\state [] -> do return state { clDoOptimUsage = True } ),
        -- Latching
        CommandLineSeparator "",
        CommandLineOption "latch" 'L' [] "insert latches" (onClOpts $ \opts [] ->
            return $ opts { optDoLatch = True }),
        CommandLineOption "latch-opt" 'l' ["opt"] "latch sub-options"
            (onClOpts $ \opts [opt] -> do
                latchOpts' <- parseSubOptionsString latchOptionUsage latchUsage (optLatch opts) opt
                return $ opts { optLatch = latchOpts' }
                ),
        CommandLineOption "latch-usage" ' ' [] "display latch options usage"
            (\state [] -> latchUsage (optLatch $ clOpts state) "" >> return state),
        -- Plotting
        CommandLineSeparator "",
        CommandLineOption "plot" ' ' [] "make a postscript plot of the compiled parts"
            (\state [] -> return $ state { clDoPlot = True }),
        CommandLineOption "plot-opt" 'p' ["opt"] "plot sub-options"
            (onClOpts $ \opts [opt] -> do
                plotOpts' <- parseSubOptionsString plotOptionUsage plotUsage (optPlot opts) opt
                return $ opts { optPlot = plotOpts' }),
        CommandLineOption "plot-usage" ' ' [] "display plot options usage"
            (\state [] -> plotUsage (optPlot $ clOpts state) "" >> return state),
        -- Gate-level netlisting
        CommandLineSeparator "",
        CommandLineOption "gates" ' ' [] "make a gate level netlist"
            (\state [] -> return $ state { clDoGates = True }),
        CommandLineOption "technology" 'X' ["tech"] "technology for gate level netlist"
            (onClOpts $ \opts [tech] -> return $ opts { optTech = tech }),
        CommandLineOption "test-protocol" ' ' [] "test channel protocol violations in Verilog"
            (onClOpts $ \opts [] -> return $ opts {
                optGenPartToGate = GenPartToGateProtocolTest : optGenPartToGate opts }),
        CommandLineOption "gates-usage" ' ' [] "display gates options usage"
            (\state [] -> gatesUsage state "" >> return state),
        -- Operating modes other than just compile->plot->gates
        CommandLineSeparator "",
        CommandLineOption "gui" ' ' [] "launch GUI"
            (\state [] -> return $ state { clDoGui = True }),
        CommandLineOption "gui-opt" 'g' ["opt"] "gui sub-options"
            (onClOpts $ \opts [opt] -> do
                guiOpts' <- parseSubOptionsString guiOptionUsage guiUsage (optGui opts) opt
                return $ opts { optGui = guiOpts' }),
        CommandLineOption "monitor-events" 'e' ["file"] "read monitor events file"
            (\state [file] -> return $ state { clEventFiles = file : clEventFiles state }),
        CommandLineOption "gui-usage" ' ' [] "display gui options usage"
            (\state [] -> guiUsage (optGui $ clOpts state) "" >> return state)
        ]

    header :: IO ()
    header = do
        putStrLn ""
        putStrLn "   _ _|_  _  _  |    eTeak synthesiser for the Balsa language"
        putStrLn $ "|_| |  |_| _| |/ . version: " ++ teakVersion
        putStrLn "  |_  |_ |_ |_| |\\ . (C) 2007-2016 The University of Manchester"
        putStrLn ""
        putStrLn "  This program comes with ABSOLUTELY NO WARRANTY;"
        putStrLn "  This is free software, and you are welcome to redistribute it"
        putStrLn "  under the conditions of version 3 (or greater) of the GNU GPL"
        putStrLn ""
        putStrLn "  (Graph library (C) 2002-2004 The University of Glasgow)"
        putStrLn ""

    usage :: String -> IO ()
    usage message = do
        header
        progName <- getProgName
        putStrLn $ "  usage: " ++ progName ++ " <switch>* [<file>]"
        putStrLn ""
        putStrLn "  switch:"
        putStrLn $ showOptionUsage "    " "    " clOptions
        when (message /= "") $ putStrLn $ "*** " ++ message ++ "\n"
        exitFailure

    optimsToSubOptionUsages :: [Optim TeakNetwork] -> [RuleGroup] -> SubOptionUsages (OptimOption TeakNetwork)
    optimsToSubOptionUsages optims groups = SubOptionUsages "optimisation" show (Just []) Nothing $
        (if null groups then [] else [allRule, noneRule] ++ map groupToSOU groups) ++ map optimToSOU optims
        where
            optimToSOU optim = (optimName optim, boolSubOption (optimDescription optim) (OptimOptim optim))
            groupToSOU group = (ruleGroupName group, SubOptionUsage True "" (ruleGroupDescription group)
                "" (const True) (const (map OptimOptim $ groupToOptims group, [])))

            allRule = ("all", SubOptionUsage True "" "all rules" "" (const True) (const (map OptimOptim optims, [])))
            noneRule = ("none", SubOptionUsage True "" "no rules" "" (const True) (const ([], map OptimOptim optims)))

            findOptims name
                | isJust optim = [fromJust optim]
                | isJust group = groupToOptims $ fromJust group
                | otherwise = []
                where
                    optim = find (isOptim name) optims
                    group = find ((== name) . ruleGroupName) groups

            groupToOptims group = concatMap findOptims $ ruleGroupMembers group

    optimiseUsage :: RuleSet TeakNetwork -> [Optim TeakNetwork] -> [OptimOption TeakNetwork] -> String -> IO ()
    optimiseUsage ruleSet allOptims opts message = do
        header
        let groups = ruleSetGroups ruleSet
        when (not (null groups)) $ do
            putStrLn "  Option group abbreviations\n"
            let
                names = map makeName groups
                descs = map (\group -> ruleGroupDescription group
                    ++ " (" ++ joinWith "," (ruleGroupMembers group) ++ ")") groups

                makeName group = (if optimOn then "   " else "no-") ++ ruleGroupName group
                    where optimOn = all (\name -> isJust (find (isOptimName name) opts)) $
                            ruleGroupMembers group

                isOptimName name (OptimOptim optim) = optimName optim == name
                isOptimName _ _ = False

            mapM_ putStrLn $ columnFormat ["   all":"   none":names, "all rules":"no rules":descs]
                ["  ", " -- "] ["  ", "    "]
        putStrLn ""
        subOptionsUsage (appendSubOptionUsages optimOptionUsage (optimsToSubOptionUsages allOptims []))
            opts "-q" message
        exitFailure

    plotUsage :: [PlotOption] -> String -> IO ()
    plotUsage opts message = do
        header
        subOptionsUsage plotOptionUsage opts "-p" message
        exitFailure

    guiUsage :: [GuiOption] -> String -> IO ()
    guiUsage opts message = do
        header
        subOptionsUsage guiOptionUsage opts "-g" message
        exitFailure

    latchUsage :: [LatchOption] -> String -> IO ()
    latchUsage opts message = do
        header
        subOptionsUsage latchOptionUsage opts "-l" message
        exitFailure

    teakUsage :: [TeakOption] -> String -> IO ()
    teakUsage opts message = do
        header
        subOptionsUsage teakOptionUsage opts "-k" message
        exitFailure

    simUsage :: [SimOption] -> String -> IO ()
    simUsage opts message = do
        header
        subOptionsUsage simOptionUsage opts "-s" message
        exitFailure

    gatesUsage :: CommandLineState -> String -> IO ()
    gatesUsage state _message = do
        header
        techs <- teakFindTechs $ clOpts state
        putStrLn $ "  Available technologies: " ++ joinWith ", " techs
        putStrLn ""
        exitFailure

    readDefaultRules :: CommandLineState -> WhyT IO CommandLineState
    readDefaultRules state = do
        optimPath <- lift $ teakOptimPath
        let defaultRulesFile = optimPath </> "default" <.> "rules"
        if not (clReadDefaultRules state)
            then do
                opts' <- appendRulesFile (clOpts state) defaultRulesFile
                return $ state { clReadDefaultRules = True, clOpts = opts' }
            else return state

    readDefaultRulesIO :: CommandLineState -> IO CommandLineState
    readDefaultRulesIO state = do
        Why comp state' <- runWhyT $ readDefaultRules state
        stop <- printCompleteness noPosContext comp
        when stop exitFailure
        return state'

    appendRulesFile :: ToolOptions TeakNetwork -> FilePath -> WhyT IO (ToolOptions TeakNetwork)
    appendRulesFile opts file = do
        ruleSet <- readRulesFile (optVerbose opts) file
        let
            rules' = concatRuleSets [ruleSet, optRules opts]
            optims = map ruleToOptim $ ruleSetRules rules'

        return $ opts { optRules = rules',
            optEnabledOptims = optEnabledOptims opts ++ filter optimOnByDefault optims,
            optAllOptims = optAllOptims opts ++ optims
            }

    readRulesFile :: Bool -> String -> WhyT IO (RuleSet TeakNetwork)
    readRulesFile verbose file = do
        exists <- lift $ doesFileExist file
        if exists
            then do
                contents <- lift $ readFile file
                let comp@(Why _ ruleSet) = parseRules (PosLC (PosFile file (ImportFile file)) 1 1) contents
                when verbose $ lift $ putStrLn $ "*** read " ++ summariseRuleSet ruleSet (" from file " ++ file)
                {-
                lift $ mapM (\rule -> do
                    print $ ruleName rule
                    mapM_ print $ ruleFromPatternLinks rule
                    -- mapM_ print $ ruleFromLeadsTos rule
                    print "From"
                    mapM_ (\comp -> do
                        print $ compPatternName comp
                        mapM_ print $ compPatternPortPatterns comp
                        ) $ ruleFrom rule
                    print "To"
                    mapM print $ ruleTo rule
                    ) $ ruleSetRules ruleSet
                    -}
                WhyT $ return comp
            else failPos PosTopLevel $ "can't open optimisation rules file `" ++ file ++ "'"

    parseOptimSubOptions :: CommandLineState -> String -> IO ([OptimOption TeakNetwork], [Optim TeakNetwork])
    parseOptimSubOptions state optString = do
        subOpts <- parseSubOptionsString
            (appendSubOptionUsages optimOptionUsage
                (optimsToSubOptionUsages (optAllOptims opts) (ruleSetGroups (optRules opts))))
            (optimiseUsage (optRules opts) (optAllOptims opts))
            (optOptim opts ++ (map OptimOptim (optEnabledOptims opts)))
            optString
        return $ separateOptimOptions subOpts
        where opts = clOpts state

    mainWithArgs :: [String] -> IO ()
    mainWithArgs args = do
        teakLibrary <- teakLibraryPath
        let state0 = modifyToolOptions defaultCommandLineState $ setTeakHome teakLibrary
        (stateWithoutFlat, remainingArgs) <- parseOptions clOptions state0 args

        let
            flatArgs = joinWith " " args
            state = stateWithoutFlat { clFlat = flatArgs }

        when (isJust $ clDoPNTestCard state) $ do
            pnTestCard $ fromJust $ clDoPNTestCard state
            exitWith ExitSuccess

        when (clDoGui state && clDoSimulate state) $
            usage "Don't use --simulate and --gui together"

        when (clDoGui state && (clDoGates state || clDoPlot state)) $
            usage "Don't use --plot, --gate, --simulate with --gui"

        when (clDoSimulate state && (clDoGates state || clDoPlot state)) $
            usage "Don't use --plot, --gate, with --simulate"

        when (isJust $ clDoRulesTestCard state) $ do
            state' <- readDefaultRulesIO state
            let Just (file, sectionWord) = clDoRulesTestCard state'
            rulesTestCard (optRules $ clOpts state') file sectionWord
            exitWith ExitSuccess

        when (clDoOptimUsage state) $ do
            state' <- readDefaultRulesIO state
            optimiseUsage (optRules $ clOpts state')
                (optAllOptims $ clOpts state')
                (optOptim (clOpts state') ++ (map OptimOptim (optEnabledOptims $ clOpts state'))) ""

        compileFlow state remainingArgs

    putTimeStamped :: String -> IO ()
    putTimeStamped str = do
        time <- getClockTime
        putStrLn $ show time ++ ": " ++ str

    compileFlow :: CommandLineState -> [String] -> IO ()
    compileFlow state remainingArgs = do
        let
            searchPath = optBalsaSearchPath $ clOpts state
            networkFile = clNetworkFile state
            verbose = optVerbose $ clOpts state

            putVerboseObj Nothing str = putVerbose str
            putVerboseObj (Just obj) str = when verbose $ do
                let len = show $ length $ show obj
                putStr $ "*** (" ++ len ++ ") "
                putTimeStamped str

            putVerbose str = when verbose $ do
                putStr $ "*** "
                putTimeStamped str

        (contextUnbound, state') <- case remainingArgs of
            [] | clDoGui state -> return (emptyContext, state)
            [] | isJust networkFile -> return (emptyContext, state)
            [inputFile]
                | isNothing networkFile && isSuffixOf ".teak" inputFile -> do
                    -- Use this as the input network.  Don't set base name
                    return (emptyContext, state { clNetworkFile = Just inputFile })
                | isNothing networkFile -> do
                    let baseFilename = fromMaybe (dropSuffix ".balsa" inputFile) $ optBaseName $ clOpts state
                    Why r balsaContext <- runWhyT $ parseBalsaFile searchPath inputFile
                    putVerboseObj (Just balsaContext) "Parsed Balsa input (if any)"
                    stop <- printCompleteness (Just balsaContext) r
                    when stop exitFailure
                    return (balsaContext, state {
                        clOpts = (clOpts state) { optBaseName = Just baseFilename } })
            _ -> do
                usage "pass exactly one <file> argument, or a network file, or use --gui"
                return (emptyContext, state)

        when (optDumpParseTree (clOpts state') && isNothing (optBaseName (clOpts state'))) $
            usage "Must have a base filename (use -o) to dump parse trees"

        contextFinish <- do
            let
                Why bindingR contextBound = bind contextUnbound
                Why evalR contextEval = evalContext contextBound
                contextFinish = finish contextEval

                dumpParseTree = optDumpParseTree $ clOpts state'

                treeFilename = fromJust (optBaseName (clOpts state')) <.> "tree"

                writeTree suffix context = do
                    treeFile <- openFile (treeFilename ++ suffix) WriteMode
                    hPutStrLn treeFile $ showTree context
                    hClose treeFile

            when dumpParseTree $ writeTree "-parse" contextUnbound

            bindingStop <- printCompleteness (Just contextBound) bindingR
            when bindingStop exitFailure

            when dumpParseTree $ do
                writeTree "-bind" contextBound
                writeTree "-eval" contextEval

            evalStop <- printCompleteness (Just contextEval) evalR
            when evalStop exitFailure

            when dumpParseTree $ writeTree "-finish" contextFinish

            return contextFinish

        putVerboseObj (Just contextFinish) "Finished elaboration"

        let
            SimType simType = getSubOption (optSim $ clOpts state') $ SimType SimTypeLanguage

        if clDoSimulate state' && simType == SimTypeLanguage
            then simulateFlow state' contextFinish
            -- Actually committing to Teak network/gates
            else do
                state'' <- readDefaultRulesIO state'
                backendFlow state'' verbose putVerbose putVerboseObj contextFinish

    simulateFlow :: CommandLineState -> Context Decl -> IO ()
    simulateFlow state context = do
        let
            maybeTopLevelName = clTopLevel state
            Just topLevelName = maybeTopLevelName
            maybeRef = findRefByName [context] ProcNamespace topLevelName

        let maybeSimWritePN = findSubOption (optSim $ clOpts state) $ SimWritePN ""
        when (isJust maybeSimWritePN) $ putStrLn $
            "*** Can't output a Petri net, wrong simulation type, use -s type=pn"

        maybeBinding <- if isJust maybeTopLevelName
            then if isJust maybeRef
                then return $ Just $ findBindingByRef [context] $ fromJust maybeRef
                else do
                    usage $ "No procedure `" ++ topLevelName ++ "' to simulate"
                    return Nothing
            else if isEmptyContext context
                then do
                    usage "No top-level procedures to simulate"
                    return Nothing
                else return $ Just $ findBindingByRef [context] $ Ref $ contextsLastIndex [context]

        when (isJust maybeBinding && findBoolSubOption (optSim $ clOpts state) SimSimulate) $ do
            let Just binding = maybeBinding
            putStrLn $ "*** Simulating BEGIN: " ++ bindingName binding
            simulate (optSimDefines $ clOpts state) (optSim $ clOpts state) context binding
            putStrLn $ "*** Simulating END " ++ bindingName binding

    -- backendFlow : things to do with parse trees to generate reports, Teak component implementations
    backendFlow :: CommandLineState -> Bool -> (String -> IO ()) ->
        (Maybe [Part TeakNetwork] -> String -> IO ()) -> Context Decl -> IO ()
    backendFlow state verbose putVerbose putVerboseObj context = do
        let networkFile = clNetworkFile state

        Why compileComp compiledParts <- if isJust networkFile
            then do
                Why comp readParts <- runWhyT $ readNetworkFile (fromJust networkFile)
                stop <- printCompleteness noPosContext comp
                when stop exitFailure
                return $ Why Complete (readParts :: [Part TeakNetwork])
            else return $ teak (optTeak $ clOpts state) context
        stop <- printCompleteness (Just context) compileComp
        when stop exitFailure

        putVerboseObj (Just compiledParts) "Finished compilation/reading network"

        finalParts <- do
            let
                maybeTopLevelName = clTopLevel state
                topLevelName = fromJust maybeTopLevelName

                unaliasedParts = map ((flip runPart_) networkRemoveAliases) compiledParts

            when (isJust maybeTopLevelName && isNothing (nwFindPart unaliasedParts topLevelName)) $
                usage $ "can't find top-level: `" ++ topLevelName ++ "'"

            uniqueParts <- if isJust maybeTopLevelName
                then do
                    let uniqueParts = uniquifyPart unaliasedParts topLevelName
                    hFlush stdout
                    return $ removeGo uniqueParts topLevelName
                else return unaliasedParts

            let
                optimisePart :: [Part TeakNetwork] -> Part TeakNetwork -> IO (Part TeakNetwork)
                optimisePart parts part = do
                    -- FIXME, make localOptims stuff a part of Balsa.hs
                    optimisations <- case localOptims of
                        Just (TeakParamString str) -> liftM snd $ parseOptimSubOptions state str
                        Nothing -> return $ optEnabledOptims $ clOpts state
                        _ -> do
                            optUsage "bad parameter type, must be string"
                            return $ optEnabledOptims $ clOpts state
                    let
                        optimContext = OptimContext { optimContextParts = parts }

                        optimLog _part comp optim = putStrLn $
                            (show (refComp comp)) ++ " " ++ optimName optim

                        optRun partIn runNo = do
                            putVerboseObj (Just [partIn]) $ "Run " ++ show runNo
                            Why comp partOut <- runWhyT $ applyOptims optimisations optimContext partIn
                                (if verbose && findBoolSubOption (optOptim $ clOpts state) OptimVerbose
                                    then optimLog
                                    else noOptimLog)
                            stop <- printCompleteness noPosContext comp
                            when stop exitFailure
                            return partOut
                    putVerbose $ "Optimising part " ++ networkName part
                    part' <- foldM optRun part [1..clOptimPasses state]
                    putVerboseObj (Just [part']) $ "Optimised " ++ networkName part
                    return part'
                    where
                        localOptims = tryPart part $ nwGetAttributeVal "optim"

                        optUsage msg = putStrLn $ "*** in part `" ++ networkName part ++
                            "' " ++ msg

                optimisePartsElem parts (i, part) = do
                    part' <- optimisePart parts part
                    return $ replaceAt parts i part'

            optimisedParts <- if clDoOptimise state
                then do
                    untrimmedOptimisedParts <- foldM optimisePartsElem uniqueParts $ zip [0..] uniqueParts
                    -- remove unused parts
                    return $ if isJust maybeTopLevelName
                        then uniquifyPart untrimmedOptimisedParts topLevelName
                        else untrimmedOptimisedParts
                else return uniqueParts

            putVerboseObj (Just optimisedParts) "Finished optimisation "

            finalParts <- if not (optDoLatch (clOpts state))
                then return optimisedParts
                else do
                    let
                        latchOpts = optLatch $ clOpts state

                        Why comp latchedParts = gatherFail $ map
                            (\part -> runWhyTPart_ part $ nwInsertLatches latchOpts) optimisedParts

                    exit <- printCompleteness noPosContext comp
                    when exit exitFailure

                    let
                        doscp = (findBoolSubOption latchOpts LatchDoSCP) -- || findBoolSubOption latchOpts (LatchSCPLimit 3000)
                    return latchedParts
{-

                    putVerboseObj (Just latchedParts) "Finished latch insertion"
                    print latchOpts
                    print $ findBoolSubOption latchOpts LatchDoSCP
                    print $ findBoolSubOption latchOpts (LatchSCPLimit 3000)
                    print $ findSubOption latchOpts (LatchSCPLimit undefined)
                    return latchedParts
-}
            return finalParts

        putVerboseObj (Just finalParts) "Checking networks"

        do -- check
            let comp = gatherCompleteness $ map checkPart finalParts
            _exit <- printCompleteness noPosContext comp
            -- exitFailure
            return ()

        putVerboseObj (Just finalParts) "Finished generating networks"

        if clDoGui state
            then do
                -- Read event files first
                let
                    readEventFile :: FilePath -> IO PartMonitorEvents
                    readEventFile file = do
                        Why comp events <- runWhyT $ readMonitorFile finalParts file
                        stop <- printCompleteness noPosContext comp
                        when stop exitFailure
                        return events

                events <- case clEventFiles state of
                    [] -> return []
                    [file] -> readEventFile file
                    _ -> do
                        usage "more than one monitor events file given"
                        return []

                let opts = (clOpts state) { optPartMonitorEvents = events }
                gui opts finalParts
                return ()
            else backend2 state verbose putVerbose finalParts

    backend2 :: CommandLineState -> Bool -> (String -> IO ()) -> [Part TeakNetwork] -> IO ()
    backend2 state verbose putVerbose partsIn = do
        let
            baseFilename = optBaseName $ clOpts state

            writeTeak parts = do
                let teakFilename = fromJust baseFilename ++ ".teak"
                if isNothing baseFilename
                    then putVerbose "Must have a base filename (use -o) to write network files, skipping"
                    else do
                        putVerbose $ "Writing Teak network file " ++ teakFilename
                        writeNetworkFile (clPrettyNetwork state) (clFlat state) teakFilename parts
                        putVerbose $ "Finished writing Teak network file"

        writeTeak partsIn

        when (clDoGates state) $ do
            when (isNothing baseFilename) $ usage "Must have a base filename (use -o) to write gate netlists"
            progName <- getProgName
            Why comp techMapping <- runWhyT $
                teakFindTechMapping (clOpts state) (optTech $ clOpts state)
            case comp of
                Complete -> genMakeGatesFile verbose (optGenPartToGate $ clOpts state)
                    ("from command: " ++ progName ++ " " ++ clFlat state)
                    techMapping -- (optTech $ clOpts state)
                    (fromJust baseFilename ++ ".v")
                    partsIn
                _ -> do
                    stop <- printCompleteness noPosContext comp
                    when stop exitFailure

        when (clDoPlot state) $ do
            let
                plotOpts = optPlot $ clOpts state
                trimmedParts = map (trimPartForPartialPlot plotOpts) partsIn
            plotParts (fromJust baseFilename) True plotOpts verbose
                (\opts part -> partGraphicalInfo False opts (networkName part) part)
                Nothing
                trimmedParts

        let SimType simType = getSubOption (optSim $ clOpts state) $ SimType SimTypeLanguage
        when (clDoSimulate state && simType == SimTypePN) $ do
            putVerbose "Petri net simulation"
            let
                maybeTopLevelName = clTopLevel state
                Just topLevelName = maybeTopLevelName
                maybeTopLevelPart = nwFindPart partsIn topLevelName

            Just part <- if isJust maybeTopLevelName
                then if isJust maybeTopLevelPart
                    then return maybeTopLevelPart
                    else do
                        usage $ "No procedure `" ++ topLevelName ++ "' to simulate"
                        return Nothing
                else if null partsIn
                    then do
                        usage "No top-level procedures to simulate"
                        return Nothing
                    else return $ Just $ last partsIn

            let SimWriteEvents logFilename = getSubOption (optSim $ clOpts state) $ SimWriteEvents "/dev/null"
            logFile <- openFile logFilename WriteMode

            let
                pn = makeTopLevelPartPN partsIn part
                setTime = simFlowSet TimeRef . TimeState

                initState = [[(TimeRef, TimeState 0),
                    (DefinesRef, DefinesState $ optSimDefines $ clOpts state),
                    (LogFileRef, FileState logFile)]]

                isNonEmptyMarking (_, marking) = length marking /= 0

                simTimeRange = [0..200000]

                maybeSimWritePN = findSubOption (optSim $ clOpts state) $ SimWritePN ""
                SimWritePNFormat format = getSubOption (optSim $ clOpts state) $ SimWritePNFormat SimWritePNDot

            when (isJust maybeSimWritePN) $ do
                putVerbose "Writing Petri net file"
                let Just (SimWritePN file) = maybeSimWritePN
                case format of
                    SimWritePNDot -> writeGraphsToFile file [
                        -- dotGraphGroupNodesByLabel (Just 1) [] $
                        pnToDot Nothing (networkName part) pn]
                    SimWritePNHLNet -> writeHLNet file (networkName part) pn
                putVerbose "Finished writing Petri net file"

            when (findBoolSubOption (optSim $ clOpts state) SimSimulate) $ do
                let otherPorts = filter (fromMaybe False . liftM (`notElem` [GoAccess, DoneAccess]) . nwPortRef) $
                      networkPorts part
                when (not (null otherPorts)) $ usage "Top-level part must have no ports"

                let marking0 = pnInitialMarking pn
                (marking', _) <- runStateT (runPN setTime pn marking0 simTimeRange) initState
                hClose logFile

                mapM_ (putStrLn . (\placeMarking -> showMarkingElem pn placeMarking "")) $
                    filter isNonEmptyMarking $ DM.assocs marking'


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>DeployQt4 — CMake 3.7.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="top" title="CMake 3.7.2 Documentation" href="../index.html" />
    <link rel="up" title="cmake-modules(7)" href="../manual/cmake-modules.7.html" />
    <link rel="next" title="Documentation" href="Documentation.html" />
    <link rel="prev" title="Dart" href="Dart.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.7.2 Documentation »

cmake-modules(7) »

DeployQt4¶

Functions to help assemble a standalone Qt4 executable.

A collection of CMake utility functions useful for deploying Qt4
executables.

The following functions are provided by this module:

write_qt4_conf
resolve_qt4_paths
fixup_qt4_executable
install_qt4_plugin_path
install_qt4_plugin
install_qt4_executable

Requires CMake 2.6 or greater because it uses function and
PARENT_SCOPE.  Also depends on BundleUtilities.cmake.

WRITE_QT4_CONF(<qt_conf_dir> <qt_conf_contents>)

Writes a qt.conf file with the <qt_conf_contents> into <qt_conf_dir>.

RESOLVE_QT4_PATHS(<paths_var> [<executable_path>])

Loop through <paths_var> list and if any don’t exist resolve them
relative to the <executable_path> (if supplied) or the
CMAKE_INSTALL_PREFIX.

FIXUP_QT4_EXECUTABLE(<executable>
  [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf>])

Copies Qt plugins, writes a Qt configuration file (if needed) and
fixes up a Qt4 executable using BundleUtilities so it is standalone
and can be drag-and-drop copied to another machine as long as all of
the system libraries are compatible.

<executable> should point to the executable to be fixed-up.

<qtplugins> should contain a list of the names or paths of any Qt
plugins to be installed.

<libs> will be passed to BundleUtilities and should be a list of any
already installed plugins, libraries or executables to also be
fixed-up.

<dirs> will be passed to BundleUtilities and should contain and
directories to be searched to find library dependencies.

<plugins_dir> allows an custom plugins directory to be used.

<request_qt_conf> will force a qt.conf file to be written even if not
needed.

INSTALL_QT4_PLUGIN_PATH(plugin executable copy installed_plugin_path_var
                        <plugins_dir> <component> <configurations>)

Install (or copy) a resolved <plugin> to the default plugins directory
(or <plugins_dir>) relative to <executable> and store the result in
<installed_plugin_path_var>.

If <copy> is set to TRUE then the plugins will be copied rather than
installed.  This is to allow this module to be used at CMake time
rather than install time.

If <component> is set then anything installed will use this COMPONENT.

INSTALL_QT4_PLUGIN(plugin executable copy installed_plugin_path_var
                   <plugins_dir> <component>)

Install (or copy) an unresolved <plugin> to the default plugins
directory (or <plugins_dir>) relative to <executable> and store the
result in <installed_plugin_path_var>.  See documentation of
INSTALL_QT4_PLUGIN_PATH.

INSTALL_QT4_EXECUTABLE(<executable>
  [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf> <component>])

Installs Qt plugins, writes a Qt configuration file (if needed) and
fixes up a Qt4 executable using BundleUtilities so it is standalone
and can be drag-and-drop copied to another machine as long as all of
the system libraries are compatible.  The executable will be fixed-up
at install time.  <component> is the COMPONENT used for bundle fixup
and plugin installation.  See documentation of FIXUP_QT4_BUNDLE.

Previous topic

Dart

Next topic

Documentation

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

    CMake »

    3.7.2 Documentation »

cmake-modules(7) »

        © Copyright 2000-2016 Kitware, Inc. and Contributors.
      Created using Sphinx 1.4a0+.