text:
package hello

import (
	"html/template"
	//"io/ioutil"
	"fmt"
	"net/http"
	//"net/url"
	"strconv"
	"time"

	"appengine"
	"appengine/datastore"
	"appengine/user"
)

var (
	backendTemplate = template.Must(template.ParseFiles("backend.html"))
	addqTemplate    = template.Must(template.ParseFiles("addq.html"))
	askTemplate     = template.Must(template.ParseFiles("ask.html"))
	activeTemplate  = template.Must(template.ParseFiles("active.html"))
	resultTemplate  = template.Must(template.ParseFiles("results.html"))
	dankeTemplate   = template.Must(template.ParseFiles("danke.html"))
)

type Question struct {
	Question string
	Date     time.Time
	Choices  []string
	Active   bool
}

type Answer struct {
	Date   time.Time
	Count  []int
	Active bool
	//QKey  datastore.Key
}

type Uurl struct {
	Userid string
	Uurl   string
}

func init() {
	http.HandleFunc("/", ask)
	http.HandleFunc("/backend", backend)
	http.HandleFunc("/count", count)
	http.HandleFunc("/danke", danke)
	http.HandleFunc("/backend/active", active)
	http.HandleFunc("/backend/deactivate", deactivate)
	//http.HandleFunc("/backend/results", results)
	http.HandleFunc("/backend/addq", backend_addq)
	http.HandleFunc("/backend/saveq", backend_saveq)
	http.HandleFunc("/backend/delq", backend_delq)
	http.HandleFunc("/backend/save_new_url", be_save_new_url)
	//http.HandleFunc("/", landing)
}

func user_rootkey(ctx appengine.Context, userid string) *datastore.Key {
	return datastore.NewKey(ctx, "Question", userid, 0, nil)
}

func url_rootkey(ctx appengine.Context) *datastore.Key {
	return datastore.NewKey(ctx, "URL", "URL", 0, nil)
}

func count(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	key_str := r.FormValue("key")
	nr_str := r.FormValue("idnr")
	nr, err := strconv.ParseInt(nr_str, 10, 64)
	ctx.Debugf("%v", nr_str)
	key, err := datastore.DecodeKey(key_str)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var answer []Answer
	qu := datastore.NewQuery("Answer").Ancestor(key).Filter("Active = ", true).Limit(1)
	keys, err := qu.GetAll(ctx, &answer)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if len(answer) == 0 {
		fmt.Fprint(w, "no Answer")
		return
	}

	answer[0].Count[nr-1] += 1
	ctx.Debugf("%v", answer[0].Count[nr-1])

	_, err = datastore.Put(ctx, keys[0], &answer[0])
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Location", "/danke")
	w.WriteHeader(http.StatusFound)
	return

}

