text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

describe "Module#append_features" do
  it "is a private method" do
    Module.should have_private_instance_method(:append_features)
  end

  describe "on Class" do
    it "is undefined" do
      Class.should_not have_private_instance_method(:append_features, true)
    end

    it "raises a TypeError if calling after rebinded to Class" do
      lambda {
        Module.instance_method(:append_features).bind(Class.new).call Module.new
      }.should raise_error(TypeError)
    end
  end

  it "gets called when self is included in another module/class" do
    begin
      m = Module.new do
        def self.append_features(mod)
          $appended_to = mod
        end
      end

      c = Class.new do
        include m
      end

      $appended_to.should == c
    ensure
      $appended_to = nil
    end
  end

  it "raises an ArgumentError on a cyclic include" do
    lambda {
      ModuleSpecs::CyclicAppendA.send(:append_features, ModuleSpecs::CyclicAppendA)
    }.should raise_error(ArgumentError)

    lambda {
      ModuleSpecs::CyclicAppendB.send(:append_features, ModuleSpecs::CyclicAppendA)
    }.should raise_error(ArgumentError)

  end

  it "copies own tainted status to the given module" do
    other = Module.new
    Module.new.taint.send :append_features, other
    other.tainted?.should be_true
  end

  ruby_version_is "1.9" do
    it "copies own untrusted status to the given module" do
      other = Module.new
      Module.new.untrust.send :append_features, other
      other.untrusted?.should be_true
    end
  end

  describe "when other is frozen" do
    before :each do
      @receiver = Module.new
      @other = Module.new.freeze
    end

    ruby_version_is ""..."1.9" do
      it "raises a TypeError before appending self" do
        lambda { @receiver.send(:append_features, @other) }.should raise_error(TypeError)
        @other.ancestors.should_not include(@receiver)
      end
    end

    ruby_version_is "1.9" do
      it "raises a RuntimeError before appending self" do
        lambda { @receiver.send(:append_features, @other) }.should raise_error(RuntimeError)
        @other.ancestors.should_not include(@receiver)
      end
    end
  end
end


text:
/**
* Handles the cookie used by several JavaScript functions
*
* Only a single cookie is written and read. You may only save
* simple name-value pairs - no complex types!
*
* You should only use the getValue and setValue methods
*
* @author Andreas Gohr <andi@splitbrain.org>
* @author Michal Rezler <m.rezler@centrum.cz>
*/
var DokuCookie = {
    data: {},
    name: 'DOKU_PREFS',

    /**
     * Save a value to the cookie
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     */
    setValue: function(key,val){
        var text = [],
            _this = this;
        this.init();
        this.data[key] = val;

        //save the whole data array
        jQuery.each(_this.data, function (key, val) {
            if (_this.data.hasOwnProperty(key)) {
                text.push(encodeURIComponent(key)+'#'+encodeURIComponent(val));
            }
        });
        jQuery.cookie(this.name, text.join('#'), {expires: 365, path: DOKU_COOKIE_PARAM.path, secure: DOKU_COOKIE_PARAM.secure});
    },

    /**
     * Get a Value from the Cookie
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     */
    getValue: function(key){
        this.init();
        return this.data[key];
    },

    /**
     * Loads the current set cookie
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     */
    init: function(){
        var text, parts, i;
        if(!jQuery.isEmptyObject(this.data)) {
            return;
        }
        text = jQuery.cookie(this.name);
        if(text){
            parts = text.split('#');
            for(i = 0; i < parts.length; i += 2){
                this.data[decodeURIComponent(parts[i])] = decodeURIComponent(parts[i+1]);
            }
        }
    }
};

redpajama_set_name: RedPajamaGithub


text:
require "simplecov"
SimpleCov.start

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'active_model'

require 'csv_importer'

RSpec.configure do |c|
  c.example_status_persistence_file_path = "./spec/examples.txt"
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

<input type="text" id="input1"/>


text:
package client

import (
	"bytes"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"sort"
	"strings"
	"time"
)

var (
	BaseURL                 = "https://api.sailthru.com"
	HTTPClientTimeout       = 120 * time.Second
	HTTPDialerTimeout       = 10 * time.Second
	HTTPTLSHandshakeTimeout = 10 * time.Second
)

var transport = &http.Transport{
	Dial: (&net.Dialer{
		Timeout: HTTPDialerTimeout,
	}).Dial,
	TLSHandshakeTimeout: HTTPTLSHandshakeTimeout,
}

type Client struct {
	key        string
	secret     string
	HTTPClient *http.Client
}

func NewClient(key, secret string) *Client {
	return &Client{
		key:    key,
		secret: secret,
		HTTPClient: &http.Client{
			Timeout:   HTTPClientTimeout,
			Transport: transport,
		},
	}
}

func (c *Client) Get(endpoint string, obj interface{}) (Response, error) {
	values, err := c.formValues(obj)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%v/%v?%v", BaseURL, endpoint, values.Encode())
	r, _ := http.NewRequest("GET", url, nil)
	return c.request(r)
}

func (c *Client) Post(endpoint string, obj interface{}) (Response, error) {
	values, err := c.formValues(obj)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%v/%v", BaseURL, endpoint)
	r, _ := http.NewRequest("POST", url, bytes.NewBufferString(values.Encode()))
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	return c.request(r)
}

func (c *Client) Delete(endpoint string, obj interface{}) (Response, error) {
	values, err := c.formValues(obj)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%v/%v?%v", BaseURL, endpoint, values.Encode())
	r, _ := http.NewRequest("DELETE", url, nil)
	return c.request(r)
}

func (c *Client) signature(params string) string {
	values := []string{
		c.key,
		"json",
		params,
	}
	sort.Strings(values)
	values = append([]string{c.secret}, values...)

	signature := fmt.Sprintf("%x", md5.Sum([]byte(strings.Join(values, ""))))
	return signature
}

func (c *Client) formValues(obj interface{}) (url.Values, error) {
	dd, err := json.Marshal(obj)
	if err != nil {
		return url.Values{}, err
	}

	params := string(dd)

	formData := url.Values{}
	formData.Set("api_key", c.key)
	formData.Add("sig", c.signature(params))
	formData.Add("format", "json")
	formData.Add("json", params)

	return formData, nil
}

func (c *Client) request(r *http.Request) (Response, error) {
	httpRes, err := c.HTTPClient.Do(r)

	if err != nil {
		return nil, err
	}

	defer httpRes.Body.Close()

	if httpRes.StatusCode != http.StatusOK {
		return nil, fmt.Errorf(httpRes.Status)
	}

	decoder := json.NewDecoder(httpRes.Body)

	response := &JSONResponse{}
	if err := decoder.Decode(&response); err != nil && err != io.EOF {
		return nil, err
	}

	return response, nil
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: chrishao
 * Date: 16-11-19
 * Time: 下午7:27
 */

defined('DS') or define('DS', DIRECTORY_SEPARATOR);
defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . DS);
defined('ROOT_PATH') or define('ROOT_PATH', dirname(realpath(APP_PATH)) . DS);


text:
package org.apache.sling.extensions.leakdetector.internal;

import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.Constants;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.util.tracker.BundleTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LeakDetector implements Runnable, BundleActivator {
    /**
     * Set of PhantomReferences such that PhantomReference itself is not GC.
     * While analyzing the Heap Dump it might appear that GC roots of such classloaders (suspected)
     * points to LeakDetector. This happens because they are held here through PhantomReference
     * and there normal GC has not been done. So consider that as false positive
     */
    private final Set<Reference<?>> refs = Collections.synchronizedSet(new HashSet<Reference<?>>());

    /**
     * Lock to control concurrent access to internal data structures
     */
    private final Object leakDetectorLock = new Object();

    private final ReferenceQueue<ClassLoader> queue = new ReferenceQueue<ClassLoader>();

    private final ConcurrentMap<Long, BundleInfo> bundleInfos = new ConcurrentHashMap<Long, BundleInfo>();

    private final Logger log = LoggerFactory.getLogger(getClass());

    private Thread referencePoller;

    private BundleContext context;

    private BundleTracker bundleTracker;

    public void start(BundleContext context) {
        this.context = context;
        this.bundleTracker = new LeakDetectorBundleTracker(context);

        referencePoller = new Thread(this, "Bundle Leak Detector Thread");
        referencePoller.setDaemon(true);
        referencePoller.start();

        Dictionary<String,Object> printerProps = new Hashtable<String, Object>();
        printerProps.put(Constants.SERVICE_VENDOR, "Apache Software Foundation");
        printerProps.put(Constants.SERVICE_DESCRIPTION, "Sling Log Configuration Printer");
        printerProps.put("felix.webconsole.label", "leakdetector");
        printerProps.put("felix.webconsole.title", "Classloader Leak Detector");
        printerProps.put("felix.webconsole.configprinter.modes", "always");

        context.registerService(LeakDetector.class.getName(), this, printerProps);
    }

    public void stop(BundleContext context) {
        this.bundleTracker.close();
        referencePoller.interrupt();
    }

    private class LeakDetectorBundleTracker extends BundleTracker {
        public LeakDetectorBundleTracker(BundleContext context) {
            //Only listen for started
            super(context, Bundle.ACTIVE, null);
            this.open();
        }

        @Override
        public Object addingBundle(Bundle bundle, BundleEvent event) {
            synchronized (leakDetectorLock) {
                registerBundle(bundle);
            }
            return bundle;
        }
    }

    private void registerBundle(Bundle bundle) {
        ClassLoader cl = getClassloader(bundle);
        //cl would be null for Fragment bundle
        if (cl != null) {
            BundleReference ref = new BundleReference(bundle, cl);
            refs.add(ref);

            //Note that a bundle can be started multiple times
            //for e.g. when refreshed So we need to account for that also
            BundleInfo bi = bundleInfos.get(bundle.getBundleId());
            if (bi == null) {
                bi = new BundleInfo(bundle);
                bundleInfos.put(bundle.getBundleId(), bi);
            }
            bi.incrementUsageCount(ref);
            log.info("Registered bundle [{}] with Classloader [{}]", bi, ref.classloaderInfo);
        }
    }

    //~----------------------------------------<GC Callback>

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                BundleReference ref = (BundleReference) queue.remove();
                if (ref != null) {
                    removeBundle(ref);
                }
            } catch (InterruptedException e) {
                break;
            }
        }

        log.info("Shutting down reference collector for Classloader LeakDetector");
        //Drain out the queue
        BundleReference ref = null;
        while ((ref = (BundleReference)queue.poll()) != null){
            removeBundle(ref);
        }
    }

    private void removeBundle(BundleReference ref) {
        BundleInfo bi = bundleInfos.get(ref.bundleId);

        synchronized (leakDetectorLock){
            //bi cannot be null
            bi.decrementUsageCount(ref);
            refs.remove(ref);
            ref.clear();
        }

        log.info("Detected garbage collection of bundle [{}] - Classloader [{}]", bi, ref.classloaderInfo);
    }

    //~---------------------------------------<Configuration Printer>

    /**
     * @see org.apache.felix.webconsole.ConfigurationPrinter#printConfiguration(java.io.PrintWriter)
     */
    @SuppressWarnings("UnusedDeclaration")
    public void printConfiguration(PrintWriter pw) {
        //Try to force GC
        //TODO Should we do by default or let user do it explicitly via
        //Felix Web Console
        //System.gc();

        Set<Long> activeBundleIds = new HashSet<Long>();
        for (Bundle b : context.getBundles()) {
            activeBundleIds.add(b.getBundleId());
        }

        List<BundleInfo> suspiciousBundles = new ArrayList<BundleInfo>(bundleInfos.values());
        Iterator<BundleInfo> itr = suspiciousBundles.iterator();
        while (itr.hasNext()) {
            BundleInfo bi = itr.next();

            //Filter out bundles which are active and have
            //only one classloader created for them
            if (bi.hasSingleInstance()
                    && activeBundleIds.contains(bi.bundleId)) {
                itr.remove();
            }
        }

        if (suspiciousBundles.isEmpty()) {
            pw.println("No classloader leak detected");
        } else {
            pw.println("Possible classloader leak detected");
            pw.printf("Number of suspicious bundles - %d %n", suspiciousBundles.size());
            pw.println();

            final String tab = "    ";

            for(BundleInfo bi : suspiciousBundles){
                pw.printf("* %s %n", bi);
                pw.printf("%s - Bundle Id - %d %n", tab, bi.bundleId);
                pw.printf("%s - Leaked classloaders %n", tab);
                for(ClassloaderInfo ci : bi.leakedClassloaders()){
                    pw.printf("%s%s - %s %n", tab, tab, ci);
                }
            }
        }
        pw.println();

        addHelp(pw);
    }

    private static void addHelp(PrintWriter pw){
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
        List<String> argList = bean.getInputArguments();

        boolean containsRequiredArgs = argList.contains("-XX:+UseConcMarkSweepGC")
                && argList.contains("-XX:+CMSClassUnloadingEnabled");

        if(!containsRequiredArgs){
            pw.println("Required VM Options Missing");
            pw.println("===========================");
            pw.println("Leak detector relies on garbage collection of classloaders. By default");
            pw.println("the classloaders are not garbage collected. To enable garbage collection of");
            pw.println("classloader start the JVM with following options ");
            pw.println("");
            pw.println("    -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled");
        }
    }

    //~---------------------------------------<Data Model>

    private static class BundleInfo {
        final String symbolicName;
        final String version;
        final long bundleId;
        private final Set<ClassloaderInfo> classloaderInfos =
                Collections.synchronizedSet(new HashSet<ClassloaderInfo>());

        public BundleInfo(Bundle b) {
            this.symbolicName = b.getSymbolicName();
            this.version = b.getVersion().toString();
            this.bundleId = b.getBundleId();
        }

        public synchronized void incrementUsageCount(BundleReference ref) {
            classloaderInfos.add(ref.classloaderInfo);
        }

        public synchronized void decrementUsageCount(BundleReference ref) {
            classloaderInfos.remove(ref.classloaderInfo);
        }

        public synchronized boolean hasSingleInstance() {
            return classloaderInfos.size() == 1;
        }

        public synchronized List<ClassloaderInfo> leakedClassloaders(){
            if(hasSingleInstance()){
                return new ArrayList<ClassloaderInfo>(classloaderInfos);
            }else{
                List<ClassloaderInfo> cis = new ArrayList<ClassloaderInfo>(classloaderInfos);
                Collections.sort(cis);

                //Leave out the latest classloader entry as that is
                //associated with running bundle
                return cis.subList(0, cis.size() - 1);
            }
        }

        @Override
        public String toString() {
            return String.format("%s (%s) - Classloader Count [%s]", symbolicName,
                    version, classloaderInfos.size());
        }
    }

    private static class ClassloaderInfo implements Comparable<ClassloaderInfo> {
        final Long creationTime = System.currentTimeMillis();
        /**
         * The hashCode might collide for two different classloaders but then
         * we cannot keep a hard reference to Classloader reference. So at best
         * we keep the systemHashCode and *assume* it is unqiue at least wrt
         * classloader instances
         */
        final long systemHashCode;

        private ClassloaderInfo(ClassLoader cl) {
            this.systemHashCode = System.identityHashCode(cl);
        }

        public int compareTo(ClassloaderInfo o) {
            return creationTime.compareTo(o.creationTime);
        }

        public String getAddress(){
            return Long.toHexString(systemHashCode);
        }

        public String getCreationDate(){
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
            return dateFormat.format(new Date(creationTime));
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            ClassloaderInfo that = (ClassloaderInfo) o;

            if (systemHashCode != that.systemHashCode) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return (int) (systemHashCode ^ (systemHashCode >>> 32));
        }

        @Override
        public String toString() {
            return String.format("Identity HashCode - %s, Creation time %s", getAddress(), getCreationDate());
        }
    }

    private class BundleReference extends PhantomReference<ClassLoader> {
        final Long bundleId;
        final ClassloaderInfo classloaderInfo;

        public BundleReference(Bundle bundle, ClassLoader cl) {
            super(cl, queue);
            this.bundleId = bundle.getBundleId();
            this.classloaderInfo = new ClassloaderInfo(cl);
        }
    }

    private static ClassLoader getClassloader(Bundle b) {
        //Somehow it fails to compile on JDK 7. Explicit cast helps
        BundleWiring bw = (BundleWiring) b.adapt(BundleWiring.class);
        if(bw != null){
            return bw.getClassLoader();
        }
        return null;
    }
}


text:
package mx.ambmultimedia.brillamexico.utils;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.view.View;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

public class URLImageParser implements Html.ImageGetter {
    Context c;
    View container;

    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(View t, Context c) {
        this.c = c;
        this.container = t;
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask( urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            // set the correct bound according to the result from HTTP call

            Rect outBoundsConainer = new Rect();
            container.getDrawingRect(outBoundsConainer);

            int width = outBoundsConainer.width();
            int height = (result.getIntrinsicHeight() / result.getIntrinsicWidth()) * width;

            urlDrawable.setBounds(0, 0, width, height);

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();
        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Drawable drawable = Drawable.createFromStream(is, "src");

                Rect outBoundsConainer = new Rect();
                container.getDrawingRect(outBoundsConainer);

                int width = outBoundsConainer.width();
                int height = (drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth()) * width;

                drawable.setBounds(0, 0, width, height);

                return drawable;
            } catch (Exception e) {
                return null;
            }
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
    }
}


text:
from freezegun import freeze_time
import sure  # noqa

from moto.swf.models import ActivityType, Timeout, WorkflowType, WorkflowExecution
from moto.swf.exceptions import SWFDefaultUndefinedFault
from ..utils import (
    auto_start_decision_tasks,
    get_basic_domain,
    get_basic_workflow_type,
    make_workflow_execution,
)

VALID_ACTIVITY_TASK_ATTRIBUTES = {
    "activityId": "my-activity-001",
    "activityType": {"name": "test-activity", "version": "v1.1"},
    "taskList": {"name": "task-list-name"},
    "scheduleToStartTimeout": "600",
    "scheduleToCloseTimeout": "600",
    "startToCloseTimeout": "600",
    "heartbeatTimeout": "300",
}

def test_workflow_execution_creation():
    domain = get_basic_domain()
    wft = get_basic_workflow_type()
    wfe = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE")

    wfe.domain.should.equal(domain)
    wfe.workflow_type.should.equal(wft)
    wfe.child_policy.should.equal("TERMINATE")

def test_workflow_execution_creation_child_policy_logic():
    domain = get_basic_domain()

    WorkflowExecution(
        domain,
        WorkflowType(
            "test-workflow",
            "v1.0",
            task_list="queue",
            default_child_policy="ABANDON",
            default_execution_start_to_close_timeout="300",
            default_task_start_to_close_timeout="300",
        ),
        "ab1234",
    ).child_policy.should.equal("ABANDON")

    WorkflowExecution(
        domain,
        WorkflowType(
            "test-workflow",
            "v1.0",
            task_list="queue",
            default_execution_start_to_close_timeout="300",
            default_task_start_to_close_timeout="300",
        ),
        "ab1234",
        child_policy="REQUEST_CANCEL",
    ).child_policy.should.equal("REQUEST_CANCEL")

    WorkflowExecution.when.called_with(
        domain, WorkflowType("test-workflow", "v1.0"), "ab1234"
    ).should.throw(SWFDefaultUndefinedFault)

def test_workflow_execution_string_representation():
    wfe = make_workflow_execution(child_policy="TERMINATE")
    str(wfe).should.match(r"^WorkflowExecution\(run_id: .*\)")

def test_workflow_execution_generates_a_random_run_id():
    domain = get_basic_domain()
    wft = get_basic_workflow_type()
    wfe1 = WorkflowExecution(domain, wft, "ab1234", child_policy="TERMINATE")
    wfe2 = WorkflowExecution(domain, wft, "ab1235", child_policy="TERMINATE")
    wfe1.run_id.should_not.equal(wfe2.run_id)

def test_workflow_execution_short_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    sd = wfe.to_short_dict()
    sd["workflowId"].should.equal("ab1234")
    sd.should.contain("runId")

def test_workflow_execution_medium_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    md = wfe.to_medium_dict()
    md["execution"].should.equal(wfe.to_short_dict())
    md["workflowType"].should.equal(wf_type.to_short_dict())
    md["startTimestamp"].should.be.a("float")
    md["executionStatus"].should.equal("OPEN")
    md["cancelRequested"].should.be.falsy
    md.should_not.contain("tagList")

    wfe.tag_list = ["foo", "bar", "baz"]
    md = wfe.to_medium_dict()
    md["tagList"].should.equal(["foo", "bar", "baz"])