func active(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	key_str := r.FormValue("key")
	key, err := datastore.DecodeKey(key_str)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	e := new(Question)
	err = datastore.Get(ctx, key, e)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	e.Active = true
	_, err = datastore.Put(ctx, key, e)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	url_rk := url_rootkey(ctx)
	var uid []Uurl
	qu := datastore.NewQuery("URL").Ancestor(url_rk).Filter("Userid = ", u.ID).Limit(1)
	_, err = qu.GetAll(ctx, &uid)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if len(uid) == 0 {
		fmt.Fprint(w, "no URL")
		return
	}
	answer := new(Answer)
	answer.Date = time.Now()
	arr := make([]int, 5)
	ctx.Debugf("%v", arr)
	answer.Count = arr
	answer.Active = true
	//answer.QKey = *key
	//root_key := datastore.NewKey(ctx, "Answer", u.ID, 0, nil)
	na_key := datastore.NewIncompleteKey(ctx, "Answer", key)
	a_key, err := datastore.Put(ctx, na_key, answer)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	//ctx.Debugf(r.URL.Host)

	data := struct {
		Url      string
		Key_a    string
		Key      string
		Myurl    string
		Myurlraw string
	}{
		uid[0].Uurl,
		a_key.Encode(),
		key_str,
		r.URL.Host + uid[0].Uurl, //url.QueryEscape(r.URL.Host + uid[0].Uurl),
		r.URL.Host + uid[0].Uurl,
	}

	err = activeTemplate.Execute(w, data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

}

func deactivate(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	//u := user.Current(ctx)
	key_str := r.FormValue("key")
	keya_str := r.FormValue("keya")
	key, err := datastore.DecodeKey(key_str)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	keya, err := datastore.DecodeKey(keya_str)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	e := new(Question)
	err = datastore.Get(ctx, key, e)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	e.Active = false
	_, err = datastore.Put(ctx, key, e)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	a := new(Answer)
	err = datastore.Get(ctx, keya, a)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	a.Active = false
	_, err = datastore.Put(ctx, keya, a)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	type As struct {
		A string
		P int
	}

	as := make([]As, 5)
	for i := 0; i < 5; i++ {
		as[i].A = e.Choices[i]
		as[i].P = a.Count[i]
		//ctx.Debugf("%v", as[i].Nr)
	}

	data := struct {
		Q   string
		Aws []As
	}{
		e.Question,
		as,
	}

	err = resultTemplate.Execute(w, data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

}

func ask(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	url_rk := url_rootkey(ctx)
	var uurl []Uurl
	q := datastore.NewQuery("URL").Ancestor(url_rk).Filter("Uurl = ", r.URL.Path).Limit(1)
	q.GetAll(ctx, &uurl)

	if len(uurl) == 0 {
		fmt.Fprint(w, "nothing here")
		return
	}
	user_rk := user_rootkey(ctx, uurl[0].Userid)
	var question []Question
	qu := datastore.NewQuery("Question").Ancestor(user_rk).Filter("Active = ", true).Limit(1)
	keys, err := qu.GetAll(ctx, &question)
	if len(question) == 0 {
		fmt.Fprint(w, "no active question")
		return
	}

	type As struct {
		Ans string
		Nr  string
	}

	as := make([]As, 0, 5)
	var a As
	for i := 0; i < len(question[0].Choices); i++ {

		a.Ans = question[0].Choices[i]
		a.Nr = strconv.Itoa(i + 1)
		if len(a.Ans) > 0 {
			as = append(as, a)
			ctx.Debugf("%v", len(as))
		}
	}

	data := struct {
		Question string
		Choices  []As
		Key      string
	}{
		question[0].Question,
		as,
		keys[0].Encode(),
	}

	err = askTemplate.Execute(w, data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

func backend_saveq(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)

	rootkey := user_rootkey(ctx, u.ID)

	if r.FormValue("q") != "" {
		key := datastore.NewIncompleteKey(ctx, "Question", rootkey)
		var q Question
		q.Question = r.FormValue("q")
		q.Date = time.Now()
		a := make([]string, 5)
		for i := 0; i < 5; i++ {
			a[i] = r.FormValue("c" + strconv.Itoa(i))

		}
		q.Active = false
		q.Choices = a

		_, err := datastore.Put(ctx, key, &q)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	w.Header().Set("Location", "/backend")
	w.WriteHeader(http.StatusFound)
	return
}

func danke(w http.ResponseWriter, r *http.Request) {

	data := struct {
		danke string
	}{
		"test",
	}

	err := dankeTemplate.Execute(w, data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

func backend_addq(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	//count, _ := strconv.Atoi(r.FormValue("count"))
	//rootkey := user_rootkey(ctx, u.ID)

	data := struct {
		User string
		Id   string
	}{
		u.Email,
		u.ID,
	}

	err := addqTemplate.Execute(w, data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

func backend_delq(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	key_str := r.FormValue("key")
	key, err := datastore.DecodeKey(key_str)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = datastore.Delete(ctx, key)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Location", "/backend")
	w.WriteHeader(http.StatusFound)
	return
}

func be_save_new_url(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	url_rk := url_rootkey(ctx)
	ctx.Debugf(r.FormValue("url"))
	var uid []Uurl
	qu := datastore.NewQuery("URL").Ancestor(url_rk).Filter("Uurl = ", r.FormValue("url")).Limit(1)
	_, err := qu.GetAll(ctx, &uid)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if len(uid) == 0 {
		key := datastore.NewIncompleteKey(ctx, "URL", url_rk)
		var uid2 Uurl
		uid2.Userid = u.ID
		uid2.Uurl = "/" + r.FormValue("url")
		_, err := datastore.Put(ctx, key, &uid2)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", "/backend")
		w.WriteHeader(http.StatusFound)
		return
	} else {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Error(w, err.Error(), http.StatusInternalServerError)
	return
}

func backend(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := user.Current(ctx)
	if u == nil {
		url, err := user.LoginURL(ctx, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	// Prüfen ob der User schon eine URL fuer Fragen hat
	url_rk := url_rootkey(ctx)
	var uid []Uurl  // Array aus Uurl structs deklarieren
	qu := datastore.NewQuery("URL").Ancestor(url_rk).Filter("Userid = ", u.ID).Limit(1)
	keys, err := qu.GetAll(ctx, &uid) // Die Adresse des Uurl structs uebergeben

	// Wenn Fehler beim Daten holen, 500er Fehler anzeigen
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Wenn es zu diesem User einen Eintrag gibt, die URL in uid_out speichern
	var uid_out string
	if len(uid) > 0 {
		uid_out = uid[0].Uurl
	}

	// Alle Fragen zu diesem User aus dem Datastore holen
	rootkey := user_rootkey(ctx, u.ID)
	q := datastore.NewQuery("Question").Ancestor(rootkey).Order("-Date")
	var questions []Question
	keys, err = q.GetAll(ctx, &questions)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	type Qs struct {
		Question string
		Date     string
		Key      string
		Active   bool
	}

	qs := make([]Qs, len(keys)) // Slice vom struct Qs erzeugen
	for i := 0; i < len(keys); i++ {
		qs[i].Question = questions[i].Question
		qs[i].Date = questions[i].Date.Format("2006-01-02 15:04")
		qs[i].Key = keys[i].Encode()
		qs[i].Active = questions[i].Active
	}

	lo_url, _ := user.LogoutURL(ctx, "/backend")
	//rootkey := user_rootkey(ctx, u.ID)

	// Struct fuer die Uebergabe an die Templating Engine erzeugen
	data := struct {
		User      string
		Questions *[]Qs
		Lo_url    string
		Uurl      string
	}{
		u.Email,
		&qs,     // Die Adresse des Qs Slice
		lo_url,
		uid_out,
	}

	err = backendTemplate.Execute(w, data)   // Template rendern
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}


text:
package org.jetbrains.plugins.groovy.annotator.intentions;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause;

/**
 * @author Max Medvedev
 */
public class ReplaceDelimiterFix extends Intention {
  @NotNull
  @Override
  public String getText() {
    return "Replace ':' with 'in'";
  }

  @NotNull
  @Override
  public String getFamilyName() {
    return "Replace for-each operator";
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return true;
  }

  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
    final PsiFile file = element.getContainingFile();
    PsiElement at = file.findElementAt(editor.getCaretModel().getOffset());
    GrForStatement forStatement = PsiTreeUtil.getParentOfType(at, GrForStatement.class);
    if (forStatement == null) return;
    GrForClause clause = forStatement.getClause();
    if (clause instanceof GrForInClause) {
      GroovyFile f = GroovyPsiElementFactory.getInstance(project).createGroovyFile("in", false, null);
      PsiElement child = f.getFirstChild().getFirstChild();
      PsiElement delimiter = ((GrForInClause)clause).getDelimiter();
      delimiter.replace(child);
    }
  }

  @NotNull
  @Override
  protected PsiElementPredicate getElementPredicate() {
    return new PsiElementPredicate() {
      @Override
      public boolean satisfiedBy(PsiElement element) {
        return true;
      }
    };
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }
}

redpajama_set_name: RedPajamaGithub


text:
Meteor.publish('livechat:departmentAgents', function(departmentId) {
	if (!this.userId) {
		return this.error(new Meteor.Error('error-not-authorized', 'Not authorized', { publish: 'livechat:departmentAgents' }));
	}

	if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-rooms')) {
		return this.error(new Meteor.Error('error-not-authorized', 'Not authorized', { publish: 'livechat:departmentAgents' }));
	}

	return RocketChat.models.LivechatDepartmentAgents.find({ departmentId: departmentId });
});


text:
import SecFromTime = require('../2015/SecFromTime');
export = SecFromTime;


text:
.. _bundle_couchdb:

CouchDB Integration
===================

This bundle provides two features:

1. A Thread local isntance of a server bound to the URL of your choosing.
2. A proxy to that Couch instance

Using CouchDB
-------------

To use the couchdb bundle add its setup function during application setup,
like so::

    from glashammer.bundles.couchdbdb import setup_couchdb

    def setup_app(app):
        app.add_setup(setup_couchdb)

This will add the bundle using the default url of `http://localhost:5984`,
and a mount pioint of `/couch` for the proxy. These default values can be
overridden on adding the setup function, and later overriden by configuration
variables::

    from glashammer.bundles.couchdbdb import setup_couchdb

    def setup_app(app):
        app.add_setup(setup_couchdb, 'http://localhost:5984', '/couchdb')

Using the server instance
-------------------------

The server instance is available to the request on the thread local instance
as the by calling the :func:`get_couchdb_server` function::

    from glashammer.bundles.couchdbdb import get_couchdb_server

    def my_view(req):
        # Get the server instance
        server = get_couchdb_server()

        # Now do something with it
        server.create('my_db')

Bundle cheat-sheet
------------------

Endpoints:
    `couchdb/proxy` For making proxy calls to the couchdb isntance

Configuration Variables:
    * `couchdb/server_url` - The couchdb server's URL
    * `couchdb/mount_path` - The path to the couchdb proxy

API:

.. autofunction:: glashammer.bundles.couchdbdb.get_couchdb_server

Setup callable arguments:

.. autofunction:: glashammer.bundles.couchdbdb.setup_couchdb


text:
<?php

namespace Symfony\Component\HttpKernel\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\Util\ValueExporter;
use Symfony\Component\VarDumper\Caster\ClassStub;
use Symfony\Component\VarDumper\Cloner\ClonerInterface;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Cloner\VarCloner;

/**
 * DataCollector.
 *
 * Children of this class must store the collected data in the data property.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Bernhard Schussek <bschussek@symfony.com>
 */
abstract class DataCollector implements DataCollectorInterface, \Serializable
{
    protected $data = array();

    /**
     * @var ValueExporter
     */
    private $valueExporter;

    /**
     * @var ClonerInterface
     */
    private static $cloner;

    private static $stubsCache = array();

    public function serialize()
    {
        return serialize($this->data);
    }

    public function unserialize($data)
    {
        $this->data = unserialize($data);
    }

    /**
     * Converts the variable into a serializable Data instance.
     *
     * This array can be displayed in the template using
     * the VarDumper component.
     *
     * @param mixed $var
     *
     * @return Data
     */
    protected function cloneVar($var)
    {
        if (null === self::$cloner) {
            if (class_exists(ClassStub::class)) {
                self::$cloner = new VarCloner();
                self::$cloner->setMaxItems(-1);
            } else {
                @trigger_error(sprintf('Using the %s() method without the VarDumper component is deprecated since version 3.2 and won\'t be supported in 4.0. Install symfony/var-dumper version 3.2 or above.', __METHOD__), E_USER_DEPRECATED);
                self::$cloner = false;
            }
        }
        if (false === self::$cloner) {
            if (null === $this->valueExporter) {
                $this->valueExporter = new ValueExporter();
            }

            return $this->valueExporter->exportValue($var);
        }

        return self::$cloner->cloneVar($var);
    }

    /**
     * Converts a PHP variable to a string.
     *
     * @param mixed $var A PHP variable
     *
     * @return string The string representation of the variable
     *
     * @deprecated since version 3.2, to be removed in 4.0. Use cloneVar() instead.
     */
    protected function varToString($var)
    {
        @trigger_error(sprintf('The %s() method is deprecated since version 3.2 and will be removed in 4.0. Use cloneVar() instead.', __METHOD__), E_USER_DEPRECATED);

        if (null === $this->valueExporter) {
            $this->valueExporter = new ValueExporter();
        }

        return $this->valueExporter->exportValue($var);
    }
}


text:
+---------+-------------------+
| liver   | R Documentation   |
+---------+-------------------+

Liver related laboratory data
-----------------------------

Description
~~~~~~~~~~~

Liver related laboratory data from a randomized, blind, parallel group
clinical trial with 4 doses of a drug.

Usage
~~~~~

::

    data(liver)

Format
~~~~~~

A data frame with 606 observations on the following 9 variables.

``ALP.B``
    Alkaline phosphatase at baseline. A numeric vector.

``ALT.B``
    Alanine aminotransferase at baseline. A numeric vector.

``AST.B``
    Aspartate aminotransferase at baseline. A numeric vector.

``TBL.B``
    Total bilirubin at baseline. A numeric vector.

``ALP.M``
    Alkaline phosphatase after treatment. A numeric vector.

``ALT.M``
    Alanine aminotransferase after treatment. A numeric vector.

``AST.M``
    Aspartate aminotransferase after treatment. A numeric vector.

``TBL.M``
    Total bilirubin after treatment. A numeric vector.

``dose``
    The treatment group (i.e. dose group). A factor with levels ``A``
    ``B`` ``C`` ``D``

Details
~~~~~~~

Dose A is the lowest dose, dose, B the next, C the next, and D the
highest dose. The baseline values were taken prior to any treatment
being received, and the clinical trial had a single post-baseline visit.

Source
~~~~~~

AstraZeneca data on file.


text:
<img src="./screenshot.png" width="80%" height="80%">

### Command Line Arguments
```
Simple HTTP(s) Server 0.6.3

USAGE:
    simple-http-server [FLAGS] [OPTIONS] [--] [root]

FLAGS:
        --coep       Add "Cross-Origin-Embedder-Policy" HTTP header and set it to "require-corp"
        --coop       Add "Cross-Origin-Opener-Policy" HTTP header and set it to "same-origin"
        --cors       Enable CORS via the "Access-Control-Allow-Origin" header
    -h, --help       Prints help information
    -i, --index      Enable automatic render index page [index.html, index.htm]
        --nocache    Disable http cache
        --norange    Disable header::Range support (partial request)
        --nosort     Disable directory entries sort (by: name, modified, size)
    -s, --silent     Disable all outputs
    -u, --upload     Enable upload files (multiple select) (CSRF token required)
    -V, --version    Prints version information

OPTIONS:
    -a, --auth <auth>                              HTTP Basic Auth (username:password)
        --cert <cert>                              TLS/SSL certificate (pkcs#12 format)
        --certpass <certpass>                      TLS/SSL certificate password
    -c, --compress <compress>...
            Enable file compression: gzip/deflate
                Example: -c=js,d.ts
                Note: disabled on partial request!
        --ip <ip>                                  IP address to bind [default: 0.0.0.0]
    -p, --port <port>                              Port number [default: 8000]
        --redirect <redirect>                      takes a URL to redirect to using HTTP 301 Moved Permanently
    -t, --threads <threads>                        How many worker threads [default: 3]
        --try-file <PATH>
            serve this file (server root relative) in place of missing files (useful for single page apps) [aliases:
            try-file-404]
    -l, --upload-size-limit <upload_size_limit>    Upload file size limit [bytes] [default: 8000000]

```

# Installation

### Download binary
[Goto Download](https://github.com/TheWaWaR/simple-http-server/releases)

 - windows-64bit
 - osx-64bit
 - linux-64bit

### Install by cargo

``` bash
# Install Rust
curl https://sh.rustup.rs -sSf | sh

# Install simple-http-server
cargo install simple-http-server
rehash
simple-http-server -h
```

# Features
- [x] Windows support (with colored log)
- [x] Specify listen address (ip, port)
- [x] Specify running threads
- [x] Specify root directory
- [x] Pretty log
- [x] Nginx like directory view (directory entries, link, filesize, modfiled date)
- [x] Breadcrumb navigation
- [x] (default enabled) Guess mime type
- [x] (default enabled) HTTP cache control
  - Sending Last-Modified / ETag
  - Replying 304 to If-Modified-Since
- [x] (default enabled) Partial request
  - Accept-Ranges: bytes([ByteRangeSpec; length=1])
  - [Range, If-Range, If-Match] => [Content-Range, 206, 416]
- [x] (default disabled) Automatic render index page [index.html, index.htm]
- [x] (default disabled) Upload file
  - A CSRF token is generated when upload is enabled and must be sent as a parameter when uploading a file
- [x] (default disabled) HTTP Basic Authentication (by username:password)
- [x] Sort by: filename, filesize, modifled
- [x] HTTPS support
- [x] Content-Encoding: gzip/deflate
- [x] Added CORS headers support
- [x] Silent mode


text:
package org.apache.eagle.common;

public enum Environment {
	dev,
	test,
	prod,
}


text:
class StepsController < ApplicationController

  before_filter :get_global_variables
  before_filter :authenticate_user!, except: [:index, :show, :show_redirect, :mobile]
  before_filter :check_tree_width, only: :mobile

  # :get_project defined at bottom of the file,
  # and takes the project_id given by the routing
  # and converts it to a @project object

  # GET /steps
  # GET /steps.json
  def index
    authorize! :read, @project
    @stepIDs = @project.steps.not_labels.order("published_on").pluck(:id)

    # fix step position and ancestry if there's an error
    if @project.steps.where(:position => -1).present?
      Rails.logger.info("FIXING STEP POSITIONS AND ANCESTRY")
      start_position = @project.steps.order(:position).last.position
      @project.steps.where(:position => -1).order("created_at").each do |step|
        last_step = @project.steps.where(:position => start_position).first
        step.update_attributes(:ancestry => last_step.ancestry + "/" + last_step.id.to_s)
        step.update_attributes(:position => start_position+1)
        start_position = start_position + 1
      end
    end

    respond_to do |format|
      # go directly to the project overview page
      format.html
      format.json
      format.xml
    end
  end

  # GET /steps/mobile
  def mobile
    @stepIDs = @project.steps.not_labels.order("published_on").pluck(:id)
    respond_to do |format|
        format.html{
           if @project.users.include?(User.where(:authentication_token => params[:auth_token]).first)  || (current_user && @project.users.include?(current_user)) || (current_user && current_user.admin?)
           else
            redirect_to errors_unauthorized_path
           end
        }
    end
  end

  # GET /steps/1
  # GET /steps/1.json
  def show
    authorize! :read, @project
    @step = @project.steps.find_by_position(params[:id])
    @images = @project.images.where("step_id=?", @step.id).order("position")

    respond_to do |format|
      format.html
      format.json
      format.xml
    end
  end

  def new
    begin
      @step = @project.steps.build(:parent_id=> params[:parent_id].to_i)
    rescue Exception
      @step = @project.steps.build
    end

    authorize! :create, @step
    @step.build_question

    if params[:label] == "false"
      @step.name = "New Step"
      @step.description = " "
    else
      @step.name = "New Branch Label"
    end

    @step.id = "-1"
    @parentID = params[:parent_id]
    Rails.logger.debug("@parentID: #{@parentID}")
    @step.user_id = current_user.id

    respond_to do |format|
      format.html
      format.json { render :json => @step }
    end
  end

  # GET /steps/1/edit
  def edit
      @step = @project.steps.find_by_position(params[:id])
      authorize! :edit, @step

      if @step.question
        question = @step.question
      else
        question = @step.build_question
      end

      if question && !question.decision
        decision = question.build_decision
        decision.description = "I decided to ..."
      end

      # update edits with started editing at time
      if Edit.where("user_id = ? AND step_id = ?", current_user.id, @step.id).first
        # user already exists in the step users
        Edit.where("user_id = ? AND step_id = ?", current_user.id, @step.id).first.update_attributes(:started_editing_at => Time.now)
      elsif @project.users.include?(current_user) && !@step.users.include?(current_user)
        # create edit for newly added author that is editing an existing step
        Edit.create(:user_id => current_user.id, :project_id => @project.id, :step_id => @step.id, :started_editing_at => Time.now, :temp => true)
      end

      authorize! :update, @step
      @step.images.build if @step.images.empty?
      @images = @project.images.where("step_id=?", @step.id).order("position")
      @step.design_files.build if @step.design_files.empty?
    end

  # POST /steps
  # POST /steps.json
  def create

    # ensure that the submitted parent_id actually exists
    if !Step.exists?(params[:step][:parent_id].to_i)
      logger.debug "Step doesn't exist!"
      if @project.steps.last
        params[:step][:parent_id] = @project.steps.last.id
      else
        params[:step][:parent_id] = nil
      end
    end

    if params[:step][:pin] && params[:step][:pin].empty?
      params[:step][:pin] = nil
    end

    @step = @project.steps.build(params[:step])
    authorize! :create, @step

    if params[:step][:position]
      @step.position = params[:step][:position]
    else
      @step.position = @numSteps
    end

    respond_to do |format|
      if @step.save

       # update corresponding collections
        @step.project.collections.each do |collection|
          collection.touch
        end

         # create an edit entry
         Edit.create(:user_id => current_user.id, :step_id => @step.id, :project_id => @project.id)

        # check whether project is published
        if @project.public? || @project.privacy.blank?
          @project.set_published(current_user.id, @project.id, @step.id)
        end

        @project.set_built

        # update the project updated_at date
        @project.touch

        # update the user last_updated_at date
        current_user.touch

        @step.update_attributes(:published_on => @step.created_at)

        # create a public activity for any added question
        if @step.question
          Rails.logger.debug("created new question")
          @step.question.create_activity :create, owner: current_user, primary: true
        end

        # log the creation of a new step
        @project.delay.log

        format.html {

          # update all images with new step id
          new_step_images = @project.images.where("step_id = -1")
          new_step_images.each do |image|
            image.update_attributes(:saved => true)
            image.update_attributes(:step_id => @step.id)
          end

          # update all videos with new step id
          new_step_videos = @project.videos.where("step_id = -1")
          new_step_videos.each do |video|
            video.update_attributes(:saved=>true)
            video.update_attributes(:step_id=> @step.id)
          end

          # push project to village if it doesn't already exist
          if @project.village_id.blank? && current_user.from_village? && @project.public? && !access_token.blank?
            create_village_project
          elsif !@project.village_id.blank? && !access_token.blank?
            update_village_project
          end

          redirect_to project_steps_path(@project), :flash=>{:createdStep => @step.id}

        }

        format.json { render :json => @step }
      else
        Rails.logger.debug(@step.errors.inspect)
        format.html { render :action => "new" }
        format.json { render :json => @step.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /steps/1
  # PUT /steps/1.json
  def update
    @step = @project.steps.find_by_position(params[:id])
    authorize! :update, @step

    # update corresponding collections
    @step.project.collections.each do |collection|
      collection.touch
    end

    @step.images.each do |image|
      image.update_attributes(:saved => true)
    end

    # remove question if question description is empty
    if params[:step][:question_attributes] && params[:step][:question_attributes][:description].length == 0 && @step.question
      @step.question.destroy
    end

    if params[:step][:published_on_date]
      date = params[:step][:published_on_date]
      logger.debug "date: #{date}"
      time = params[:step][:published_on_time]
      # retain the same seconds as the original published_on date
      time.insert 5, ":" + @step.published_on.strftime("%S")
      # logger.debug "time: #{time}"
      timeZone = params[:step][:timeZone]
      # logger.debug "timeZone: #{timeZone}"
      dateTime = date + " " + time + " " + timeZone
      # logger.debug "dateTime: #{dateTime}"
      dateTime = DateTime.strptime(dateTime, '%m/%d/%Y %I:%M:%S %p %Z')
      # logger.debug "datetime: #{dateTime}"

      params[:step][:published_on] = dateTime
      params[:step].delete :'published_on_date'
      params[:step].delete :"published_on_time"
      params[:step].delete :timeZone
    end

    # update the project
    @project.touch

    # update the user last updated date
    current_user.touch

    # remove any design attributes if they contain an ID that doesn't exist (the file had been removed)
    if params[:step][:design_files_attributes]
      params[:step][:design_files_attributes].values.each do |design_file|
        if DesignFile.exists?(design_file['id']) == false
          design_file.delete :id
        end
      end
    end

    respond_to do |format|

      if @step.update_attributes(params[:step])

        # clear label color if user didn't select color
        if @step.label == false
          @step.update_column("label_color", nil)
        end

        # clear edit
        edit = Edit.where("user_id = ? AND step_id = ?", current_user.id, @step.id).first
        edit.update_attributes(:started_editing_at => nil)
        if edit.project_id.blank?
          edit.update_attributes(:project_id => @project.id)
        end

        # check whether project is published
        if @project.public? || @project.privacy.blank?
          @project.set_published(current_user.id, @project.id, @step.id)
        end

        # check and set built attribute of project
        @project.set_built

        # create a public activity for any questions associated with the step if it doesn't already exist
        if @step.question && !PublicActivity::Activity.where(:trackable_type => "Question").where(:trackable_id => @step.question.id).exists?
          @step.question.create_activity :create, owner: current_user, primary: true
        end

        # create project on the village if the current user is a village user and the project doesn't already exist
        if @project.village_id.blank? && current_user.from_village? && !access_token.blank? && @project.public?
          create_village_project
        elsif !@project.village_id.blank? && !access_token.blank?
          update_village_project
        end

        format.html {
            redirect_to project_steps_path(@project), :notice => 'Step was successfully updated.', :flash => {:createdStep => @step.id}
        }
        format.json { head :no_content }
      else
        Rails.logger.info(@step.errors.inspect)
        format.html { render :action => "edit" }
        format.json { render :json => @step.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /steps/1
  # DELETE /steps/1.json
  def destroy
    @step = Step.find(params[:step_id])
    authorize! :destroy, @step

    if @step.ancestry=="0" && @project.steps.where(:ancestry => @step.id.to_s).length > 1
      # can't delete root!
      respond_to do |format|
        format.html {
          flash[:error] = "Can't delete the root of your project!"
          redirect_to project_steps_url
        }
      end
    else
      if @step.ancestry == "0"
        @project.steps.where("id !=?", @step.id.to_s).each do |step|
          if step.ancestry == @step.id.to_s
            step.update_attributes(:ancestry => "0")
          else
            step.update_attributes(:ancestry => step.ancestry.gsub(@step.id.to_s+"/", ""))
          end
        end
      end

      PublicActivity::Activity.where(:trackable_id => @step.id).destroy_all
      if @step.question
        PublicActivity::Activity.where(:trackable_id => @step.question.id).destroy_all
      end

      # destroy any news items associated with it
      News.where(:step_id => @step.id).each do |news_item|
        news_item.destroy
      end

      @step.destroy

      # update positions of subsequent steps
      if @step.position < @steps.count
        for step in @step.position+1..@steps.count
          if @steps.where("position" => step).exists?
            @steps.where("position" => step)[0].update_attribute(:position, step-1)
          end
        end
      end

      # check whether project is published
      if @project.public?
        @project.set_published(current_user.id, @project.id, nil)
      end

      # check and set built attribute of project
      @project.set_built

      @project.delay.log

      respond_to do |format|
        format.html { redirect_to project_steps_url }
        format.json { head :no_content }
      end
    end
  end

  # Destroy new images
  def destroyNewImages
     respond_to do |format|
        format.html { redirect_to project_steps_url }
      end
  end

  # Sorts steps
  def sort
    params[:step].each_with_index do |id, index|
      Step.update_all({position: index+1}, {id: id})
    end
    render nothing: true
  end

  def create_branch
    @parentStepID = params[:parent]
    @project = Step.find(@parentStepID).project
    authorize! :create_branch, @project
    @label = params[:label]
    respond_to do |format|
      format.js { render :js => "window.location = '#{new_project_step_path(@project, :parent_id=>@parentStepID, :label => @label)}'"}
    end
  end

  # redirect to the edit page for a particular step - called from clicking a step in the
  # process map while already on the edit page for another step
  def edit_redirect
    @stepID = params[:stepID]
    step = Step.find(@stepID)
    @stepPosition = @steps.where("id"=>@stepID).first.position

    if params[:answered]
      answered = true
    end

    Rails.logger.info('checking editing conflict')

    # check if someone else is editing the step
    editing_conflict = false
    editing_conflict_user = ""
    step.edits.pluck(:started_editing_at).each do |edit_date|
      if edit_date != nil && step.edits.where(:started_editing_at => edit_date).first.user != current_user
        editing_conflict = true
        editing_conflict_user = editing_conflict_user + step.edits.where(:started_editing_at => edit_date).first.user.username
      end
    end
    Rails.logger.info('editing_conflict_user: ' + editing_conflict_user)

    respond_to do |format|
      format.js {
        if !editing_conflict
          render :js => "window.location='#{edit_project_step_path(@project, @stepPosition)}?answered=#{answered}'"
        else
          render :json => editing_conflict_user
        end
      }
    end
  end

  # redirect to the show page for a particular step
  def show_redirect
    @stepID = params[:stepID]
    @step = @steps.where("id"=>@stepID).first
    if @step.present?
      @stepPosition = @step.position
      respond_to do |format|
        format.js { render :js => "window.location = '#{project_step_path(@project, @stepPosition)}'"}
      end
    else
      respond_to do |format|
        format.js { render :nothing => true}
      end
    end
  end

  # get the position of a step (used for redirecting to edit / show step pages)
  def get_position
    @step = Step.find(params[:stepID])
    if @step
      position = @step.position
    end
    respond_to do |format|
      format.js{
        render :js => position
      }
    end
  end

  # update_ancestry: given an array of the steps in a project, update the position and ancestry of all steps
  # the expected format is {step_id: [position,ancestry]}
  def update_ancestry
    Step.record_timestamps = false
    steps = params[:stepMapArray]

    # Rails.logger.debug("steps: #{steps}")
    steps.each do |step|
      id = step[0].to_i
      position = step[1][0].to_i
      ancestry = step[1][1]

      # Rails.logger.debug("id: #{step[0]} position: #{step[1][0]} ancestry: #{step[1][1]}")
      if Step.exists?(:id => id)
          Step.find(id).update_attributes(:position => position)
          Step.find(id).update_attributes(:ancestry => ancestry)
      end
    end

    Step.record_timestamps = true
    respond_to do |format|
      format.js {render :nothing => true}
    end
  end

  # reset the started_editing_at attribute of an edit table if a user presses the back button
  # out of a step form
  def reset_started_editing
    logger.debug 'in reset started editing'
    user_id = params[:user_id]
    step_id = params[:step_id]
    @project = Project.find(params[:project_id])
    edit = Edit.where("user_id = ? AND step_id = ?", user_id, step_id).first

    # if edit was temp, destroy the edit
    if edit
      if edit.temp
        edit.destroy
      else
        edit.reset_started_editing_at
      end
    end

    respond_to do |format|
      format.js { render :nothing => true }
    end

  end

  # create a project on the village using an iframe with the embed page
  def create_village_project
    iframe_src = "
This project created with #{ENV["APP_NAME"]} and updated on " + @project.updated_at.strftime("%A, %B %-d at %-I:%M %p") +"
"
    iframe_src = iframe_src.html_safe.to_str
    village_user_ids = @project.village_user_ids
    response = access_token.post("/api/projects", params: {project: {name: @project.title, project_type_id: 15, source: "original", description: iframe_src, thumbnail_file_id: 769508, user_ids: village_user_ids} })
    village_project_id = response.parsed["project"]["id"]
    @project.update_attributes(:village_id => village_project_id)
  end

  # update a project on the village
  def update_village_project
    iframe_src = "
This project created with #{ENV["APP_NAME"]} and updated on " + @project.updated_at.strftime("%A, %B %-d at %-I:%M %p") +"
"
    iframe_src = iframe_src.html_safe.to_str
    village_user_ids = @project.village_user_ids
    response = access_token.put("/api/projects/" + @project.village_id.to_s, params: {project: {name: @project.title, description: iframe_src, user_ids: village_user_ids}})
  end

  private

  # get_project converts the project_id given by the routing
  # into an @project object
  def get_global_variables
    @project = Project.where(:id => params[:project_id])
    if @project.present?
      @project = @project.first
      @steps = @project.steps.order("position")
      @numSteps = @steps.count
      @ancestry = @steps.pluck(:ancestry) # array of ancestry ids for all steps
      @allBranches # variable for storing the tree structure of the process map
      @users = @project.users # user who created the project
      @authorLoggedIn = user_signed_in? && @users.map(&:username).include?(current_user.username)
    else
      # redirect to error page - project no longer exists
      render :file => "errors/404.html",  :status => 404
    end
  end

  def check_tree_width
    redirect_to(tree_width: @project.tree_width, auth_token: params[:auth_token]) unless params[:tree_width].present?
  end

end


text:
using namespace std;

class Room;

class Map
{
public:
	Map(string mapfile);
	virtual ~Map();

	bool faceWall(double global_x_mm, double global_y_mm, double theta_rad);

	void print(void);
	void printEachRoom(void);
private:
	vector<bool> m_horizontal;
	vector<bool> m_vertical;

	vector<Room> m_rooms;

	int m_x_room_num;
	int m_y_room_num;
};

#endif


text:
module ActiveEncode
  # == Active Encode adapters
  #
  # Active Encode has adapters for the following engines:
  #
  #
  #
  module EngineAdapters
    extend ActiveSupport::Autoload

    autoload :MatterhornAdapter
    autoload :ZencoderAdapter
    autoload :ElasticTranscoderAdapter
    autoload :TestAdapter
    autoload :FfmpegAdapter
    autoload :PassThroughAdapter

    ADAPTER = 'Adapter'
    private_constant :ADAPTER

    class << self
      def lookup(name)
        const_get(name.to_s.camelize << ADAPTER)
      end
    end
  end
end


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

namespace Repsaj.Submerged.Infrastructure.Models
{
    /// <summary>
    /// A type that provides metadata related to a Device's property.
    /// </summary>
    public class DevicePropertyMetadata
    {
        /// <summary>
        /// Gets or sets a value that indicates whether the property is
        /// displayed for Registered Devices.
        /// </summary>
        public bool IsDisplayedForRegisteredDevices
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value that indicates whether the property is
        /// displayed for Unregistered Devices.
        /// </summary>
        public bool IsDisplayedForUnregisteredDevices
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value that indicates whether the property is
        /// user-editable.
        /// </summary>
        public bool IsEditable
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the described property's name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the descriped property's <see cref="PropertyType" />.
        /// </summary>
        public PropertyType PropertyType
        {
            get;
            set;
        }
    }
}


text:
/***************************************************************
 * Definições do tipo cggl::Input
 *
 * (c) Carlos Guedes e José Branco - Novembro de 2007
 ***************************************************************/
#include "Input.h"

namespace cggl {

  Input::Input() {
    for(int i = 0; i < CGGL_INPUT_MAX_KEYS; ++i) {
      asciiKeys[i] = false;
      specialKeys[i] = false;
    }
  }

  void Input::PressKey(unsigned char k) {
    asciiKeys[k] = true;
  }

  void Input::ReleaseKey(unsigned char k) {
    asciiKeys[k] = false;
  }

  int  Input::IsKeyPressed(unsigned char k) {
    return (asciiKeys[k] == true);
  }

  void Input::PressSpecialKey(int k) {
	specialKeys[k] = true;
  }

  void Input::ReleaseSpecialKey(int k) {
    specialKeys[k] = false;
  }

  int  Input::IsSpecialKeyPressed(int k) {
    return (specialKeys[k] == true);
  }

}


text:
<?php

use Luminary\Exceptions\Presenters\DefaultPresenter;

class ExceptionDefaultPresenterTest extends TestCase
{
    /**
     * Check that the default presenter returns
     * correct data
     *
     * @return void
     */
    public function testDefaultPresenter() :void
    {
        $e = new Exception('this is a default exception', 404);
        $response = (new DefaultPresenter($e))->response();
        $expected = [[
            'status' => 404,
            'title' => 'An unknown error has occurred',
            'detail' => 'this is a default exception'
        ]];

        $this->assertEquals($expected, $response);
    }
}


text:
include_recipe 'fake::ruby_install'

rbenv_gem 'bundler' do
  ruby_version node['fake']['ruby_version']
  version '1.3.5'
end


text:
..
..
.. Licensed under the Apache License, Version 2.0 (the "License");
.. you may not use this file except in compliance with the License.
.. You may obtain a copy of the License at
..
..     http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing, software
.. distributed under the License is distributed on an "AS IS" BASIS,
.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.. See the License for the specific language governing permissions and
.. limitations under the License.
..

.. _rl-federations-qht:

*********************
Configure Federations
*********************

1)  Create a user with a federations role (Misc -> Users -> Add User).  This user will have the ability to perform the following actions:

		- Edit the federation
		- Delete the federation
		- Add IPV4 resolvers
		- Add IPV6 resolvers

.. image:: federation01.png
	:scale: 100%
	:align: center

2) 	As a user with admin priveleges, create a Federation Mapping by going to Delivery Services -> Federations and then clicking 'Add Federation Mapping'

3)	Choose the Delivery Service for the federation to be mapped to and assign it to the Federation User; click Add.

.. image:: federation02.png
	:scale: 100%
	:align: center

4) 	After the Federation is added, Traffic Ops will display the Federation.

	Changes can be made at this time or the Federation can be deleted.  Notice that no resolvers have been added to the fedeation yet.  This can only be done by the federation user created in step 1.

	If no further action is necessary, the Close button will close the window and display the list of all Federations.

.. image:: federation03.png
	:scale: 100%
	:align: center

**The Federation user can now add resolvers to the Federation Mapping in Traffic Ops.**

5)	The federation user logs to traffic ops and stores the mojolicious cookie.  The mojolicious cookie can be obtained manually using the debug tools on a web browser or via curl.

	Example::

		$ curl -i -XPOST "http://localhost:3000/api/1.1/user/login" -H "Content-Type: application/json" -d '{ "u": "federation_user1", "p": "password" }'

		HTTP/1.1 200 OK
		Date: Wed, 02 Dec 2015 21:12:06 GMT
		Content-Length: 65
		Access-Control-Allow-Credentials: true
		Content-Type: application/json
		Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
		Set-Cookie: mojolicious=eyJleHBpcmVzIjoxNDQ5MTA1MTI2LCJhdXRoX2RhdGEiOiJmZWRlcmF0aW9uX3VzZXIxIn0---06b4f870d809d82a91433e92eae8320875c3e8b0; expires=Thu, 03 Dec 2015 01:12:06 GMT; path=/; HttpOnly
		Server: Mojolicious (Perl)
		Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
		Cache-Control: no-cache, no-store, max-age=0, must-revalidate
		Connection: keep-alive
		Access-Control-Allow-Origin: http://localhost:8080

		{"alerts":[{"level":"success","text":"Successfully logged in."}]}

6) The federation user sends a request to Traffic Ops to add IPV4 and/or IPV6 resolvers

	Example::

		$ curl -ki -H "Cookie: mojolicious=eyJleHBpcmVzIjoxNDQ5MTA1MTI2LCJhdXRoX2RhdGEiOiJmZWRlcmF0aW9uX3VzZXIxIn0---06b4f870d809d82a91433e92eae8320875c3e8b0;" -XPUT 'http://localhost:3000/api/1.2/federations' -d '
			{"federations": [
				{   "deliveryService": "images-c1",
					"mappings":
						{ "resolve4": [ "8.8.8.8/32", "8.8.4.4/32" ],
						  "resolve6": ["2001:4860:4860::8888/128", "2001:4860:4860::8844"]
						}
				}
			  ]
			}'

		HTTP/1.1 200 OK
		Set-Cookie: mojolicious=eyJleHBpcmVzIjoxNDQ5MTA1OTQyLCJhdXRoX2RhdGEiOiJmZWRlcmF0aW9uX3VzZXIxIn0---b42be0749415cefd1d14e1a91bb214845b4de556; expires=Thu, 03 Dec 2015 01:25:42 GMT; path=/; HttpOnly
		Server: Mojolicious (Perl)
		Date: Wed, 02 Dec 2015 21:25:42 GMT
		Content-Length: 74
		Access-Control-Allow-Credentials: true
		Content-Type: application/json
		Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
		Cache-Control: no-cache, no-store, max-age=0, must-revalidate
		Access-Control-Allow-Origin: http://localhost:8080
		Connection: keep-alive
		Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept

		{"response":"federation_user1 successfully created federation resolvers."}

7) The resolvers added by the federation user will now visible in Traffic Ops.

.. image:: federation04.png
	:scale: 100%
	:align: center

8) Any requests made from a client that resolves to one of the federation resolvers will now be given a CNAME from Traffic Router.

	Example::

		$ dig @tr.kabletown.net edge.images-c1.kabletown.net

		; <<>> DiG 9.7.3-RedHat-9.7.3-2.el6 <<>> @tr.kabletown.net edge.images-c1.kabletown.net
		; (1 server found)
		;; global options: +cmd
		;; Got answer:
		;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45110
		;; flags: qr rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
		;; WARNING: recursion requested but not available

		;; QUESTION SECTION:
		;edge.images-c1.kabletown.net.	IN A

		;; ANSWER SECTION:
		edge.images-c1.kabletown.net.	30 IN CNAME img.mega-cdn.net.

		;; Query time: 9 msec
		;; SERVER: 10.10.10.10#53(10.10.10.10)
		;; WHEN: Wed Dec  2 22:05:26 2015
		;; MSG SIZE  rcvd: 84


text:
FullFrame::FullFrame(BytecodeStream *stream, u_long start) : StackMapFrame( stream, start){
    this->offsetDelta=getNextUShort();
    this->numberOfLocals=getNextUShort();
    for (int i = 0; i < this->numberOfLocals; ++i) {
        this->locals.push_back(getNextVerificationTypeInfo());
    }
    this->numberOfStackItems=getNextUShort();
    for (int j = 0; j < this->numberOfStackItems; ++j) {
        this->stack.push_back(getNextVerificationTypeInfo());
    }
}

u_long FullFrame::getBytesLength() const {
    u_long res=7;
    for (int i = 0; i < this->numberOfStackItems; ++i) {
        res+=this->stack[i]->getBytesLength();
    }

    for (int j = 0; j < this->numberOfLocals; ++j) {
        res+=this->locals[j]->getBytesLength();
    }
    return res;
}

string FullFrame::toString() const {
    std::stringstream ss;
    ss << "FullFrame{ frameType: " << this->frameType
       << ", offsetDelta: " << this->offsetDelta
       << ", number of locals: " << this->numberOfLocals
       << ", locals: " << VectorUtil::toString(this->locals)
       << ", number of stack items: " << this->numberOfStackItems
       << ", stack: " << VectorUtil::toString(this->stack)
       << " }";
}

bool FullFrame::verifyTag(byte tag) {
    return tag==255;
}


text:
<?php

namespace FOS\YahooBundle\Twig\Extension;

use FOS\YahooBundle\Templating\Helper\YahooHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;

class YahooExtension extends \Twig_Extension
{
    protected $container;

    /**
     * Constructor.
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Returns a list of global functions to add to the existing list.
     *
     * @return array An array of global functions
     */
    public function getFunctions()
    {
        return array(
            'yahoo_login_button' => new \Twig_Function_Method($this, 'renderLoginButton', array('is_safe' => array('html'))),
        );
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'yahoo';
    }

    /**
     * @see GoogleHelper::loginButton()
     */
    public function renderLoginButton($parameters = array(), $name = null)
    {
        return $this->container->get('fos_yahoo.helper')->loginButton($parameters, $name ?: 'FOSYahooBundle::loginButton.html.twig');
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Protocols/SDWebImageManagerDelegate.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/intf/SDWebImageManagerDelegate</TokenIdentifier>
			<Abstract type="html">Delegate protocol for SDWebImageManager</Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<NodeRef refid="12"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didProgressWithPartialImage:forURL:userInfo:</TokenIdentifier>
			<Abstract type="html">Called while an image is downloading with an partial image object representing the currently downloaded portion of the image.
This delegate is called only if ImageIO is available and SDWebImageProgressiveDownload option has been used.</Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didProgressWithPartialImage:(UIImage *)image forURL:(NSURL *)url userInfo:(NSDictionary *)info</Declaration>
			<Parameters>
				<Parameter>
					<Name>imageManager</Name>
					<Abstract type="html">The image manager</Abstract>
				</Parameter><Parameter>
					<Name>image</Name>
					<Abstract type="html">The retrived image object</Abstract>
				</Parameter><Parameter>
					<Name>url</Name>
					<Abstract type="html">The image URL used to retrive the image</Abstract>
				</Parameter><Parameter>
					<Name>info</Name>
					<Abstract type="html">The user info dictionnary</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/webImageManager:didProgressWithPartialImage:forURL:userInfo:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didProgressWithPartialImage:forURL:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didProgressWithPartialImage:(UIImage *)image forURL:(NSURL *)url</Declaration>

			<Anchor>//api/name/webImageManager:didProgressWithPartialImage:forURL:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didFinishWithImage:forURL:userInfo:</TokenIdentifier>
			<Abstract type="html">Called when image download is completed successfuly.</Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image forURL:(NSURL *)url userInfo:(NSDictionary *)info</Declaration>
			<Parameters>
				<Parameter>
					<Name>imageManager</Name>
					<Abstract type="html">The image manager</Abstract>
				</Parameter><Parameter>
					<Name>image</Name>
					<Abstract type="html">The retrived image object</Abstract>
				</Parameter><Parameter>
					<Name>url</Name>
					<Abstract type="html">The image URL used to retrive the image</Abstract>
				</Parameter><Parameter>
					<Name>info</Name>
					<Abstract type="html">The user info dictionnary</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/webImageManager:didFinishWithImage:forURL:userInfo:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didFinishWithImage:forURL:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image forURL:(NSURL *)url</Declaration>

			<Anchor>//api/name/webImageManager:didFinishWithImage:forURL:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didFinishWithImage:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image</Declaration>

			<Anchor>//api/name/webImageManager:didFinishWithImage:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didFailWithError:forURL:userInfo:</TokenIdentifier>
			<Abstract type="html">Called when an error occurred.</Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error forURL:(NSURL *)url userInfo:(NSDictionary *)info</Declaration>
			<Parameters>
				<Parameter>
					<Name>imageManager</Name>
					<Abstract type="html">The image manager</Abstract>
				</Parameter><Parameter>
					<Name>error</Name>
					<Abstract type="html">The error</Abstract>
				</Parameter><Parameter>
					<Name>url</Name>
					<Abstract type="html">The image URL used to retrive the image</Abstract>
				</Parameter><Parameter>
					<Name>info</Name>
					<Abstract type="html">The user info dictionnary</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/webImageManager:didFailWithError:forURL:userInfo:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didFailWithError:forURL:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error forURL:(NSURL *)url</Declaration>

			<Anchor>//api/name/webImageManager:didFailWithError:forURL:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/SDWebImageManagerDelegate/webImageManager:didFailWithError:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>SDWebImageManagerDelegate.h</DeclaredIn>

			<Declaration>- (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error</Declaration>

			<Anchor>//api/name/webImageManager:didFailWithError:</Anchor>
		</Token>

	</File>
</Tokens>


text:
"""
Verify that a hard_dependency that is not exported is not pulled in as a
dependency for a target if the target does not explicitly specify a dependency
and none of its dependencies export the hard_dependency.
"""

import TestGyp

test = TestGyp.TestGyp()

if test.format == 'dump_dependency_json':
  test.skip_test('Skipping test; dependency JSON does not adjust ' \
                 'static libaries.\n')

test.run_gyp('hard_dependency.gyp', chdir='src')

chdir = 'relocate/src'
test.relocate('src', chdir)

test.build('hard_dependency.gyp', 'd', chdir=chdir)

# Because 'c' does not export a hard_dependency, only the target 'd' should
# be built. This is because the 'd' target does not need the generated headers
# in order to be compiled.
test.built_file_must_not_exist('a', type=test.STATIC_LIB, chdir=chdir)
test.built_file_must_not_exist('b', type=test.STATIC_LIB, chdir=chdir)
test.built_file_must_not_exist('c', type=test.STATIC_LIB, chdir=chdir)
test.built_file_must_exist('d', type=test.STATIC_LIB, chdir=chdir)

test.pass_test()


text:
<Alloy>
		<TabGroup>
			<Tab id="tab1">
				<Require src="schedule" id="scheduleTab"></Require>
			</Tab>
			<Tab id="tab2">
				<Require src="venue" id="venueTab"></Require>
			</Tab>
			<Tab id="tab3">
				<Require src="conversation" id="conversationTab"></Require>
			</Tab>
			<Tab id="tab4">
				<Require src="videos" id="videosTab"></Require>
			</Tab>
		</TabGroup>
</Alloy>


text:
layout: post
microblog: true
date: 2009-12-30 03:00 +0300
guid: http://desparoz.micro.blog/2009/12/30/t7193548600.html
---
Bizarre. They were a terrific sight - tho stinky! RT @GuyKawasaki: The mysterious disappearance of the San Fran sea lions [om.ly/dalW](http://om.ly/dalW)


text:
#ifndef SKY_ENGINE_PLATFORM_LENGTHSIZE_H_
#define SKY_ENGINE_PLATFORM_LENGTHSIZE_H_

#include "sky/engine/platform/Length.h"

namespace blink {

class LengthSize {
public:
    LengthSize()
    {
    }

    LengthSize(const Length& width, const Length& height)
        : m_width(width)
        , m_height(height)
    {
    }

    bool operator==(const LengthSize& o) const
    {
        return m_width == o.m_width && m_height == o.m_height;
    }

    void setWidth(const Length& width) { m_width = width; }
    const Length& width() const { return m_width; }

    void setHeight(const Length& height) { m_height = height; }
    const Length& height() const { return m_height; }

private:
    Length m_width;
    Length m_height;
};

} // namespace blink

#endif  // SKY_ENGINE_PLATFORM_LENGTHSIZE_H_


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Great Basin Naturalist 37:95. 1977

#### Original name
null

### Remarks
null


text:
echo "[Step1] Installing dependencies"
brew install automake libtool

echo "[Step2] git cloning Caffe2"
git clone --recursive https://github.com/caffe2/caffe2.git

echo "[Step2 - b] checkout to a stable version tags/v0.7.0-163-gebc17cc8"
cd caffe2 && git checkout tags/v0.7.0-163-gebc17cc8

echo "[Step3] build ios"
./scripts/build_ios.sh

echo "[Tada!] Done"


text:
layout: post
date: 2016-06-06
title: "Watters - Watters Watters Maids Dress Carita style 5225 Sleeveless Short/Mini Sheath/Column"
category: Watters - Watters
tags: [Watters - Watters,Watters,Sheath/Column,Scalloped-Edge,Short/Mini,Sleeveless]
---
### Watters - Watters Watters Maids Dress Carita style 5225
Just **$209.99**
###   Sleeveless Short/Mini Sheath/Column

BRANDS	Watters

Silhouette	Sheath/Column

Neckline	Scalloped-Edge

Hemline/Train	Short/Mini

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/watters-watters/14234-watters-dress-carita-style-5225.html](https://www.readybrides.com/en/watters-watters/14234-watters-dress-carita-style-5225.html)


text:
package cluster

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/Sirupsen/logrus"
	"github.com/docker/distribution/reference"
	apierrors "github.com/docker/docker/api/errors"
	apitypes "github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/backend"
	types "github.com/docker/docker/api/types/swarm"
	"github.com/docker/docker/daemon/cluster/convert"
	"github.com/docker/docker/daemon/logger"
	"github.com/docker/docker/pkg/ioutils"
	"github.com/docker/docker/pkg/stdcopy"
	swarmapi "github.com/docker/swarmkit/api"
	gogotypes "github.com/gogo/protobuf/types"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
)

// GetServices returns all services of a managed swarm cluster.
func (c *Cluster) GetServices(options apitypes.ServiceListOptions) ([]types.Service, error) {
	c.mu.RLock()
	defer c.mu.RUnlock()

	state := c.currentNodeState()
	if !state.IsActiveManager() {
		return nil, c.errNoManager(state)
	}

	filters, err := newListServicesFilters(options.Filters)
	if err != nil {
		return nil, err
	}
	ctx, cancel := c.getRequestContext()
	defer cancel()

	r, err := state.controlClient.ListServices(
		ctx,
		&swarmapi.ListServicesRequest{Filters: filters})
	if err != nil {
		return nil, err
	}

	services := []types.Service{}

	for _, service := range r.Services {
		services = append(services, convert.ServiceFromGRPC(*service))
	}

	return services, nil
}

// GetService returns a service based on an ID or name.
func (c *Cluster) GetService(input string) (types.Service, error) {
	var service *swarmapi.Service
	if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		s, err := getService(ctx, state.controlClient, input)
		if err != nil {
			return err
		}
		service = s
		return nil
	}); err != nil {
		return types.Service{}, err
	}
	return convert.ServiceFromGRPC(*service), nil
}

// CreateService creates a new service in a managed swarm cluster.
func (c *Cluster) CreateService(s types.ServiceSpec, encodedAuth string) (*apitypes.ServiceCreateResponse, error) {
	var resp *apitypes.ServiceCreateResponse
	err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		err := c.populateNetworkID(ctx, state.controlClient, &s)
		if err != nil {
			return err
		}

		serviceSpec, err := convert.ServiceSpecToGRPC(s)
		if err != nil {
			return apierrors.NewBadRequestError(err)
		}

		ctnr := serviceSpec.Task.GetContainer()
		if ctnr == nil {
			return errors.New("service does not use container tasks")
		}

		if encodedAuth != "" {
			ctnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth}
		}

		// retrieve auth config from encoded auth
		authConfig := &apitypes.AuthConfig{}
		if encodedAuth != "" {
			if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuth))).Decode(authConfig); err != nil {
				logrus.Warnf("invalid authconfig: %v", err)
			}
		}

		resp = &apitypes.ServiceCreateResponse{}

		// pin image by digest
		if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" {
			digestImage, err := c.imageWithDigestString(ctx, ctnr.Image, authConfig)
			if err != nil {
				logrus.Warnf("unable to pin image %s to digest: %s", ctnr.Image, err.Error())
				resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", ctnr.Image, err.Error()))
			} else if ctnr.Image != digestImage {
				logrus.Debugf("pinning image %s by digest: %s", ctnr.Image, digestImage)
				ctnr.Image = digestImage
			} else {
				logrus.Debugf("creating service using supplied digest reference %s", ctnr.Image)
			}
		}

		r, err := state.controlClient.CreateService(ctx, &swarmapi.CreateServiceRequest{Spec: &serviceSpec})
		if err != nil {
			return err
		}

		resp.ID = r.Service.ID
		return nil
	})
	return resp, err
}