def test_workflow_execution_full_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    fd = wfe.to_full_dict()
    fd["executionInfo"].should.equal(wfe.to_medium_dict())
    fd["openCounts"]["openTimers"].should.equal(0)
    fd["openCounts"]["openDecisionTasks"].should.equal(0)
    fd["openCounts"]["openActivityTasks"].should.equal(0)
    fd["executionConfiguration"].should.equal(
        {
            "childPolicy": "ABANDON",
            "executionStartToCloseTimeout": "300",
            "taskList": {"name": "queue"},
            "taskStartToCloseTimeout": "300",
        }
    )

def test_closed_workflow_execution_full_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")
    wfe.execution_status = "CLOSED"
    wfe.close_status = "CANCELED"
    wfe.close_timestamp = 1420066801.123

    fd = wfe.to_full_dict()
    medium_dict = wfe.to_medium_dict()
    medium_dict["closeStatus"] = "CANCELED"
    medium_dict["closeTimestamp"] = 1420066801.123
    fd["executionInfo"].should.equal(medium_dict)
    fd["openCounts"]["openTimers"].should.equal(0)
    fd["openCounts"]["openDecisionTasks"].should.equal(0)
    fd["openCounts"]["openActivityTasks"].should.equal(0)
    fd["executionConfiguration"].should.equal(
        {
            "childPolicy": "ABANDON",
            "executionStartToCloseTimeout": "300",
            "taskList": {"name": "queue"},
            "taskStartToCloseTimeout": "300",
        }
    )

def test_workflow_execution_list_dict_representation():
    domain = get_basic_domain()
    wf_type = WorkflowType(
        "test-workflow",
        "v1.0",
        task_list="queue",
        default_child_policy="ABANDON",
        default_execution_start_to_close_timeout="300",
        default_task_start_to_close_timeout="300",
    )
    wfe = WorkflowExecution(domain, wf_type, "ab1234")

    ld = wfe.to_list_dict()
    ld["workflowType"]["version"].should.equal("v1.0")
    ld["workflowType"]["name"].should.equal("test-workflow")
    ld["executionStatus"].should.equal("OPEN")
    ld["execution"]["workflowId"].should.equal("ab1234")
    ld["execution"].should.contain("runId")
    ld["cancelRequested"].should.be.false
    ld.should.contain("startTimestamp")

def test_workflow_execution_schedule_decision_task():
    wfe = make_workflow_execution()
    wfe.open_counts["openDecisionTasks"].should.equal(0)
    wfe.schedule_decision_task()
    wfe.open_counts["openDecisionTasks"].should.equal(1)

def test_workflow_execution_start_decision_task():
    wfe = make_workflow_execution()
    wfe.schedule_decision_task()
    dt = wfe.decision_tasks[0]
    wfe.start_decision_task(dt.task_token, identity="srv01")
    dt = wfe.decision_tasks[0]
    dt.state.should.equal("STARTED")
    wfe.events()[-1].event_type.should.equal("DecisionTaskStarted")
    wfe.events()[-1].event_attributes["identity"].should.equal("srv01")

def test_workflow_execution_history_events_ids():
    wfe = make_workflow_execution()
    wfe._add_event("WorkflowExecutionStarted")
    wfe._add_event("DecisionTaskScheduled")
    wfe._add_event("DecisionTaskStarted")
    ids = [evt.event_id for evt in wfe.events()]
    ids.should.equal([1, 2, 3])

@freeze_time("2015-01-01 12:00:00")
def test_workflow_execution_start():
    wfe = make_workflow_execution()
    wfe.events().should.equal([])

    wfe.start()
    wfe.start_timestamp.should.equal(1420113600.0)
    wfe.events().should.have.length_of(2)
    wfe.events()[0].event_type.should.equal("WorkflowExecutionStarted")
    wfe.events()[1].event_type.should.equal("DecisionTaskScheduled")

@freeze_time("2015-01-02 12:00:00")
def test_workflow_execution_complete():
    wfe = make_workflow_execution()
    wfe.complete(123, result="foo")

    wfe.execution_status.should.equal("CLOSED")
    wfe.close_status.should.equal("COMPLETED")
    wfe.close_timestamp.should.equal(1420200000.0)
    wfe.events()[-1].event_type.should.equal("WorkflowExecutionCompleted")
    wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"].should.equal(123)
    wfe.events()[-1].event_attributes["result"].should.equal("foo")

@freeze_time("2015-01-02 12:00:00")
def test_workflow_execution_fail():
    wfe = make_workflow_execution()
    wfe.fail(123, details="some details", reason="my rules")

    wfe.execution_status.should.equal("CLOSED")
    wfe.close_status.should.equal("FAILED")
    wfe.close_timestamp.should.equal(1420200000.0)
    wfe.events()[-1].event_type.should.equal("WorkflowExecutionFailed")
    wfe.events()[-1].event_attributes["decisionTaskCompletedEventId"].should.equal(123)
    wfe.events()[-1].event_attributes["details"].should.equal("some details")
    wfe.events()[-1].event_attributes["reason"].should.equal("my rules")

@freeze_time("2015-01-01 12:00:00")
def test_workflow_execution_schedule_activity_task():
    wfe = make_workflow_execution()
    wfe.latest_activity_task_timestamp.should.be.none

    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)

    wfe.latest_activity_task_timestamp.should.equal(1420113600.0)

    wfe.open_counts["openActivityTasks"].should.equal(1)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ActivityTaskScheduled")
    last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123)
    last_event.event_attributes["taskList"]["name"].should.equal("task-list-name")

    wfe.activity_tasks.should.have.length_of(1)
    task = wfe.activity_tasks[0]
    task.activity_id.should.equal("my-activity-001")
    task.activity_type.name.should.equal("test-activity")
    wfe.domain.activity_task_lists["task-list-name"].should.contain(task)

def test_workflow_execution_schedule_activity_task_without_task_list_should_take_default():
    wfe = make_workflow_execution()
    wfe.domain.add_type(ActivityType("test-activity", "v1.2", task_list="foobar"))
    wfe.schedule_activity_task(
        123,
        {
            "activityId": "my-activity-001",
            "activityType": {"name": "test-activity", "version": "v1.2"},
            "scheduleToStartTimeout": "600",
            "scheduleToCloseTimeout": "600",
            "startToCloseTimeout": "600",
            "heartbeatTimeout": "300",
        },
    )

    wfe.open_counts["openActivityTasks"].should.equal(1)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ActivityTaskScheduled")
    last_event.event_attributes["taskList"]["name"].should.equal("foobar")

    task = wfe.activity_tasks[0]
    wfe.domain.activity_task_lists["foobar"].should.contain(task)

def test_workflow_execution_schedule_activity_task_should_fail_if_wrong_attributes():
    wfe = make_workflow_execution()
    at = ActivityType("test-activity", "v1.1")
    at.status = "DEPRECATED"
    wfe.domain.add_type(at)
    wfe.domain.add_type(ActivityType("test-activity", "v1.2"))

    hsh = {
        "activityId": "my-activity-001",
        "activityType": {"name": "test-activity-does-not-exists", "version": "v1.1"},
    }

    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal("ACTIVITY_TYPE_DOES_NOT_EXIST")

    hsh["activityType"]["name"] = "test-activity"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal("ACTIVITY_TYPE_DEPRECATED")

    hsh["activityType"]["version"] = "v1.2"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal("DEFAULT_TASK_LIST_UNDEFINED")

    hsh["taskList"] = {"name": "foobar"}
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal(
        "DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED"
    )

    hsh["scheduleToStartTimeout"] = "600"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal(
        "DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED"
    )

    hsh["scheduleToCloseTimeout"] = "600"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal(
        "DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED"
    )

    hsh["startToCloseTimeout"] = "600"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal(
        "DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED"
    )

    wfe.open_counts["openActivityTasks"].should.equal(0)
    wfe.activity_tasks.should.have.length_of(0)
    wfe.domain.activity_task_lists.should.have.length_of(0)

    hsh["heartbeatTimeout"] = "300"
    wfe.schedule_activity_task(123, hsh)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ActivityTaskScheduled")

    task = wfe.activity_tasks[0]
    wfe.domain.activity_task_lists["foobar"].should.contain(task)
    wfe.open_counts["openDecisionTasks"].should.equal(0)
    wfe.open_counts["openActivityTasks"].should.equal(1)

def test_workflow_execution_schedule_activity_task_failure_triggers_new_decision():
    wfe = make_workflow_execution()
    wfe.start()
    task_token = wfe.decision_tasks[-1].task_token
    wfe.start_decision_task(task_token)
    wfe.complete_decision_task(
        task_token,
        execution_context="free-form execution context",
        decisions=[
            {
                "decisionType": "ScheduleActivityTask",
                "scheduleActivityTaskDecisionAttributes": {
                    "activityId": "my-activity-001",
                    "activityType": {
                        "name": "test-activity-does-not-exist",
                        "version": "v1.2",
                    },
                },
            },
            {
                "decisionType": "ScheduleActivityTask",
                "scheduleActivityTaskDecisionAttributes": {
                    "activityId": "my-activity-001",
                    "activityType": {
                        "name": "test-activity-does-not-exist",
                        "version": "v1.2",
                    },
                },
            },
        ],
    )

    wfe.latest_execution_context.should.equal("free-form execution context")
    wfe.open_counts["openActivityTasks"].should.equal(0)
    wfe.open_counts["openDecisionTasks"].should.equal(1)
    last_events = wfe.events()[-3:]
    last_events[0].event_type.should.equal("ScheduleActivityTaskFailed")
    last_events[1].event_type.should.equal("ScheduleActivityTaskFailed")
    last_events[2].event_type.should.equal("DecisionTaskScheduled")

def test_workflow_execution_schedule_activity_task_with_same_activity_id():
    wfe = make_workflow_execution()

    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    wfe.open_counts["openActivityTasks"].should.equal(1)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ActivityTaskScheduled")

    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    wfe.open_counts["openActivityTasks"].should.equal(1)
    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("ScheduleActivityTaskFailed")
    last_event.event_attributes["cause"].should.equal("ACTIVITY_ID_ALREADY_IN_USE")

def test_workflow_execution_start_activity_task():
    wfe = make_workflow_execution()
    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    task_token = wfe.activity_tasks[-1].task_token
    wfe.start_activity_task(task_token, identity="worker01")
    task = wfe.activity_tasks[-1]
    task.state.should.equal("STARTED")
    wfe.events()[-1].event_type.should.equal("ActivityTaskStarted")
    wfe.events()[-1].event_attributes["identity"].should.equal("worker01")

def test_complete_activity_task():
    wfe = make_workflow_execution()
    wfe.schedule_activity_task(123, VALID_ACTIVITY_TASK_ATTRIBUTES)
    task_token = wfe.activity_tasks[-1].task_token

    wfe.open_counts["openActivityTasks"].should.equal(1)
    wfe.open_counts["openDecisionTasks"].should.equal(0)

    wfe.start_activity_task(task_token, identity="worker01")
    wfe.complete_activity_task(task_token, result="a superb result")

    task = wfe.activity_tasks[-1]
    task.state.should.equal("COMPLETED")
    wfe.events()[-2].event_type.should.equal("ActivityTaskCompleted")
    wfe.events()[-1].event_type.should.equal("DecisionTaskScheduled")

    wfe.open_counts["openActivityTasks"].should.equal(0)
    wfe.open_counts["openDecisionTasks"].should.equal(1)

def test_terminate():
    wfe = make_workflow_execution()
    wfe.schedule_decision_task()
    wfe.terminate()

    wfe.execution_status.should.equal("CLOSED")
    wfe.close_status.should.equal("TERMINATED")
    wfe.close_cause.should.equal("OPERATOR_INITIATED")
    wfe.open_counts["openDecisionTasks"].should.equal(1)

    last_event = wfe.events()[-1]
    last_event.event_type.should.equal("WorkflowExecutionTerminated")
    # take default child_policy if not provided (as here)
    last_event.event_attributes["childPolicy"].should.equal("ABANDON")

def test_first_timeout():
    wfe = make_workflow_execution()
    wfe.first_timeout().should.be.none

    with freeze_time("2015-01-01 12:00:00"):
        wfe.start()
        wfe.first_timeout().should.be.none

    with freeze_time("2015-01-01 14:01"):
        # 2 hours timeout reached
        wfe.first_timeout().should.be.a(Timeout)

# See moto/swf/models/workflow_execution.py "_process_timeouts()" for more
# details
def test_timeouts_are_processed_in_order_and_reevaluated():
    # Let's make a Workflow Execution with the following properties:
    # - execution start to close timeout of 8 mins
    # - (decision) task start to close timeout of 5 mins
    #
    # Now start the workflow execution, and look at the history 15 mins later:
    # - a first decision task is fired just after workflow execution start
    # - the first decision task should have timed out after 5 mins
    # - that fires a new decision task (which we hack to start automatically)
    # - then the workflow timeouts after 8 mins (shows gradual reevaluation)
    # - but the last scheduled decision task should *not* timeout (workflow closed)
    with freeze_time("2015-01-01 12:00:00"):
        wfe = make_workflow_execution(
            execution_start_to_close_timeout=8 * 60, task_start_to_close_timeout=5 * 60
        )
        # decision will automatically start
        wfe = auto_start_decision_tasks(wfe)
        wfe.start()
        event_idx = len(wfe.events())

    with freeze_time("2015-01-01 12:08:00"):
        wfe._process_timeouts()

        event_types = [e.event_type for e in wfe.events()[event_idx:]]
        event_types.should.equal(
            [
                "DecisionTaskTimedOut",
                "DecisionTaskScheduled",
                "DecisionTaskStarted",
                "WorkflowExecutionTimedOut",
            ]
        )


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ThemeBundle\Context;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class EmptyThemeContext implements ThemeContextInterface
{
    /**
     * {@inheritdoc}
     *
     * @return null
     */
    public function getTheme()
    {
        return null;
    }
}


text:
import { Component, OnInit } from '@angular/core';
import {BuildInfoService, BuildInfo} from '../../core/build/build-info.service';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

  buildInfo: BuildInfo;

  constructor(private buildInfoService: BuildInfoService) { }

  ngOnInit() {
    this.buildInfoService.load().subscribe(
      (buildInfo) => this.buildInfo = buildInfo
    );
  }

}


text:
var express = require('express');
var router = express.Router();

var Message = require('../models/message');

router.get('/', function (req, res, next) {
    Message.find()
        .exec(function (err, messages) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occurred',
                    error: err
                });
            }
            res.status(200).json({
                message: 'Success',
                obj: messages
            });
        });
});

router.post('/', function (req, res, next) {
    var message = new Message({
        content: req.body.content
    });
    message.save(function (err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
        }
        res.status(201).json({
            message: 'Saved message',
            obj: result
        });
    });
});

router.patch('/:id', function (req, res, next) {
    Message.findById(req.params.id, function (err, message) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
        }
        if (!message) {
            return res.status(500).json({
                title: 'No Message Found!',
                error: {message: 'Message not found'}
            });
        }
        message.content = req.body.content;
        message.save(function(err, result) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occurred',
                    error: err
                });
            }
            res.status(200).json({
                message: 'Updated message',
                obj: result
            });
        });
    });
});

router.delete('/:id', function(req, res, next) {
    Message.findById(req.params.id, function (err, message) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
        }
        if (!message) {
            return res.status(500).json({
                title: 'No Message Found!',
                error: {message: 'Message not found'}
            });
        }
        message.remove(function(err, result) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occurred',
                    error: err
                });
            }
            res.status(200).json({
                message: 'Deleted message',
                obj: result
            });
        });
    });
});

module.exports = router;


text:
@interface PASFollowManager ()

@property (nonatomic, strong) PASDataProvider *dataProvider;
@property (nonatomic ,strong) NSMutableDictionary *dataDic;
@property (nonatomic ,assign) int failCount;
@end
@implementation PASFollowManager
- (instancetype)init
{
    if (self = [super init])
    {
        PASConfiguration *config = [PASConfiguration shareInstance];

        NSString *strURL = [[NSUserDefaults standardUserDefaults] objectForKey:kNSUserDefaultMainHost];
        config.baseURL = [NSURL URLWithString:strURL];
        _dataProvider = [[PASDataProvider alloc] initWithConfiguration:config];
    }
    return self;
}
- (void)requestAllFollowAppsWithBundleIDs:(NSArray *)bundleIDs
                                  success:(PAS_FollowSuccessBlock)sucess
                                     fail:(PAS_FollowSuccessFailBlock)fail  {

    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (int i = 0; i < bundleIDs.count; i++) {

        NSString *bundleID = bundleIDs[i];
        dispatch_group_async(group, queue, ^{

            __weak PASFollowManager *weakSelf = self;
            [_dataProvider getAllBuildsWithParameters:nil bundleID:bundleID completion:^(id  _Nullable responseObject, NSError * _Nullable error) {
                if (error) {
                    weakSelf.failCount ++;

                }else {
                [weakSelf handleRequestWithResponseObject:responseObject];

                }
                dispatch_group_leave(group);
            }];

        });
        dispatch_group_enter(group);

    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        //请求完成
        if (sucess&&_failCount<bundleIDs.count) {
            sucess (self.dataDic);
            return ;
        }
        if (fail&&_failCount==bundleIDs.count) {
            fail(@"0000",@"失败");
        }
    });
}
- (void)handleRequestWithResponseObject:(id)responseObject {

    if ([responseObject isKindOfClass:[NSArray class]]) {
        NSArray *dataArr = (NSArray *)responseObject;
        NSMutableArray *dataArra = [[NSMutableArray alloc] init];
        for (int i = 0; i < dataArr.count; i++) {
            NSDictionary *dataDic = dataArr[i];
            PASDiscoverModel *model = [PASDiscoverModel yy_modelWithDictionary:dataDic];
            [dataArra addObject:model];
            if (i == dataArr.count -1) {
                [self.dataDic setObject:dataArra forKey:model.name];
            }
        }
    }
}
- (NSMutableDictionary *)dataDic {

    if (!_dataDic) {
        _dataDic = [[NSMutableDictionary alloc] init];
    }
    return _dataDic;
}
@end


text:
package com.tterrag.k9.util.annotation;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target({ TYPE, FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, PACKAGE, TYPE_PARAMETER, TYPE_USE })
public @interface NonNull {

}


text:
package goauto

import (
	"fmt"
	"regexp"
	"time"
)

// A Workflow represents a set of tasks for files matching one or more regex patterns
type Workflow struct {
	Name       string
	Concurrent bool
	Op         Op
	Regexs     []*regexp.Regexp
	Tasks      []Tasker
}

// NewWorkflow returns a Workflow with tasks
func NewWorkflow(tasks ...Tasker) *Workflow {
	wf := new(Workflow)
	wf.WatchOp(Create | Write | Remove | Rename)
	wf.Add(tasks...)
	return wf
}

// WatchPattern adds one or more regex for matching files for this workflow
// An invalid regexp pattern will return an error
// Sets file operations to Create|Write|Remove|Rename if not set
func (wf *Workflow) WatchPattern(patterns ...string) error {
	if wf.Op == 0 {
		wf.WatchOp(Create | Write | Remove | Rename)
	}
	for _, p := range patterns {
		r, err := regexp.Compile(p)
		if err != nil {
			return err
		}
		wf.Regexs = append(wf.Regexs, r)
	}
	return nil
}

// WatchOp sets the file operations to match
// The default is Create | Write | Remove | Rename
func (wf *Workflow) WatchOp(op Op) {
	wf.Op = op
}

func (wf *Workflow) matchOp(op Op) bool {
	switch {
	case wf.Op&Create == op&Create:
		return true
	case wf.Op&Write == op&Write:
		return true
	case wf.Op&Remove == op&Remove:
		return true
	case wf.Op&Rename == op&Rename:
		return true
	case wf.Op&Chmod == op&Chmod:
		return true
	}
	return false
}

// Match checks a file name against the regexp of the Workflow and the file operation
func (wf *Workflow) Match(fpath string, op Op) bool {
	if wf.matchOp(op) {
		for _, r := range wf.Regexs {
			if r.MatchString(fpath) {
				return true
			}
		}
	}
	return false
}

// Add adds a task to the workflow
func (wf *Workflow) Add(tasks ...Tasker) {
	for _, t := range tasks {
		wf.Tasks = append(wf.Tasks, t)
	}
}

func (wf *Workflow) runner(info *TaskInfo) {
	if info.Verbose {
		fmt.Fprintf(info.Tout, ">> %v %v for %v\n\n", time.Now().Format("2006/01/02 3:04pm"), wf.Name, info.Src)
	}
	fname := info.Src
	info.Collect = []string{fname}
	var err error
	for _, t := range wf.Tasks {
		info.Target = "" // reset the Target
		if err = t.Run(info); err != nil {
			fmt.Fprintln(info.Terr, err)
			fmt.Fprintf(info.Terr, "Fail! Workflow %v did not complete for %v\n\n\n", wf.Name, fname)
			return
		}
		if info.Target != "" {
			// if the task set a target use it for the Src in the next task
			info.Src = info.Target
			info.Collect = append(info.Collect, info.Target)
		}
	}
}