// UpdateService updates existing service to match new properties.
func (c *Cluster) UpdateService(serviceIDOrName string, version uint64, spec types.ServiceSpec, encodedAuth string, registryAuthFrom string) (*apitypes.ServiceUpdateResponse, error) {
	var resp *apitypes.ServiceUpdateResponse

	err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {

		err := c.populateNetworkID(ctx, state.controlClient, &spec)
		if err != nil {
			return err
		}

		serviceSpec, err := convert.ServiceSpecToGRPC(spec)
		if err != nil {
			return apierrors.NewBadRequestError(err)
		}

		currentService, err := getService(ctx, state.controlClient, serviceIDOrName)
		if err != nil {
			return err
		}

		newCtnr := serviceSpec.Task.GetContainer()
		if newCtnr == nil {
			return errors.New("service does not use container tasks")
		}

		if encodedAuth != "" {
			newCtnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth}
		} else {
			// this is needed because if the encodedAuth isn't being updated then we
			// shouldn't lose it, and continue to use the one that was already present
			var ctnr *swarmapi.ContainerSpec
			switch registryAuthFrom {
			case apitypes.RegistryAuthFromSpec, "":
				ctnr = currentService.Spec.Task.GetContainer()
			case apitypes.RegistryAuthFromPreviousSpec:
				if currentService.PreviousSpec == nil {
					return errors.New("service does not have a previous spec")
				}
				ctnr = currentService.PreviousSpec.Task.GetContainer()
			default:
				return errors.New("unsupported registryAuthFrom value")
			}
			if ctnr == nil {
				return errors.New("service does not use container tasks")
			}
			newCtnr.PullOptions = ctnr.PullOptions
			// update encodedAuth so it can be used to pin image by digest
			if ctnr.PullOptions != nil {
				encodedAuth = ctnr.PullOptions.RegistryAuth
			}
		}

		// retrieve auth config from encoded auth
		authConfig := &apitypes.AuthConfig{}
		if encodedAuth != "" {
			if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuth))).Decode(authConfig); err != nil {
				logrus.Warnf("invalid authconfig: %v", err)
			}
		}

		resp := &apitypes.ServiceUpdateResponse{}

		// pin image by digest
		if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" {
			digestImage, err := c.imageWithDigestString(ctx, newCtnr.Image, authConfig)
			if err != nil {
				logrus.Warnf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error())
				resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error()))
			} else if newCtnr.Image != digestImage {
				logrus.Debugf("pinning image %s by digest: %s", newCtnr.Image, digestImage)
				newCtnr.Image = digestImage
			} else {
				logrus.Debugf("updating service using supplied digest reference %s", newCtnr.Image)
			}
		}

		_, err = state.controlClient.UpdateService(
			ctx,
			&swarmapi.UpdateServiceRequest{
				ServiceID: currentService.ID,
				Spec:      &serviceSpec,
				ServiceVersion: &swarmapi.Version{
					Index: version,
				},
			},
		)
		return err
	})
	return resp, err
}