// Run will start the execution of tasks
func (wf *Workflow) Run(info *TaskInfo) {
	if wf.Concurrent {
		go wf.runner(info)
		return
	}
	wf.runner(info)
}


text:
'use strict'

const assert = require('chai').assert
const proxyquire = require('proxyquire')
const spooks = require('spooks')
const Promise = require('bluebird')

const modulePath = '../../src/parse'

suite('parse:', () => {
  test('require does not throw', () => {
    assert.doesNotThrow(() => {
      require(modulePath)
    })
  })

  test('require returns function', () => {
    assert.isFunction(require(modulePath))
  })

  suite('require:', () => {
    let log, results, parse

    setup(() => {
      log = {}
      results = {
        walk: [
          {
            on: spooks.fn({ name: 'on', log: log }),
            pause: spooks.fn({ name: 'pause', log: log, results: [ () => {} ] }),
            removeAllListeners: spooks.fn({ name: 'removeAllListeners', log: log })
          }
        ]
      }
      parse = proxyquire(modulePath, {
        './walk': spooks.fn({
          name: 'walk',
          log: log,
          results: results.walk
        })
      })
    })

    test('parse expects one argument', () => {
      assert.lengthOf(parse, 1)
    })

    test('parse does not throw', () => {
      assert.doesNotThrow(() => {
        parse()
      })
    })

    test('parse does not throw if reviver is an object', () => {
      assert.doesNotThrow(() => {
        parse({}, { reviver: {} }).catch(() => {})
      })
    })

    test('parse does not throw if revive is a function', () => {
      assert.doesNotThrow(() => {
        parse({}, { reviver: () => {} })
      })
    })

    test('parse returns a promise', () => {
      assert.instanceOf(parse(), Promise)
    })

    test('parse returns a different type of promise if the option is set', () => {
      assert.isFunction(global.Promise)
      assert.notStrictEqual(Promise, global.Promise)
      assert.instanceOf(parse('', { Promise: global.Promise }), global.Promise)
    })

    test('parse rejects immediately if reviver is an object', () => {
      return parse({}, { reviver: {} })
        .then(() => assert(false))
        .catch(error => assert.instanceOf(error, Error))
    })

    test('parse does not reject immediately if reviver is a function', () => {
      parse({}, { reviver: () => {} })
        .catch(error => assert(false))
    })

    test('walk was not called', () => {
      assert.strictEqual(log.counts.walk, 0)
    })

    test('EventEmitter.on was not called', () => {
      assert.strictEqual(log.counts.on, 0)
    })

    suite('parse:', () => {
      let stream, options

      setup(() => {
        stream = {}
        options = {}
        parse(stream, options)
          .then(spooks.fn({ name: 'resolve', log: log }))
          .catch(spooks.fn({ name: 'reject', log: log }))
      })

      test('walk was called once', () => {
        assert.strictEqual(log.counts.walk, 1)
        assert.isUndefined(log.these.walk[0])
      })

      test('walk was called correctly', () => {
        assert.lengthOf(log.args.walk[0], 2)
        assert.strictEqual(log.args.walk[0][0], stream)
        assert.lengthOf(Object.keys(log.args.walk[0][0]), 0)
        assert.strictEqual(log.args.walk[0][1], options)
        assert.lengthOf(Object.keys(log.args.walk[0][1]), 0)
      })

      test('EventEmitter.on was called eleven times', () => {
        assert.strictEqual(log.counts.on, 11)
        assert.strictEqual(log.these.on[0], results.walk[0])
        assert.strictEqual(log.these.on[1], results.walk[0])
        assert.strictEqual(log.these.on[2], results.walk[0])
        assert.strictEqual(log.these.on[3], results.walk[0])
        assert.strictEqual(log.these.on[4], results.walk[0])
        assert.strictEqual(log.these.on[5], results.walk[0])
        assert.strictEqual(log.these.on[6], results.walk[0])
        assert.strictEqual(log.these.on[7], results.walk[0])
        assert.strictEqual(log.these.on[8], results.walk[0])
        assert.strictEqual(log.these.on[9], results.walk[0])
        assert.strictEqual(log.these.on[10], results.walk[0])
      })

      test('EventEmitter.on was called correctly first time', () => {
        assert.lengthOf(log.args.on[0], 2)
        assert.strictEqual(log.args.on[0][0], 'arr')
        assert.isFunction(log.args.on[0][1])
      })

      test('EventEmitter.on was called correctly second time', () => {
        assert.lengthOf(log.args.on[1], 2)
        assert.strictEqual(log.args.on[1][0], 'obj')
        assert.isFunction(log.args.on[1][1])
        assert.notStrictEqual(log.args.on[1][1], log.args.on[0][1])
      })

      test('EventEmitter.on was called correctly third time', () => {
        assert.lengthOf(log.args.on[2], 2)
        assert.strictEqual(log.args.on[2][0], 'pro')
        assert.isFunction(log.args.on[2][1])
        assert.notStrictEqual(log.args.on[2][1], log.args.on[0][1])
        assert.notStrictEqual(log.args.on[2][1], log.args.on[1][1])
      })

      test('EventEmitter.on was called correctly fourth time', () => {
        assert.lengthOf(log.args.on[3], 2)
        assert.strictEqual(log.args.on[3][0], 'str')
        assert.isFunction(log.args.on[3][1])
        assert.notStrictEqual(log.args.on[3][1], log.args.on[0][1])
        assert.notStrictEqual(log.args.on[3][1], log.args.on[1][1])
        assert.notStrictEqual(log.args.on[3][1], log.args.on[2][1])
      })

      test('EventEmitter.on was called correctly fifth time', () => {
        assert.lengthOf(log.args.on[4], 2)
        assert.strictEqual(log.args.on[4][0], 'num')
        assert.isFunction(log.args.on[4][1])
        assert.strictEqual(log.args.on[4][1], log.args.on[3][1])
      })

      test('EventEmitter.on was called correctly sixth time', () => {
        assert.lengthOf(log.args.on[5], 2)
        assert.strictEqual(log.args.on[5][0], 'lit')
        assert.isFunction(log.args.on[5][1])
        assert.strictEqual(log.args.on[5][1], log.args.on[3][1])
      })

      test('EventEmitter.on was called correctly seventh time', () => {
        assert.lengthOf(log.args.on[6], 2)
        assert.strictEqual(log.args.on[6][0], 'end-arr')
        assert.isFunction(log.args.on[6][1])
        assert.notStrictEqual(log.args.on[6][1], log.args.on[0][1])
        assert.notStrictEqual(log.args.on[6][1], log.args.on[1][1])
        assert.notStrictEqual(log.args.on[6][1], log.args.on[2][1])
        assert.notStrictEqual(log.args.on[6][1], log.args.on[3][1])
      })

      test('EventEmitter.on was called correctly eighth time', () => {
        assert.lengthOf(log.args.on[7], 2)
        assert.strictEqual(log.args.on[7][0], 'end-obj')
        assert.isFunction(log.args.on[7][1])
        assert.strictEqual(log.args.on[7][1], log.args.on[6][1])
      })

      test('EventEmitter.on was called correctly ninth time', () => {
        assert.lengthOf(log.args.on[8], 2)
        assert.strictEqual(log.args.on[8][0], 'end')
        assert.isFunction(log.args.on[8][1])
        assert.notStrictEqual(log.args.on[8][1], log.args.on[0][1])
        assert.notStrictEqual(log.args.on[8][1], log.args.on[1][1])
        assert.notStrictEqual(log.args.on[8][1], log.args.on[2][1])
        assert.notStrictEqual(log.args.on[8][1], log.args.on[3][1])
        assert.notStrictEqual(log.args.on[8][1], log.args.on[6][1])
      })

      test('EventEmitter.on was called correctly tenth time', () => {
        assert.lengthOf(log.args.on[9], 2)
        assert.strictEqual(log.args.on[9][0], 'err')
        assert.isFunction(log.args.on[9][1])
        assert.notStrictEqual(log.args.on[9][1], log.args.on[0][1])
        assert.notStrictEqual(log.args.on[9][1], log.args.on[1][1])
        assert.notStrictEqual(log.args.on[9][1], log.args.on[2][1])
        assert.notStrictEqual(log.args.on[9][1], log.args.on[3][1])
        assert.notStrictEqual(log.args.on[9][1], log.args.on[6][1])
        assert.notStrictEqual(log.args.on[9][1], log.args.on[8][1])
      })

      test('EventEmitter.on was called correctly eleventh time', () => {
        assert.lengthOf(log.args.on[10], 2)
        assert.strictEqual(log.args.on[10][0], 'err-data')
        assert.isFunction(log.args.on[10][1])
        assert.strictEqual(log.args.on[10][1], log.args.on[9][1])
      })

      suite('array event:', () => {
        setup(() => {
          log.args.on[0][1]()
        })

        test('resolve was not called', () => {
          assert.strictEqual(log.counts.resolve, 0)
        })

        suite('end event:', () => {
          setup(done => {
            log.args.on[8][1]()
            setImmediate(done)
          })

          test('resolve was called once', () => {
            assert.strictEqual(log.counts.resolve, 1)
          })

          test('resolve was called correctly', () => {
            assert.isUndefined(log.these.resolve[0])
            assert.lengthOf(log.args.resolve[0], 1)
            assert.isArray(log.args.resolve[0][0])
            assert.lengthOf(log.args.resolve[0][0], 0)
          })

          test('reject was not called', () => {
            assert.strictEqual(log.counts.reject, 0)
          })
        })

        suite('string event:', () => {
          setup(() => {
            log.args.on[3][1]('foo')
          })

          test('resolve was not called', () => {
            assert.strictEqual(log.counts.resolve, 0)
          })

          suite('end event:', () => {
            setup(done => {
              log.args.on[8][1]()
              setImmediate(done)
            })

            test('resolve was called once', () => {
              assert.strictEqual(log.counts.resolve, 1)
            })

            test('resolve was called correctly', () => {
              assert.lengthOf(log.args.resolve[0], 1)
              assert.isArray(log.args.resolve[0][0])
              assert.lengthOf(log.args.resolve[0][0], 1)
              assert.strictEqual(log.args.resolve[0][0][0], 'foo')
            })
          })

          suite('string event:', () => {
            setup(() => {
              log.args.on[3][1]('bar')
            })

            test('resolve was not called', () => {
              assert.strictEqual(log.counts.resolve, 0)
            })

            suite('end event:', () => {
              setup(done => {
                log.args.on[8][1]()
                setImmediate(done)
              })

              test('resolve was called once', () => {
                assert.strictEqual(log.counts.resolve, 1)
              })

              test('resolve was called correctly', () => {
                assert.lengthOf(log.args.resolve[0][0], 2)
                assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                assert.strictEqual(log.args.resolve[0][0][1], 'bar')
              })
            })
          })

          suite('array event:', () => {
            setup(() => {
              log.args.on[0][1]()
            })

            test('resolve was not called', () => {
              assert.strictEqual(log.counts.resolve, 0)
            })

            suite('end event:', () => {
              setup(done => {
                log.args.on[8][1]()
                setImmediate(done)
              })

              test('resolve was called once', () => {
                assert.strictEqual(log.counts.resolve, 1)
              })

              test('resolve was called correctly', () => {
                assert.lengthOf(log.args.resolve[0][0], 2)
                assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                assert.isArray(log.args.resolve[0][0][1])
                assert.lengthOf(log.args.resolve[0][0][1], 0)
              })
            })

            suite('string event:', () => {
              setup(() => {
                log.args.on[3][1]('bar')
              })

              test('resolve was not called', () => {
                assert.strictEqual(log.counts.resolve, 0)
              })

              suite('end event:', () => {
                setup(done => {
                  log.args.on[8][1]()
                  setImmediate(done)
                })

                test('resolve was called once', () => {
                  assert.strictEqual(log.counts.resolve, 1)
                })

                test('resolve was called correctly', () => {
                  assert.lengthOf(log.args.resolve[0][0], 2)
                  assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                  assert.isArray(log.args.resolve[0][0][1])
                  assert.lengthOf(log.args.resolve[0][0][1], 1)
                  assert.strictEqual(log.args.resolve[0][0][1][0], 'bar')
                })
              })

              suite('string event:', () => {
                setup(() => {
                  log.args.on[3][1]('baz')
                })

                test('resolve was not called', () => {
                  assert.strictEqual(log.counts.resolve, 0)
                })

                suite('end event:', () => {
                  setup(done => {
                    log.args.on[8][1]()
                    setImmediate(done)
                  })

                  test('resolve was called once', () => {
                    assert.strictEqual(log.counts.resolve, 1)
                  })

                  test('resolve was called correctly', () => {
                    assert.lengthOf(log.args.resolve[0][0], 2)
                    assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                    assert.isArray(log.args.resolve[0][0][1])
                    assert.lengthOf(log.args.resolve[0][0][1], 2)
                    assert.strictEqual(log.args.resolve[0][0][1][0], 'bar')
                    assert.strictEqual(log.args.resolve[0][0][1][1], 'baz')
                  })
                })
              })

              suite('endArray event:', () => {
                setup(() => {
                  log.args.on[6][1]()
                })

                suite('string event:', () => {
                  setup(() => {
                    log.args.on[3][1]('baz')
                  })

                  test('resolve was not called', () => {
                    assert.strictEqual(log.counts.resolve, 0)
                  })

                  suite('end event:', () => {
                    setup(done => {
                      log.args.on[8][1]()
                      setImmediate(done)
                    })

                    test('resolve was called once', () => {
                      assert.strictEqual(log.counts.resolve, 1)
                    })

                    test('resolve was called correctly', () => {
                      assert.lengthOf(log.args.resolve[0][0], 3)
                      assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                      assert.isArray(log.args.resolve[0][0][1])
                      assert.lengthOf(log.args.resolve[0][0][1], 1)
                      assert.strictEqual(log.args.resolve[0][0][1][0], 'bar')
                      assert.strictEqual(log.args.resolve[0][0][2], 'baz')
                    })
                  })
                })
              })
            })
          })

          suite('object event:', () => {
            setup(() => {
              log.args.on[1][1]()
            })

            test('resolve was not called', () => {
              assert.strictEqual(log.counts.resolve, 0)
            })

            suite('end event:', () => {
              setup(done => {
                log.args.on[8][1]()
                setImmediate(done)
              })

              test('resolve was called once', () => {
                assert.strictEqual(log.counts.resolve, 1)
              })

              test('resolve was called correctly', () => {
                assert.lengthOf(log.args.resolve[0][0], 2)
                assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                assert.isObject(log.args.resolve[0][0][1])
                assert.lengthOf(Object.keys(log.args.resolve[0][0][1]), 0)
              })
            })

            suite('property event:', () => {
              setup(() => {
                log.args.on[2][1]('bar')
              })

              suite('string event:', () => {
                setup(() => {
                  log.args.on[3][1]('baz')
                })

                test('resolve was not called', () => {
                  assert.strictEqual(log.counts.resolve, 0)
                })

                suite('end event:', () => {
                  setup(done => {
                    log.args.on[8][1]()
                    setImmediate(done)
                  })

                  test('resolve was called once', () => {
                    assert.strictEqual(log.counts.resolve, 1)
                  })

                  test('resolve was called correctly', () => {
                    assert.lengthOf(log.args.resolve[0][0], 2)
                    assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                    assert.isObject(log.args.resolve[0][0][1])
                    assert.lengthOf(Object.keys(log.args.resolve[0][0][1]), 1)
                    assert.strictEqual(log.args.resolve[0][0][1].bar, 'baz')
                  })
                })

                suite('property event:', () => {
                  setup(() => {
                    log.args.on[2][1]('qux')
                  })

                  suite('string event:', () => {
                    setup(() => {
                      log.args.on[3][1]('wibble')
                    })

                    test('resolve was not called', () => {
                      assert.strictEqual(log.counts.resolve, 0)
                    })

                    suite('end event:', () => {
                      setup(done => {
                        log.args.on[8][1]()
                        setImmediate(done)
                      })

                      test('resolve was called once', () => {
                        assert.strictEqual(log.counts.resolve, 1)
                      })

                      test('resolve was called correctly', () => {
                        assert.lengthOf(log.args.resolve[0][0], 2)
                        assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                        assert.isObject(log.args.resolve[0][0][1])
                        assert.lengthOf(Object.keys(log.args.resolve[0][0][1]), 2)
                        assert.strictEqual(log.args.resolve[0][0][1].bar, 'baz')
                        assert.strictEqual(log.args.resolve[0][0][1].qux, 'wibble')
                      })
                    })
                  })
                })

                suite('endObject event:', () => {
                  setup(() => {
                    log.args.on[7][1]()
                  })

                  suite('string event:', () => {
                    setup(() => {
                      log.args.on[3][1]('wibble')
                    })

                    test('resolve was not called', () => {
                      assert.strictEqual(log.counts.resolve, 0)
                    })

                    suite('end event:', () => {
                      setup(done => {
                        log.args.on[8][1]()
                        setImmediate(done)
                      })

                      test('resolve was called once', () => {
                        assert.strictEqual(log.counts.resolve, 1)
                      })

                      test('resolve was called correctly', () => {
                        assert.lengthOf(log.args.resolve[0][0], 3)
                        assert.strictEqual(log.args.resolve[0][0][0], 'foo')
                        assert.isObject(log.args.resolve[0][0][1])
                        assert.lengthOf(Object.keys(log.args.resolve[0][0][1]), 1)
                        assert.strictEqual(log.args.resolve[0][0][1].bar, 'baz')
                        assert.strictEqual(log.args.resolve[0][0][2], 'wibble')
                      })
                    })
                  })
                })
              })
            })
          })
        })

        suite('error event:', () => {
          setup(() => {
            log.args.on[9][1]('foo')
          })

          test('reject was not called', () => {
            assert.strictEqual(log.counts.reject, 0)
          })

          suite('end event:', () => {
            setup(done => {
              log.args.on[8][1]()
              setImmediate(done)
            })

            test('reject was called once', () => {
              assert.strictEqual(log.counts.reject, 1)
            })

            test('reject was called correctly', () => {
              assert.isUndefined(log.these.reject[0])
              assert.lengthOf(log.args.reject[0], 1)
              assert.strictEqual(log.args.reject[0][0], 'foo')
            })
          })

          suite('error event:', () => {
            setup(() => {
              log.args.on[9][1]('bar')
            })

            test('reject was not called', () => {
              assert.strictEqual(log.counts.reject, 0)
            })

            suite('end event:', () => {
              setup(done => {
                log.args.on[8][1]()
                setImmediate(done)
              })

              test('reject was called once', () => {
                assert.strictEqual(log.counts.reject, 1)
              })

              test('reject was called correctly', () => {
                assert.strictEqual(log.args.reject[0][0], 'foo')
              })
            })
          })
        })
      })

      suite('object event:', () => {
        setup(() => {
          log.args.on[1][1]()
        })

        test('resolve was not called', () => {
          assert.strictEqual(log.counts.resolve, 0)
        })

        suite('end event:', () => {
          setup(done => {
            log.args.on[8][1]()
            setImmediate(done)
          })

          test('resolve was called once', () => {
            assert.strictEqual(log.counts.resolve, 1)
          })

          test('resolve was called correctly', () => {
            assert.isObject(log.args.resolve[0][0])
            assert.lengthOf(Object.keys(log.args.resolve[0][0]), 0)
          })
        })
      })
    })

    suite('parse with reviver:', () => {
      let stream, options

      setup(() => {
        stream = {}
        options = { reviver: spooks.fn({ name: 'reviver', log: log, results: [ 'reviver result' ] }) }
        parse(stream, options)
          .then(spooks.fn({ name: 'resolve', log: log }))
          .catch(spooks.fn({ name: 'reject', log: log }))
      })

      test('walk was called once', () => {
        assert.strictEqual(log.counts.walk, 1)
      })

      test('EventEmitter.on was called eleven times', () => {
        assert.strictEqual(log.counts.on, 11)
      })

      suite('populated array events:', () => {
        setup(() => {
          log.args.on[0][1]()
          log.args.on[3][1]('foo')
          log.args.on[3][1]('bar')
          log.args.on[0][1]()
          log.args.on[0][1]()
          log.args.on[3][1]('baz')
          log.args.on[6][1]()
          log.args.on[3][1]('qux')
          log.args.on[6][1]()
          log.args.on[6][1]()
        })

        test('resolve was not called', () => {
          assert.strictEqual(log.counts.resolve, 0)
        })

        test('reviver was not called', () => {
          assert.strictEqual(log.counts.resolve, 0)
        })

        suite('end event:', () => {
          setup(done => {
            log.args.on[8][1]()
            setImmediate(done)
          })

          test('resolve was called once', () => {
            assert.strictEqual(log.counts.resolve, 1)
          })

          test('reviver was called six times', () => {
            assert.strictEqual(log.counts.reviver, 7)
          })

          test('reviver was called correctly first time', () => {
            assert.lengthOf(log.args.reviver[0], 2)
            assert.strictEqual(log.args.reviver[0][0], '0')
            assert.strictEqual(log.args.reviver[0][1], 'foo')
          })

          test('reviver was called correctly second time', () => {
            assert.strictEqual(log.args.reviver[1][0], '1')
            assert.strictEqual(log.args.reviver[1][1], 'bar')
          })

          test('reviver was called correctly third time', () => {
            assert.strictEqual(log.args.reviver[2][0], '0')
            assert.strictEqual(log.args.reviver[2][1], 'baz')
          })

          test('reviver was called correctly fourth time', () => {
            assert.strictEqual(log.args.reviver[3][0], '0')
            assert.isArray(log.args.reviver[3][1])
            assert.lengthOf(log.args.reviver[3][1], 1)
            assert.strictEqual(log.args.reviver[3][1][0], 'reviver result')
          })

          test('reviver was called correctly fifth time', () => {
            assert.strictEqual(log.args.reviver[4][0], '1')
            assert.strictEqual(log.args.reviver[4][1], 'qux')
          })

          test('reviver was called correctly sixth time', () => {
            assert.strictEqual(log.args.reviver[5][0], '2')
            assert.isArray(log.args.reviver[5][1])
            assert.lengthOf(log.args.reviver[5][1], 2)
            assert.strictEqual(log.args.reviver[5][1][0], 'reviver result')
            assert.strictEqual(log.args.reviver[5][1][1], 'reviver result')
          })

          test('reviver was called correctly seventh time', () => {
            assert.strictEqual(log.args.reviver[6][0], '')
            assert.isArray(log.args.reviver[6][1])
            assert.lengthOf(log.args.reviver[6][1], 3)
            assert.strictEqual(log.args.reviver[6][1][0], 'reviver result')
            assert.strictEqual(log.args.reviver[6][1][1], 'reviver result')
            assert.strictEqual(log.args.reviver[6][1][2], 'reviver result')
          })
        })
      })

      suite('populated object events:', () => {
        setup(() => {
          log.args.on[1][1]()
          log.args.on[2][1]('foo')
          log.args.on[1][1]()
          log.args.on[2][1]('bar')
          log.args.on[4][1](3.14159265359)
          log.args.on[7][1]()
          log.args.on[2][1]('baz')
          log.args.on[5][1](null)
          log.args.on[7][1]()
        })

        test('resolve was not called', () => {
          assert.strictEqual(log.counts.resolve, 0)
        })

        test('reviver was not called', () => {
          assert.strictEqual(log.counts.resolve, 0)
        })

        suite('end event:', () => {
          setup(done => {
            log.args.on[8][1]()
            setImmediate(done)
          })

          test('resolve was called once', () => {
            assert.strictEqual(log.counts.resolve, 1)
          })

          test('reviver was called four times', () => {
            assert.strictEqual(log.counts.reviver, 4)
          })

          test('reviver was called correctly first time', () => {
            assert.lengthOf(log.args.reviver[0], 2)
            assert.strictEqual(log.args.reviver[0][0], 'bar')
            assert.strictEqual(log.args.reviver[0][1], 3.14159265359)
          })

          test('reviver was called correctly second time', () => {
            assert.strictEqual(log.args.reviver[1][0], 'foo')
            assert.isObject(log.args.reviver[1][1])
            assert.lengthOf(Object.keys(log.args.reviver[1][1]), 1)
            assert.strictEqual(log.args.reviver[1][1].bar, 'reviver result')
          })

          test('reviver was called correctly third time', () => {
            assert.strictEqual(log.args.reviver[2][0], 'baz')
            assert.isNull(log.args.reviver[2][1])
          })

          test('reviver was called correctly fourth time', () => {
            assert.strictEqual(log.args.reviver[3][0], '')
            assert.isObject(log.args.reviver[3][1])
            assert.lengthOf(Object.keys(log.args.reviver[3][1]), 2)
            assert.strictEqual(log.args.reviver[3][1].foo, 'reviver result')
            assert.strictEqual(log.args.reviver[3][1].baz, 'reviver result')
          })
        })
      })
    })

    suite('parse with ndjson:', () => {
      let stream

      setup(() => {
        stream = {}
        parse(stream, { ndjson: true })
          .then(spooks.fn({ name: 'resolve', log: log }))
          .catch(spooks.fn({ name: 'reject', log: log }))
      })

      test('walk was called once', () => {
        assert.strictEqual(log.counts.walk, 1)
      })

      test('EventEmitter.on was called twelve times', () => {
        assert.strictEqual(log.counts.on, 12)
        assert.strictEqual(log.these.on[11], results.walk[0])
      })

      test('EventEmitter.on was called correctly first eleven times', () => {
        assert.strictEqual(log.args.on[0][0], 'arr')
        assert.strictEqual(log.args.on[1][0], 'obj')
        assert.strictEqual(log.args.on[2][0], 'pro')
        assert.strictEqual(log.args.on[3][0], 'str')
        assert.strictEqual(log.args.on[4][0], 'num')
        assert.strictEqual(log.args.on[5][0], 'lit')
        assert.strictEqual(log.args.on[6][0], 'end-arr')
        assert.strictEqual(log.args.on[7][0], 'end-obj')
        assert.strictEqual(log.args.on[8][0], 'end')
        assert.strictEqual(log.args.on[9][0], 'err')
        assert.strictEqual(log.args.on[10][0], 'err-data')
      })

      test('EventEmitter.on was called correctly twelfth time', () => {
        assert.lengthOf(log.args.on[11], 2)
        assert.strictEqual(log.args.on[11][0], 'end-line')
        assert.isFunction(log.args.on[11][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[0][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[1][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[2][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[3][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[6][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[8][1])
        assert.notStrictEqual(log.args.on[11][1], log.args.on[9][1])
      })

      test('emitter.pause was not called', () => {
        assert.strictEqual(log.counts.pause, 0)
      })

      test('emitter.removeAllListeners was not called', () => {
        assert.strictEqual(log.counts.removeAllListeners, 0)
      })

      suite('array, endArray, endLine:', () => {
        setup(done => {
          log.args.on[0][1]()
          log.args.on[6][1]()
          log.args.on[11][1]()
          setImmediate(done)
        })

        test('resolve was called once', () => {
          assert.strictEqual(log.counts.resolve, 1)
        })

        test('resolve was called correctly', () => {
          assert.lengthOf(log.args.resolve[0], 1)
          assert.isArray(log.args.resolve[0][0])
          assert.lengthOf(log.args.resolve[0][0], 0)
        })

        test('emitter.pause was called once', () => {
          assert.strictEqual(log.counts.pause, 1)
        })

        test('emitter.pause was called correctly', () => {
          assert.lengthOf(log.args.pause[0], 0)
        })

        test('emitter.removeAllListeners was called once', () => {
          assert.strictEqual(log.counts.removeAllListeners, 1)
        })

        test('emitter.removeAllListeners was called correctly', () => {
          assert.lengthOf(log.args.removeAllListeners[0], 0)
        })

        test('reject was not called', () => {
          assert.strictEqual(log.counts.reject, 0)
        })

        suite('parse with ndjson:', () => {
          setup(() => {
            parse(stream, { ndjson: true })
              .then(spooks.fn({ name: 'resolve2', log: log }))
              .catch(spooks.fn({ name: 'reject2', log: log }))
          })

          test('EventEmitter.on was called twelve times', () => {
            assert.strictEqual(log.counts.on, 24)
          })

          test('walk was not called', () => {
            assert.strictEqual(log.counts.walk, 1)
          })

          suite('string, end:', () => {
            setup(done => {
              log.args.on[15][1]('foo')
              log.args.on[20][1]()
              setImmediate(done)
            })

            test('resolve was called once', () => {
              assert.strictEqual(log.counts.resolve, 1)
              assert.strictEqual(log.counts.resolve2, 1)
            })

            test('resolve was called correctly', () => {
              assert.lengthOf(log.args.resolve2[0], 1)
              assert.strictEqual(log.args.resolve2[0][0], 'foo')
            })

            test('emitter.pause was called once', () => {
              assert.strictEqual(log.counts.pause, 2)
            })

            test('emitter.removeAllListeners was called once', () => {
              assert.strictEqual(log.counts.removeAllListeners, 2)
            })

            test('reject was not called', () => {
              assert.strictEqual(log.counts.reject, 0)
              assert.strictEqual(log.counts.reject2, 0)
            })

            suite('parse with ndjson:', () => {
              setup(() => {
                parse(stream, { ndjson: true })
                  .then(spooks.fn({ name: 'resolve3', log: log }))
                  .catch(spooks.fn({ name: 'reject3', log: log }))
              })

              test('EventEmitter.on was called twelve times', () => {
                assert.strictEqual(log.counts.on, 36)
              })

              test('walk was not called', () => {
                assert.strictEqual(log.counts.walk, 1)
              })

              suite('end:', () => {
                setup(done => {
                  log.args.on[32][1]()
                  setImmediate(done)
                })

                test('resolve was called once', () => {
                  assert.strictEqual(log.counts.resolve, 1)
                  assert.strictEqual(log.counts.resolve2, 1)
                  assert.strictEqual(log.counts.resolve3, 1)
                })

                test('resolve was called correctly', () => {
                  assert.lengthOf(log.args.resolve3[0], 1)
                  assert.strictEqual(log.args.resolve3[0][0], undefined)
                })

                test('emitter.pause was called once', () => {
                  assert.strictEqual(log.counts.pause, 3)
                })

                test('emitter.removeAllListeners was called once', () => {
                  assert.strictEqual(log.counts.removeAllListeners, 3)
                })

                test('reject was not called', () => {
                  assert.strictEqual(log.counts.reject, 0)
                  assert.strictEqual(log.counts.reject2, 0)
                  assert.strictEqual(log.counts.reject3, 0)
                })
              })
            })
          })
        })

        suite('parse with ndjson and fresh stream:', () => {
          setup(() => {
            parse({}, { ndjson: true })
              .then(spooks.fn({ name: 'resolve2', log: log }))
              .catch(spooks.fn({ name: 'reject2', log: log }))
          })

          test('EventEmitter.on was called twelve times', () => {
            assert.strictEqual(log.counts.on, 24)
          })

          test('walk was called once', () => {
            assert.strictEqual(log.counts.walk, 2)
          })
        })
      })
    })
  })
})


text:
import * as responseTime from 'response-time';
import EventEmitter from 'events';
import { REQUEST_TIME } from '../metric-events';
import { IFlagResolver } from '../types/experimental';

// eslint-disable-next-line @typescript-eslint/naming-convention
const _responseTime = responseTime.default;

export function responseTimeMetrics(
    eventBus: EventEmitter,
    flagResolver: IFlagResolver,
): any {
    return _responseTime((req, res, time) => {
        const { statusCode } = res;

        const pathname = req.route ? req.baseUrl + req.route.path : '(hidden)';

        let appName;
        if (flagResolver.isEnabled('responseTimeWithAppName')) {
            appName = req.headers['unleash-appname'];
        }

        const timingInfo = {
            path: pathname,
            method: req.method,
            statusCode,
            time,
            appName,
        };
        eventBus.emit(REQUEST_TIME, timingInfo);
    });
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace SensorTag.Controls
{
    public sealed partial class CompassControl : UserControl
    {
        const double HandWidth = 10;

        public CompassControl()
        {
            this.InitializeComponent();
            this.SizeChanged += CompassControl_SizeChanged;
        }

        void CompassControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            double w = e.NewSize.Width;
            double h = e.NewSize.Height;

            // the top hand
            PathGeometry top = new PathGeometry();
            PathFigure f = new PathFigure() { StartPoint = new Point(HandWidth, 0), IsFilled = true };
            top.Figures.Add(f);
            f.Segments.Add(new LineSegment() { Point = new Point(0, h / 2) });
            f.Segments.Add(new LineSegment() { Point = new Point(-HandWidth, 0) });
            TopHand.Data = top;

            // the bottom hand
            PathGeometry bottom = new PathGeometry();
            f = new PathFigure() { StartPoint = new Point(HandWidth, 0), IsFilled = true };
            bottom.Figures.Add(f);
            f.Segments.Add(new LineSegment() { Point = new Point(0, -h / 2) });
            f.Segments.Add(new LineSegment() { Point = new Point(-HandWidth, 0) });
            BottomHand.Data = bottom;

            TranslateTransform.X = TranslateTransform.Y = h / 2;
        }

        public double Angle
        {
            get { return (double)GetValue(AngleProperty); }
            set { SetValue(AngleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Angle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AngleProperty =
            DependencyProperty.Register("Angle", typeof(double), typeof(CompassControl), new PropertyMetadata(0d, new PropertyChangedCallback(OnAngleChanged)));

        private static void OnAngleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((CompassControl)d).OnAngleChanged();
        }

        void OnAngleChanged()
        {
            RotateTransform.Angle = this.Angle;
        }

    }
}


text:
layout: post
title: 教科书级别的VHDL代码之灯控有限状态机
category: 技术
tags: VHDL
keywords: VHDL
---

## 灯控有限状态机描述:

Design a finite state machine that controls a lighting circuit.

The FSM has two control inputs - DAY and MANUAL, and two outputs - LIGHT and RED

The DAY input is from a sensor that indicates whether it is daytime (DAY =' 1') or nighttime (DAY='0').

The MANUAL signal comes from a switch that sets if LIGHT is controlled by the sensor (MANUAL='0') or if it is lit independently of the sensor (MANUAL='1') - Manual mode.

The LIGHT output turns on the light during the night or when MANUAL='1'. Otherwise, the light is off - LIGHT = '0'.

The RED output lights a red signaling lamp when MANUAL is active (RED= '1').Otherwise, RED='0'.

Design and simulate your FSM so that the light turns on every nights (DAY='0') or when MANUAL='1'. Use a Moore machine.

This is one possible solution for our problem!
In this case, the problem is solved using three states – IDLE, M_ON and S_ON.
Note: !MANUAL means NOT MANUAL or MANUAL ='0'; !DAY means NOT DAY or DAY='0'

![lightFSM](https://raw.githubusercontent.com/charlieshao5189/charlieshao5189.github.io/master/assets/pics/lightFSM.png)

In the IDLE state, LIGHT is off and the red SIGNAL is also off.

If MANUAL is switched on, then we go to state M_ON. In this state, LIGHT is on and theRED is also on, signalling that we are in MANUAL mode.

If MANUAL is switched off, then if during the day (DAY='1') we return to the IDLE state, or go to the S_ON if during the night. In the latter case, light stills on but the RED goes off, signalling that we left the Manual mode.

If MANUAL is switched off, we leave the IDLE state by nightfall and go to the S_ON state. The light is lit. If the manual switch is activated in the meanwhile, we go to the M_ON state and the RED goes on. Otherwise, at daybreak we return to the IDLE state.

### VHDL代码:

```VHDL

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity control is
    Port ( clk : in STD_LOGIC;		-- clk signal input
			  reset : in STD_LOGIC;		-- FSM reset
			  DAY : in  STD_LOGIC;		-- sensor's input
           MANUAL : in  STD_LOGIC;  -- manual control input
           LIGHT : out  STD_LOGIC;	-- light
           RED : out  STD_LOGIC);	-- warning signal
end control;

architecture Behavioral of control is

-- FSM state names
type state_type is (IDLE, S_ON, M_ON);      -- state names - IDLE - light is disable, manual control is disable
														  -- S_ON - sensor activates the light - manual control is off
														  -- M_ON - manual control is on

-- signals
signal state_reg, state_next : state_type;  -- current and next state

begin

-- state register

process (clk, reset)

begin

	if (reset='1') then
		state_reg <= IDLE;
	elsif (clk'event and clk='1') then		-- update state at the
			state_reg <= state_next;			-- rising edge of the clock
	end if;

end process;

-- next-state/output logic

process (state_reg, DAY, MANUAL)		-- determine the next state
												-- when the current state
												-- or the inputs change
begin

	case state_reg is						-- FSM description

		when IDLE =>						-- in the IDLE state -> daytime and manual mode is off

			LIGHT <= '0';					-- light is off
			RED <= '0';						-- warning signal is off

			If (MANUAL = '0' and DAY = '1') then   -- daytime and manual is disable

				state_next <= IDLE;						-- remains in the IDLE state -> light and warning signal off

			elsif MANUAL = '1' then						-- MANUAL switch is enabled

				state_next <= M_ON;						-- changes to manual mode

			else

				state_next <= S_ON;						-- night falls => changes to nighttime -> light is on

			end if;

		when S_ON =>						-- in the S_ON state -> night time and manual mode off

			LIGHT <= '1';					-- light is switched on automatically
			RED <= '0';						-- warning signal is off

			If (MANUAL = '0' and DAY = '1') then   -- sun rises and manual is disable

				state_next <= IDLE;						-- goes to the IDLE state

			elsif MANUAL = '1' then						-- manual switch is enabled

				state_next <= M_ON;						-- goes to the M_ON state

			else

				state_next <= S_ON;						-- nighttime

			end if;

		when M_ON =>							-- in the M_ON state daytime and manual mode on

			LIGHT <= '1';						-- light is on manual mode
			RED <= '1';							-- red signal is on

			If (MANUAL = '0' and DAY = '1') then    -- daytime and manual is disabled

				state_next <= IDLE;						 -- goes to the IDLE state

			elsif MANUAL = '1' then					    -- MANUAL switch is enabled

				state_next <= M_ON;						 -- remains on the M_ON state

			else

				state_next <= S_ON;							-- night falls and manual is disabled -> goes to S_ON state

			end if;

	end case;					-- end of the FSM description

end process;

end Behavioral;

```

### Simulation代码:

```VHDL

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;

ENTITY control_tb IS
END control_tb;

ARCHITECTURE behavior OF control_tb IS

    -- Component Declaration for the Unit Under Test (UUT)

    COMPONENT control
    PORT(
         clk : IN  std_logic;
			reset : IN std_logic;
         DAY : IN  std_logic;
         MANUAL : IN  std_logic;
         LIGHT : OUT  std_logic;
         RED : OUT  std_logic
        );
    END COMPONENT;

   --Inputs
   signal clk : std_logic := '0';
	signal reset : std_logic := '1';		-- initialized in the IDLE state
   signal DAY : std_logic := '1';		-- daytime automatic
   signal MANUAL : std_logic := '0';

 	--Outputs
   signal LIGHT : std_logic;
   signal RED : std_logic;

   -- Clock period definitions
   constant clk_period : time := 10 ns;

BEGIN

	-- Instantiate the Unit Under Test (UUT)
   uut: control PORT MAP (
          clk => clk,
			 reset => reset,
          DAY => DAY,
          MANUAL => MANUAL,
          LIGHT => LIGHT,
          RED => RED
        );

   -- Clock generation
   clk_process :process
   begin
		clk <= '0';
		wait for clk_period/2;
		clk <= '1';
		wait for clk_period/2;
   end process;

   -- Stimulus process
   stim_proc: process
   begin
      -- hold reset state for 100 ns.
      wait for 100 ns;

      wait for clk_period*10;

      -- insert stimulus here

		reset <= '0';			-- disable reset

		MANUAL <= '1';			-- activate manual mode while in daytime
		DAY <= '1';
		wait for 105 ns;

		MANUAL <= '1';			-- night falls
		DAY <= '0';
		wait for 105 ns;

		MANUAL <= '0';			-- disable manual mode while in night time
		DAY <= '0';
		wait for 105 ns;

		MANUAL <= '0';			-- sun rises
		DAY <= '1';
		wait for 105 ns;

		MANUAL <= '0';			-- night falls
		DAY <= '0';
		wait for 105 ns;

		MANUAL <= '1';			-- activate manual mode while in night time
		DAY <= '0';
		wait for 105 ns;

		MANUAL <= '0';			-- disable manual mode when sun rises
		DAY <= '1';
		wait for 105 ns;

		wait;

   end process;

END;

```

### Tip1:
All sequential statements are within the PROCESS block. Or in other word, all statements within PROCESS are sequential.
IF THEN, CASE and FOR LOOP三种声明方式只能用在顺序结构中,即process中,参考[More VHDL Constructs](http://web.engr.oregonstate.edu/~sllu/vhdl/lec2f.html)。

### Tip2:

```
  process (state_reg, DAY, MANUAL)		-- determine the next state
```
Process executes when there is an event on one of the signals on its sensitivity list causing events to occurs on signals that it assigns to.


text: alias nw='/Applications/node-webkit/nwjs.app/Contents/MacOS/nwjs'