// RemoveService removes a service from a managed swarm cluster.
func (c *Cluster) RemoveService(input string) error {
	return c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		service, err := getService(ctx, state.controlClient, input)
		if err != nil {
			return err
		}

		_, err = state.controlClient.RemoveService(ctx, &swarmapi.RemoveServiceRequest{ServiceID: service.ID})
		return err
	})
}

// ServiceLogs collects service logs and writes them back to `config.OutStream`
func (c *Cluster) ServiceLogs(ctx context.Context, input string, config *backend.ContainerLogsConfig, started chan struct{}) error {
	c.mu.RLock()
	state := c.currentNodeState()
	if !state.IsActiveManager() {
		c.mu.RUnlock()
		return c.errNoManager(state)
	}

	service, err := getService(ctx, state.controlClient, input)
	if err != nil {
		c.mu.RUnlock()
		return err
	}

	// set the streams we'll use
	stdStreams := []swarmapi.LogStream{}
	if config.ContainerLogsOptions.ShowStdout {
		stdStreams = append(stdStreams, swarmapi.LogStreamStdout)
	}
	if config.ContainerLogsOptions.ShowStderr {
		stdStreams = append(stdStreams, swarmapi.LogStreamStderr)
	}

	stream, err := state.logsClient.SubscribeLogs(ctx, &swarmapi.SubscribeLogsRequest{
		Selector: &swarmapi.LogSelector{
			ServiceIDs: []string{service.ID},
		},
		Options: &swarmapi.LogSubscriptionOptions{
			Follow:  config.Follow,
			Streams: stdStreams,
		},
	})
	if err != nil {
		c.mu.RUnlock()
		return err
	}

	wf := ioutils.NewWriteFlusher(config.OutStream)
	defer wf.Close()
	close(started)
	wf.Flush()

	outStream := stdcopy.NewStdWriter(wf, stdcopy.Stdout)
	errStream := stdcopy.NewStdWriter(wf, stdcopy.Stderr)

	// Release the lock before starting the stream.
	c.mu.RUnlock()
	for {
		// Check the context before doing anything.
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}

		subscribeMsg, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		for _, msg := range subscribeMsg.Messages {
			data := []byte{}

			if config.Timestamps {
				ts, err := gogotypes.TimestampFromProto(msg.Timestamp)
				if err != nil {
					return err
				}
				data = append(data, []byte(ts.Format(logger.TimeFormat)+" ")...)
			}

			data = append(data, []byte(fmt.Sprintf("%s.node.id=%s,%s.service.id=%s,%s.task.id=%s ",
				contextPrefix, msg.Context.NodeID,
				contextPrefix, msg.Context.ServiceID,
				contextPrefix, msg.Context.TaskID,
			))...)

			data = append(data, msg.Data...)

			switch msg.Stream {
			case swarmapi.LogStreamStdout:
				outStream.Write(data)
			case swarmapi.LogStreamStderr:
				errStream.Write(data)
			}
		}
	}
}

// imageWithDigestString takes an image such as name or name:tag
// and returns the image pinned to a digest, such as name@sha256:34234
func (c *Cluster) imageWithDigestString(ctx context.Context, image string, authConfig *apitypes.AuthConfig) (string, error) {
	ref, err := reference.ParseAnyReference(image)
	if err != nil {
		return "", err
	}
	namedRef, ok := ref.(reference.Named)
	if !ok {
		if _, ok := ref.(reference.Digested); ok {
			return "", errors.New("image reference is an image ID")
		}
		return "", errors.Errorf("unknown image reference format: %s", image)
	}
	// only query registry if not a canonical reference (i.e. with digest)
	if _, ok := namedRef.(reference.Canonical); !ok {
		namedRef = reference.TagNameOnly(namedRef)

		taggedRef, ok := namedRef.(reference.NamedTagged)
		if !ok {
			return "", errors.Errorf("image reference not tagged: %s", image)
		}

		repo, _, err := c.config.Backend.GetRepository(ctx, taggedRef, authConfig)
		if err != nil {
			return "", err
		}
		dscrptr, err := repo.Tags(ctx).Get(ctx, taggedRef.Tag())
		if err != nil {
			return "", err
		}

		namedDigestedRef, err := reference.WithDigest(taggedRef, dscrptr.Digest)
		if err != nil {
			return "", err
		}
		// return familiar form until interface updated to return type
		return reference.FamiliarString(namedDigestedRef), nil
	}
	// reference already contains a digest, so just return it
	return reference.FamiliarString(ref), nil
}


text:
from flask import session
from wtforms import PasswordField, SelectField, StringField
from wtforms.fields.html5 import DateField, URLField

from CTFd.forms import BaseForm
from CTFd.forms.fields import SubmitField
from CTFd.forms.users import attach_custom_user_fields, build_custom_user_fields
from CTFd.utils.countries import SELECT_COUNTRIES_LIST
from CTFd.utils.user import get_current_user

def SettingsForm(*args, **kwargs):
    class _SettingsForm(BaseForm):
        name = StringField("User Name")
        email = StringField("Email")
        password = PasswordField("Password")
        confirm = PasswordField("Current Password")
        affiliation = StringField("Affiliation")
        website = URLField("Website")
        country = SelectField("Country", choices=SELECT_COUNTRIES_LIST)
        submit = SubmitField("Submit")

        @property
        def extra(self):
            fields_kwargs = _SettingsForm.get_field_kwargs()
            return build_custom_user_fields(
                self,
                include_entries=True,
                fields_kwargs=fields_kwargs,
                field_entries_kwargs={"user_id": session["id"]},
            )

        @staticmethod
        def get_field_kwargs():
            user = get_current_user()
            field_kwargs = {"editable": True}
            if user.filled_all_required_fields is False:
                # Show all fields
                field_kwargs = {}
            return field_kwargs

    field_kwargs = _SettingsForm.get_field_kwargs()
    attach_custom_user_fields(_SettingsForm, **field_kwargs)

    return _SettingsForm(*args, **kwargs)

class TokensForm(BaseForm):
    expiration = DateField("Expiration")
    submit = SubmitField("Generate")


text:
% File Copier Plugin
% Greg Schueler, Alex Honor
% November 20, 2010

## About

A File Copier provider copies a file or script to a remote or local node.

## Java Plugin Type

Your provider class must implement the interface
[DestinationFileCopier](../javadoc/com/dtolabs/rundeck/core/execution/service/DestinationFileCopier.html):

~~~~~ {.java}
public interface DestinationFileCopier extends FileCopier {

    public String copyFileStream(ExecutionContext context,
                                 InputStream input,
                                 INodeEntry node,
                                 String destination) throws FileCopierException;

    public String copyFile(ExecutionContext context,
                           File file,
                           INodeEntry node,
                           String destination) throws FileCopierException;

    public String copyScriptContent(ExecutionContext context,
                                    String script,
                                    INodeEntry node,
                                    String destination) throws FileCopierException;
}
~~~~~~~~~

### Plugin properties

See [Plugin Development - Java Plugins - Descriptions](plugin-development.html#plugin-descriptions)
to learn how to create configuration properties for your plugin.

> Note, the `destination` parameter may or may not be specified. If it is not null, it indicates that the file must be copied to the requested destination filepath. If it is null, it indicates that the copied file is likely a script file, and it should be copied to a temporary file location. In either case, the resulting file path must be returned as the result of the method call.

## Script Plugin Type

See the [Script Plugin Development](plugin-development.html#script-plugin-development)
for the basics of developing script-based plugins for Rundeck.

### Additional data context properties

The data context used in the script plugin definition can use these additional properties:

`${file-copy.file}`

  : The local path to the file that needs to be copied.

`${file-copy.destination}`

  : The remote destination path that is requested, if available.

### Provider Script Requirements

The specific service has expectations about the way your provider script behaves:

#### Script Exit Code

* Exit code of 0 indicates success.
* Any other exit code indicates failure.

#### Script Output

The first line of output of `STDOUT` MUST be the filepath of the file copied to the target node. Other output is ignored. All output to `STDERR` will be captured for the job's output.


text:
Frequently Asked Questions
==========================

How can I change the design of a Kansha app?
--------------------------------------------

Kansha supports custom themes, a default theme called *kansha_flat* is bundled with the app.

A theme is made of 4 CSS files grouped in a folder named as your theme:

  - ``kansha.css`` is included in every page, it should contain common style rules used all around the app

  - ``board.css`` is included in the board view, it defines the styles of the boards, colums and cards

  - ``home.css`` is only included in the homepage listing your boards and in user profile/user cards

  - ``login.css`` is included in the login page only

For development purposes you can store it in the folder */static/css/themes/* or configure a web server to serve these files according to `deployment section of the Nagare manual <http://www.nagare.org/trac/wiki/ApplicationDeployment#configuring-the-web-server>`_.

To activate it, you have to edit the :ref:`application` section of your configuration file, changing the ``theme`` parameter to fit your theme name.

Once done, restart your app and enjoy.

See :file:`static/css/themes/kansha_flat` folder for a working example.


text:
/*
 * stkim1 08/03/13
 * This class handles Bonjour Service with DNS-SD for BT connectivity separated in iOS 5 & 6
 */

#import "LoggerTCPTransport.h"

@interface LoggerNativeLegacyTransport : LoggerTCPTransport
@property (nonatomic, assign) BOOL useBluetooth;
@end


text:
.image-wrapper{
  max-width:90%;
  height:auto;
  position: relative;
  display:block;
  margin:0 auto;
}

.image-wrapper img{
  max-width:100% !important;
  height:auto;
  display:block;
}


text:
import os
# Django settings for opendata project.

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(PROJECT_PATH, os.pardir))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
     ('OpenData Admins', 'admin@example.org'),
)
CONTACT_EMAILS = ['admin@example.org',]
DEFAULT_FROM_EMAIL = 'OpenData Team <info@example.org>'
EMAIL_SUBJECT_PREFIX = '[OpenData.org] '
SERVER_EMAIL = 'OpenData Team <info@example.org>'

MANAGERS = (
     ('OpenData Team', 'info@example.org'),
)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'catalog',                      # Or path to database file if using sqlite3.
        'USER': 'catalog',                      # Not used with sqlite3.
        'PASSWORD': 'passw0rd',                  # Not used with sqlite3.
        'HOST': '',                      # Set to 'localhost' for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public', 'media/')
# ADMIN_MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'admin_media/')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'public', 'static/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

STATIC_DATA = os.path.join(PROJECT_ROOT, 'public', 'static/')

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
#ADMIN_MEDIA_PREFIX = '/hidden/static/admin_media/'
ADMIN_MEDIA_PREFIX = '/static/admin/'

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

### Package settings
ACCOUNT_ACTIVATION_DAYS = 7
TWITTER_TIMEOUT = 6000
THUMBNAIL_EXTENSION = 'png'
PAGINATION_DEFAULT_WINDOW = 2
###

COMMENTS_APP = 'comments'

AUTH_PROFILE_MODULE = 'opendata.odpuserprofile'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",

    "opendata.context_processors.get_current_path",
    "opendata.context_processors.get_settings",
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django_sorting.middleware.SortingMiddleware',
    'pagination.middleware.PaginationMiddleware',

)

ROOT_URLCONF = 'urls'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.comments',
    'django.contrib.flatpages',
    'django.contrib.sitemaps',
    'django.contrib.humanize',
    'south',
    'opendata',
    'registration',
    'sorl.thumbnail',
    'pagination',
    'django_sorting',
    'djangoratings',
    'comments',
    'suggestions',
    'contest',
    'catalog',
)

# the hostname of the deployment
SITEHOST = None
# the port which the deployment runs on
SITEPORT = None

# pycsw configuration
CSW = {
    'metadata:main': {
        'identification_title': 'Open Data Catalog CSW',
        'identification_abstract': 'Open Data Catalog is an open data catalog based on Django, Python and PostgreSQL. It was originally developed for OpenDataPhilly.org, a portal that provides access to open data sets, applications, and APIs related to the Philadelphia region. The Open Data Catalog is a generalized version of the original source code with a simple skin. It is intended to display information and links to publicly available data in an easily searchable format. The code also includes options for data owners to submit data for consideration and for registered public users to nominate a type of data they would like to see openly available to the public.',
        'identification_keywords': 'odc,Open Data Catalog,catalog,discovery',
        'identification_keywords_type': 'theme',
        'identification_fees': 'None',
        'identification_accessconstraints': 'None',
        'provider_name': ADMINS[0][0],
        'provider_url': 'https://github.com/azavea/Open-Data-Catalog',
        'contact_name': ADMINS[0][0],
        'contact_position': ADMINS[0][0],
        'contact_address': 'TBA',
        'contact_city': 'City',
        'contact_stateorprovince': 'State',
        'contact_postalcode': '12345',
        'contact_country': 'United States of America',
        'contact_phone': '+01-xxx-xxx-xxxx',
        'contact_fax': '+01-xxx-xxx-xxxx',
        'contact_email': ADMINS[0][1],
        'contact_url': 'https://github.com/azavea/Open-Data-Catalog/',
        'contact_hours': '0800h - 1600h EST',
        'contact_instructions': 'During hours of service.  Off on weekends.',
        'contact_role': 'pointOfContact',
    },
    'metadata:inspire': {
        'enabled': 'false',
        'languages_supported': 'eng',
        'default_language': 'eng',
        'date': '2012-06-11',
        'gemet_keywords': 'Utility and governmental services',
        'conformity_service': 'notEvaluated',
        'contact_name': MANAGERS[0][0],
        'contact_email': MANAGERS[0][1],
        'temp_extent': '2012-06-11/2012-06-11',
    }
}

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
            'propagate': True,
        },
    }
}

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'static'),
    os.path.abspath(os.path.join(os.path.dirname(__file__),
                                 'opendata/static')),
)

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'templates'),
    os.path.join(os.path.dirname(__file__), 'templates')
)


text:
from django.template import Library, Node, Variable, loader
#from django.template.context import Context
from templated_forms.factory import FormFactory
from django import template

class FormFactoryTemplateNode(Node):
    def __init__(self, form):
        self.form = template.Variable(form)

    def render(self, context):
        form = self.form.resolve(context)
        self.factory = FormFactory(form)
        return self.factory.render()


text:
class FoodSerializer < ActiveModel::Serializer
  attributes :id, :name, :weight, :calories, :protein, :carbs, :fat
  #:image
end


text:
namespace chrome_browser_net {

// A TabHelper that monitors loads for certain types of network errors and
// does interesting things with them.  Currently, starts DNS probes using the
// DnsProbeService whenever a page fails to load with a DNS-related error.
class NetErrorTabHelper
    : public content::WebContentsObserver,
      public content::WebContentsUserData<NetErrorTabHelper> {
 public:
  enum TestingState {
    TESTING_DEFAULT,
    TESTING_FORCE_DISABLED,
    TESTING_FORCE_ENABLED
  };

  typedef base::Callback<void(chrome_common_net::DnsProbeStatus)>
      DnsProbeStatusSnoopCallback;

  virtual ~NetErrorTabHelper();

  static void set_state_for_testing(TestingState testing_state);

  // Sets a callback that will be called immediately after the helper sends
  // a NetErrorHelper IPC.  (Used by the DNS probe browser test to know when to
  // check the error page for updates, instead of polling.)
  void set_dns_probe_status_snoop_callback_for_testing(
      const DnsProbeStatusSnoopCallback& dns_probe_status_snoop_callback) {
    dns_probe_status_snoop_callback_ = dns_probe_status_snoop_callback;
  }

  // content::WebContentsObserver implementation.
  virtual void DidStartNavigationToPendingEntry(
      const GURL& url,
      content::NavigationController::ReloadType reload_type) OVERRIDE;

  virtual void DidStartProvisionalLoadForFrame(
      content::RenderFrameHost* render_frame_host,
      const GURL& validated_url,
      bool is_error_page,
      bool is_iframe_srcdoc) OVERRIDE;

  virtual void DidCommitProvisionalLoadForFrame(
      content::RenderFrameHost* render_frame_host,
      const GURL& url,
      content::PageTransition transition_type) OVERRIDE;

  virtual void DidFailProvisionalLoad(
      content::RenderFrameHost* render_frame_host,
      const GURL& validated_url,
      int error_code,
      const base::string16& error_description) OVERRIDE;

 protected:
  // |contents| is the WebContents of the tab this NetErrorTabHelper is
  // attached to.
  explicit NetErrorTabHelper(content::WebContents* contents);
  virtual void StartDnsProbe();
  virtual void SendInfo();
  void OnDnsProbeFinished(chrome_common_net::DnsProbeStatus result);

  chrome_common_net::DnsProbeStatus dns_probe_status() const {
    return dns_probe_status_;
  }

 private:
  friend class content::WebContentsUserData<NetErrorTabHelper>;

  void OnMainFrameDnsError();

  void InitializePref(content::WebContents* contents);
  bool ProbesAllowed() const;

  base::WeakPtrFactory<NetErrorTabHelper> weak_factory_;

  // True if the last provisional load that started was for an error page.
  bool is_error_page_;

  // True if the helper has seen a main frame page load fail with a DNS error,
  // but has not yet seen a new page commit successfully afterwards.
  bool dns_error_active_;

  // True if the helper has seen an error page commit while |dns_error_active_|
  // is true.  (This should never be true if |dns_error_active_| is false.)
  bool dns_error_page_committed_;

  // The status of a DNS probe that may or may not have started or finished.
  // Since the renderer can change out from under the helper (in cross-process
  // navigations), it re-sends the status whenever an error page commits.
  chrome_common_net::DnsProbeStatus dns_probe_status_;

  // Optional callback for browser test to snoop on outgoing NetErrorInfo IPCs.
  DnsProbeStatusSnoopCallback dns_probe_status_snoop_callback_;

  // "Use a web service to resolve navigation errors" preference is required
  // to allow probes.
  BooleanPrefMember resolve_errors_with_web_service_;

  DISALLOW_COPY_AND_ASSIGN(NetErrorTabHelper);
};

}  // namespace chrome_browser_net

#endif  // CHROME_BROWSER_NET_NET_ERROR_TAB_HELPER_H_


text:
package no.dusken.momus.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/env")
public class EnvironmentController {

    @Autowired
    private Environment env;

    @GetMapping("/all")
    public Map<String, Object> allEnv() {
        Map<String, Object> values = new HashMap<>();
        values.put("version", env.getProperty("momus.version"));
        values.put("devmode", env.acceptsProfiles(Profiles.of("dev")));
        values.put("noAuth", env.acceptsProfiles(Profiles.of("noAuth")));
        return values;
    }
}


text:
/*

November Template

http://www.templatemo.com/tm-473-november

*/

/* HTML Document is loaded and DOM is ready.
--------------------------------------------*/
$(document).ready(function(){
  //slider
  var sudoSlider = $("#slider").sudoSlider({
   effect: "fade",
   pause: 3000,
   auto:true,
   continuous:true
 });

  //mobilemenu
  $('.mobile').click(function(){
    var $self = $(this);
    $('.menumobile').slideToggle( function(){
      $self.toggleClass('closed');
    });
  });

  //navigation script
  $('.Navigation ul li a').click(function(){
    $('.menumobile').removeAttr("style");
    $('#mobile_sec .mobile').removeClass("closed");
  });

  $('a.slicknav_btn').click(function(){
    $(".mobilemenu ul").css({"display":"block"});
  });

  //tab
  $(".tabLink").each(function(){
    $(this).click(function(){
      tabeId = $(this).attr('id');
      $(".tabLink").removeClass("activeLink");
      $(this).addClass("activeLink");
      $(".tabcontent").addClass("hide");
      $("#"+tabeId+"-1").removeClass("hide");
      return false;
    });
  });
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
      || location.hostname == this.hostname)
    {
      var target = $(this.hash),
      headerHeight = $(".primary-header").height() + 5; // Get fixed header height
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length)
      {
        $('html,body').animate({
          scrollTop: target.offset().top + 2
        }, 600);
        return false;
      }
    }
  });

  //Header Small
  window.addEventListener('scroll', function(e){
    var distanceY = window.pageYOffset || document.documentElement.scrollTop,
    shrinkOn = 50;

    if (distanceY > shrinkOn) {
      $('header').addClass("smaller");
    } else {
      $('header').toggleClass("smaller");
    }
  });

});

// Complete page is fully loaded, including all frames, objects and images
$(window).load(function() {
  // Remove preloader
  // https://ihatetomatoes.net/create-custom-preloading-screen/
  $('body').addClass('loaded');
});


text:
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');

abstract class EED_Module extends EE_Configurable {

	/**
	 * 	instance of the EED_Module object
	 * 	@access 	protected
	 *	@var 	EED_Module $_instance
	 */
	protected static $_instance = NULL;

	/**
	 * 	rendered output to be returned to WP
	 * 	@access 	protected
	 *	@var 	string $output
	 */
	protected $output = '';

	/**
	 * 	the current active espresso template theme
	 * 	@access 	protected
	 *	@var 	string $theme
	 */
	protected $theme = '';

	/**
	 * 	set_hooks - for hooking into EE Core, other modules, etc
	 *
	 *  @access 	public
	 *  @return 	void
	 */
	public static function set_hooks() {}

	/**
	 * 	set_hooks_admin - for hooking into EE Admin Core, other modules, etc
	 *
	 *  @access 	public
	 *  @return 	void
	 */
	public static function set_hooks_admin() {}

	/**
	 * 	run - initial module setup
	 * 	this method is primarily used for activating resources in the EE_Front_Controller thru the use of filters
	 *
	 *  @access 	public
	 *  @var 			WP $WP
	 *  @return 	void
	 */
	public abstract function run( $WP );

	/**
	 *    class constructor - can ONLY be instantiated by EE_Front_Controller
	 *
	 * @override default exception handling
	 * @access   public
	 * @return \EED_Module
	 */
	final public function __construct() {
		$this->theme = EE_Config::get_current_theme();
		$module_name = $this->module_name();
		EE_Registry::instance()->modules->{$module_name} = $this;
	}

	/**
	 * @param $module_name
	 * @return EED_Module
	 */
	protected static function get_instance( $module_name = '' ) {
		$module_name = ! empty( $module_name ) ? $module_name : get_called_class();
		if ( ! isset(  EE_Registry::instance()->modules->{$module_name} ) || ! EE_Registry::instance()->modules->{$module_name} instanceof EED_Module ) {
			EE_Registry::instance()->add_module( $module_name );
		}
		return EE_Registry::instance()->get_module( $module_name );
	}

	/**
	 *    module_name
	 *
	 * @access    public
	 * @return    string
	 */
	public function module_name() {
		return get_class( $this );
	}

}
// End of file EED_Module.module.php