text:
<?php

function load_config($path) {
    return json_decode(file_get_contents(LOCAL_PATH_CONFIG . DIRECTORY_SEPARATOR . $path));
}

function load_template($path) {
    $path = LOCAL_PATH_TEMPLATE . DIRECTORY_SEPARATOR . $path;
    $pathinfo = pathinfo($path);
    if ($pathinfo['extension'] == 'html') {
        return \PowerTools\DOM_Query::loadHTML(file_get_contents($path));
    } else {
        return \PowerTools\DOM_Query::loadHTML('<pre>' . htmlentities(file_get_contents($path)) . '</pre>');
    }
}

function load_external_data($path) {
    return \PowerTools\DOM_Query::loadHTML(file_get_contents($path));
}
?>


text:
from gitlint.rules import CommitRule, RuleViolation

class SignedOffBy(CommitRule):
    """This rule will enforce that each commit body contains a "Signed-off-by" line.
    We keep things simple here and just check whether the commit body contains a line that starts with "Signed-off-by".
    """

    name = "contrib-body-requires-signed-off-by"
    id = "CC1"

    def validate(self, commit):
        for line in commit.message.body:
            if line.lower().startswith("signed-off-by"):
                return []

        return [RuleViolation(self.id, "Body does not contain a 'Signed-off-by' line", line_nr=1)]

redpajama_set_name: RedPajamaGithub


text:
'use strict';

describe('Controller: DefinitionDetailCtrl Delete', function () {

  var createController,
    $rootScope,
    Definition,
    scope;

  beforeEach(module('amApp'));
  beforeEach(module('templates'));
  beforeEach(inject(function ($injector) {
    Definition = $injector.get('Definition');

    $rootScope = $injector.get('$rootScope');
    scope = $rootScope.$new();

    var $controller = $injector.get('$controller');

    createController = function(definitionMock) {
      return $controller('DefinitionDetailCtrl', {
        '$scope' : scope ,
        'definition': definitionMock
      });
    };

  }));

});


text:
package centos

import (
    "bytes"
    "crypto/rand"
    "database/sql"
    "encoding/base64"
    "errors"
    "fmt"
    "io"
    "log"
    "net"
    "os"
    "os/exec"
    "os/signal"
    "path/filepath"
    "strings"
    "syscall"
    "text/template"
    "time"

    "github.com/codegangsta/cli"
    da "github.com/flynn/discoverd/agent"
    "github.com/flynn/go-discoverd"
    _ "github.com/lib/pq"
)

func RunPg(c *cli.Context) {
    var addr string
    if len(c.String("discoverd")) > 0 {
        addr = c.String("discoverd")
    } else if len(os.Getenv("DISCOVERD")) > 0 {
        addr = os.Getenv("DISCOVERD")
    } else {
        log.Fatal("discoverd service ip is not defined")
    }

    set, err := discoverd.RegisterWithSet(c.String("service"), addr, nil)
    if err != nil {
        log.Fatal(err)
    }

    var username, password string
    var follower *follower
    var leader *exec.Cmd
    var done <-chan struct{}
    for l := range set.Leaders() {
        if l.Attrs["username"] != "" && l.Attrs["password"] != "" {
            username, password = l.Attrs["username"], l.Attrs["password"]
        }
        if l.Addr == set.SelfAddr() {
            if follower == nil {
                leader, done = startLeader(c)
            } else {
                leader, done = promoteToLeader(follower, username, password, c)
            }
            goto wait
        } else {
            if follower == nil {
                follower = startFollower(l, set, c)
            } else {
                follower = switchLeader(l, set, follower, c)
            }
        }
    }
    // TODO: handle service discovery disconnection

wait:
    set.Close()
    <-done
    procExit(leader)
}

func startLeader(c *cli.Context) (*exec.Cmd, <-chan struct{}) {
    log.Println("Starting as leader...")
    if err := dirIsEmpty(c.String("data")); err == nil {
        log.Println("Running initdb...")
        runCmd(exec.Command(
            filepath.Join(c.String("pgbin"), "initdb"),
            "-D", c.String("data"),
            "--encoding=UTF-8",
            "--locale=en_US.UTF-8", // TODO: make this configurable?
        ))
    } else if err != ErrNotEmpty {
        log.Fatal(err)
    }

    cmd, err := startPostgres(c)
    if err != nil {
        log.Fatal(err)
    }

    db := waitForPostgres(time.Minute, c)
    password := createSuperuser(db)
    db.Close()
    register(map[string]string{"username": "flynn", "password": password, "up": "true"}, c)

    done := make(chan struct{})
    go func() {
        cmd.Wait()
        close(done)
    }()

    return cmd, done
}

func register(attrs map[string]string, c *cli.Context) {
    err := discoverd.RegisterWithAttributes(c.String("service"), c.String("discoverd"), attrs)
    if err != nil {
        log.Fatalln("discoverd registration error:", err)
    }
}

func procExit(cmd *exec.Cmd) {
    discoverd.UnregisterAll()
    var status int
    if ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {
        status = ws.ExitStatus()
    }
    os.Exit(status)
}

func createSuperuser(db *sql.DB) (password string) {
    log.Println("Creating superuser...")
    password = generatePassword()

    _, err := db.Exec("DROP USER IF EXISTS flynn")
    if err != nil {
        log.Fatalln("Error dropping user:", err)
    }
    _, err = db.Exec("CREATE USER flynn WITH SUPERUSER CREATEDB CREATEROLE REPLICATION PASSWORD '" + password + "'")
    if err != nil {
        log.Fatalln("Error creating user:", err)
    }
    log.Println("Superuser created.")

    return
}

func generatePassword() string {
    b := make([]byte, 16)
    enc := make([]byte, 24)
    _, err := io.ReadFull(rand.Reader, b)
    if err != nil {
        panic(err) // This shouldn't ever happen, right?
    }
    base64.URLEncoding.Encode(enc, b)
    return string(bytes.TrimRight(enc, "="))
}

func GeneratePgDataSource(c *cli.Context) string {
    return "user=postgres host=/var/run/postgresql sslmode=disable port=" + c.String("port")
}

func waitForPostgres(maxWait time.Duration, c *cli.Context) *sql.DB {
    log.Println("Waiting for postgres to boot...")
    start := time.Now()
    for {
        var ping string
        db, err := sql.Open("postgres", GeneratePgDataSource(c))
        if err != nil {
            goto fail
        }
        err = db.QueryRow("SELECT 'ping'").Scan(&ping)
        if ping == "ping" {
            log.Println("Postgres is up.")
            return db
        }
        db.Close()

    fail:
        if time.Now().Sub(start) >= maxWait {
            log.Fatalf("Unable to connect to postgres after %s, last error: %q", maxWait, err)
        }
        time.Sleep(time.Second)
    }
}

func waitForPromotion(c *cli.Context) {
    log.Println("Waiting for promotion...")
    db, err := sql.Open("postgres", GeneratePgDataSource(c))
    if err != nil {
        log.Fatalln("Error connecting to postgres:", err)
    }
    defer db.Close()
    for {
        var recovery bool
        err := db.QueryRow("SELECT pg_is_in_recovery()").Scan(&recovery)
        if err != nil {
            log.Fatalln("Error checking recovery status:", err)
        }
        if !recovery {
            return
        }
        time.Sleep(time.Second)
    }
}

func promoteToLeader(follower *follower, username, password string, c *cli.Context) (*exec.Cmd, <-chan struct{}) {
    log.Println("Promoting follower to leader...")
    register(map[string]string{"up": "false"}, c)
    f, err := os.Create(filepath.Join(c.String("data"), "promote.trigger"))
    if err != nil {
        panic(err)
    }
    f.Close()

    waitForPromotion(c)

    if username == "" || password == "" {
        // TODO: create superuser
    }

    register(map[string]string{"up": "true", "username": username, "password": password}, c)
    log.Println("Follower promoted to leader.")
    return follower.Cancel()
}

func runCmd(cmd *exec.Cmd) {
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        if exitErr, ok := err.(*exec.ExitError); ok {
            if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
                os.Exit(status.ExitStatus())
            }
        }
        log.Fatal(err)
    }
}

func pullBaseBackup(s *discoverd.Service, c *cli.Context) {
    log.Println("Running pg_basebackup...")
    runCmd(exec.Command(filepath.Join(c.String("pgbin"),
        "pg_basebackup"),
        "-D", c.String("data"),
        "-d", fmt.Sprintf("host=%s port=%s user=%s password=%s", s.Host, s.Port, s.Attrs["username"], s.Attrs["password"]),
        "--xlog-method=stream",
        "--progress",
        "--verbose",
    ))
    log.Println("pg_basebackup complete.")
}

var recoveryTempl = template.Must(template.New("recovery").Parse(`
standby_mode = 'on'
primary_conninfo = 'host={{.Host}} port={{.Port}} user={{.Username}} password={{.Password}}'
trigger_file = '{{.Trigger}}'
`))

type recoveryConfig struct {
    Host     string
    Port     string
    Username string
    Password string
    Trigger  string
}

func writeRecoveryConf(leader *discoverd.Service, c *cli.Context) {
    f, err := os.Create(filepath.Join(c.String("data"), "recovery.conf"))
    if err != nil {
        log.Fatalln("Error creating recovery.conf:", err)
    }
    defer f.Close()

    err = recoveryTempl.Execute(f, &recoveryConfig{
        Host:     leader.Host,
        Port:     leader.Port,
        Username: leader.Attrs["username"],
        Password: leader.Attrs["password"],
        Trigger:  filepath.Join(c.String("data"), "promote.trigger"),
    })
    if err != nil {
        log.Fatalln("Error writing recovery.conf:", err)
    }
}

func updateToService(u *da.ServiceUpdate) *discoverd.Service {
    host, port, _ := net.SplitHostPort(u.Addr)
    return &discoverd.Service{
        Created: u.Created,
        Name:    u.Name,
        Addr:    u.Addr,
        Attrs:   u.Attrs,
        Host:    host,
        Port:    port,
    }
}

func waitForLeaderUp(leader *discoverd.Service, set discoverd.ServiceSet) *discoverd.Service {
    if leader.Attrs["up"] == "true" {
        return leader
    }
    log.Println("Waiting for leader to come up...")
    watch := set.Watch(true)
    defer set.Unwatch(watch)
    for update := range watch {
        if update.Addr == set.Leader().Addr && update.Attrs["up"] == "true" {
            return updateToService(update)
        }
    }
    return nil
}

func startFollower(leader *discoverd.Service, set discoverd.ServiceSet, c *cli.Context) *follower {
    log.Println("Starting as follower...")
    leader = waitForLeaderUp(leader, set)
    if err := dirIsEmpty(c.String("data")); err == nil {
        pullBaseBackup(leader, c)
    } else if err != ErrNotEmpty {
        log.Fatal(err)
    }

    writeRecoveryConf(leader, c)
    cmd, err := startPostgres(c)
    if err != nil {
        log.Fatal(err)
    }

    waitForPostgres(time.Minute, c).Close()
    register(map[string]string{"up": "true"}, c)
    log.Println("Follower started.")

    // TODO: if data and insufficient WAL, pg_basebackup
    return newFollower(cmd)
}

func switchLeader(leader *discoverd.Service, set discoverd.ServiceSet, follower *follower, c *cli.Context) *follower {
    log.Println("Switching leaders...")
    leader = waitForLeaderUp(leader, set)
    register(map[string]string{"up": "false"}, c)
    writeRecoveryConf(leader, c)
    follower.Stop()

    cmd, err := startPostgres(c)
    if err != nil {
        log.Fatal(err)
    }
    waitForPostgres(time.Minute, c).Close()
    // TODO: check for insufficient WAL, then pg_basebackup
    register(map[string]string{"up": "true"}, c)
    log.Println("Leader switch complete.")
    return newFollower(cmd)
}

func newFollower(cmd *exec.Cmd) *follower {
    f := &follower{
        cmd:  cmd,
        stop: make(chan struct{}),
        done: make(chan struct{}),
    }
    go f.wait()
    return f
}

type follower struct {
    cmd  *exec.Cmd
    stop chan struct{}
    done chan struct{}
}

func (f *follower) wait() {
    go func() {
        f.cmd.Wait()
        close(f.done)
    }()

    select {
    case <-f.done:
        procExit(f.cmd)
    case <-f.stop:
    }
}

func (f *follower) Cancel() (*exec.Cmd, <-chan struct{}) {
    close(f.stop)
    return f.cmd, f.done
}

func (f *follower) Stop() error {
    close(f.stop)
    if err := f.cmd.Process.Signal(syscall.SIGTERM); err != nil {
        return err
    }
    // TODO: escalate to kill?
    <-f.done
    return nil
}

func writeConfig(c *cli.Context) {
    folder := c.String("config")
    err := copyFile(filepath.Join(folder, "postgresql.conf"), filepath.Join(c.String("data"), "postgresql.conf"))
    if err != nil {
        log.Fatalln("Error creating postgresql.conf", err)
    }

    err = copyFile(filepath.Join(folder, "pg_hba.conf"), filepath.Join(c.String("data"), "pg_hba.conf"))
    if err != nil {
        log.Fatalln("Error creating pg_hba.conf", err)
    }

    //err = writeCert(os.Getenv("EXTERNAL_IP"), dataDir))
    //if err != nil {
    //log.Fatalln("Error writing ssl info", err)
    //}
}

func copyFile(src, dest string) error {
    sf, err := os.Open(src)
    if err != nil {
        return err
    }
    defer sf.Close()
    df, err := os.Create(dest)
    if err != nil {
        return err
    }
    defer df.Close()

    _, err = io.Copy(df, sf)
    return err
}

func startPostgres(c *cli.Context) (*exec.Cmd, error) {
    writeConfig(c)

    log.Println("Starting postgres...")
    cmd := exec.Command(
        filepath.Join(c.String("pgbin"), "postgres"),
        "-D", c.String("data"), // Set datadir
        "-p", c.String("port"), // Set port to $PORT
        "-h", "*", // Listen on all interfaces
        "-l", // Enable SSL
    )
    log.Println("exec", strings.Join(cmd.Args, " "))
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Start(); err != nil {
        return nil, err
    }
    go handleSignals(cmd)
    return cmd, nil
}

func handleSignals(cmd *exec.Cmd) {
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)

    sig := <-c
    discoverd.UnregisterAll()
    cmd.Process.Signal(sig)
}

var ErrNotEmpty = errors.New("directory is not empty")

func dirIsEmpty(dir string) error {
    d, err := os.Open(dir)
    if err != nil {
        if errno, ok := err.(syscall.Errno); ok && errno == syscall.ENOENT {
            return nil
        }
        return err
    }
    defer d.Close()

    for {
        fs, err := d.Readdir(10)
        if err != nil {
            if err == io.EOF {
                break
            }
            return err
        }
        for _, f := range fs {
            if !strings.HasPrefix(f.Name(), ".") {
                return ErrNotEmpty
            }
        }
    }

    return nil
}


text:
exports.dbname = "lrdata";
exports.dbuser = "lrdata";
exports.dbpassword = "test";

exports.lfmApiKey = 'c0db7c8bfb98655ab25aa2e959fdcc68';
exports.lfmApiSecret = 'aff4890d7cb9492bc72250abbeffc3e1';

exports.tagAgeBeforeRefresh = 14; // In days
exports.tagFetchFrequency = 1000; // In milliseconds


text:
package cn.pharmplus.xview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * The header view for {@link XListView} and {@link XScrollView}
 *
 */
public class XHeaderView extends LinearLayout {
	public final static int	STATE_NORMAL			= 0;
	public final static int	STATE_READY				= 1;
	public final static int	STATE_REFRESHING		= 2;
	public final static int	STATE_DONE				= 3;

	private final int		ROTATE_ANIM_DURATION	= 180;

	private LinearLayout	mContainer;
	private ImageView		mArrowImageView;
	private ProgressBar		mProgressBar;
	private TextView		mHintTextView;

	private int				mState					= STATE_NORMAL;

	private Animation		mRotateUpAnim;
	private Animation		mRotateDownAnim;

	private boolean			mIsFirst;

	public XHeaderView(Context context) {
		super(context);
		initView(context);
	}

	public XHeaderView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	private void initView(Context context) {
		// Initial set header view height 0
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0);
		mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.vw_header, null);
		addView(mContainer, lp);
		setGravity(Gravity.BOTTOM);

		mArrowImageView = (ImageView) findViewById(R.id.header_arrow);
		mHintTextView = (TextView) findViewById(R.id.header_hint_text);
		mProgressBar = (ProgressBar) findViewById(R.id.header_progressbar);

		/*anim_arrow = (AnimationDrawable) mArrowImageView.getDrawable();
		iv_loading = (ImageView) findViewById(R.id.iv_loading);
		anim_iv_loading = (AnimationDrawable) iv_loading.getDrawable();*/

		mRotateUpAnim = new RotateAnimation(0.0f, -180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
		mRotateUpAnim.setFillAfter(true);

		mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
		mRotateDownAnim.setFillAfter(true);
	}

	public void setState(int state) {
		if (state == mState && mIsFirst) {
			mIsFirst = true;
			return;
		}

		if (state == STATE_REFRESHING) {
			// show progress
			mArrowImageView.clearAnimation();
			mArrowImageView.setVisibility(View.INVISIBLE);
			mProgressBar.setVisibility(View.VISIBLE);
		}
		else if (state == STATE_DONE) {
			mArrowImageView.clearAnimation();
			mArrowImageView.setVisibility(View.INVISIBLE);
			mProgressBar.setVisibility(View.INVISIBLE);

		}
		else {
			// show arrow image
			mArrowImageView.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.INVISIBLE);
		}

		switch (state) {
		case STATE_NORMAL:
			if (mState == STATE_READY) {
				mArrowImageView.startAnimation(mRotateDownAnim);
			}

			if (mState == STATE_REFRESHING) {
				mArrowImageView.clearAnimation();
			}

			mHintTextView.setText(R.string.header_hint_refresh_normal);
			break;

		case STATE_READY:
			if (mState != STATE_READY) {
				mArrowImageView.clearAnimation();
				mArrowImageView.startAnimation(mRotateUpAnim);
				mHintTextView.setText(R.string.header_hint_refresh_ready);
			}
			break;

		case STATE_REFRESHING:
			mHintTextView.setText(R.string.header_hint_refresh_loading);
			break;
		case STATE_DONE:
			mHintTextView.setText(R.string.load_completed);
			break;

		default:
			break;
		}

		mState = state;
	}

	/**
	 * Set the header view visible height.
	 *
	 * @param height
	 */
	public void setVisibleHeight(int height) {
		if (height < 0)
			height = 0;
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer.getLayoutParams();
		lp.height = height;
		mContainer.setLayoutParams(lp);
	}

	/**
	 * Get the header view visible height.
	 *
	 * @return
	 */
	public int getVisibleHeight() {
		return mContainer.getLayoutParams().height;//getHeight();
	}

}


text:
"""
    sphinx.ext.todo
    ~~~~~~~~~~~~~~~

    Allow todos to be inserted into your documentation.  Inclusion of todos can
    be switched of by a configuration variable.  The todolist directive collects
    all todos of your project and lists them along with a backlink to the
    original location.

    :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from docutils import nodes
from docutils.parsers.rst import directives

import sphinx
from sphinx.locale import _
from sphinx.environment import NoUri
from sphinx.util.nodes import set_source_info
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives.admonitions import BaseAdmonition

class todo_node(nodes.Admonition, nodes.Element):
    pass

class todolist(nodes.General, nodes.Element):
    pass

class Todo(BaseAdmonition):
    """
    A todo entry, displayed (if configured) in the form of an admonition.
    """

    node_class = todo_node
    has_content = True
    required_arguments = 0
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {
        'class': directives.class_option,
    }

    def run(self):
        if not self.options.get('class'):
            self.options['class'] = ['admonition-todo']

        (todo,) = super(Todo, self).run()
        if isinstance(todo, nodes.system_message):
            return [todo]

        todo.insert(0, nodes.title(text=_('Todo')))
        set_source_info(self, todo)

        env = self.state.document.settings.env
        targetid = 'index-%s' % env.new_serialno('index')
        targetnode = nodes.target('', '', ids=[targetid])
        return [targetnode, todo]

def process_todos(app, doctree):
    # collect all todos in the environment
    # this is not done in the directive itself because it some transformations
    # must have already been run, e.g. substitutions
    env = app.builder.env
    if not hasattr(env, 'todo_all_todos'):
        env.todo_all_todos = []
    for node in doctree.traverse(todo_node):
        app.emit('todo-defined', node)

        try:
            targetnode = node.parent[node.parent.index(node) - 1]
            if not isinstance(targetnode, nodes.target):
                raise IndexError
        except IndexError:
            targetnode = None
        newnode = node.deepcopy()
        del newnode['ids']
        env.todo_all_todos.append({
            'docname': env.docname,
            'source': node.source or env.doc2path(env.docname),
            'lineno': node.line,
            'todo': newnode,
            'target': targetnode,
        })

        if env.config.todo_emit_warnings:
            env.warn_node("TODO entry found: %s" % node[1].astext(), node)

class TodoList(Directive):
    """
    A list of all todo entries.
    """

    has_content = False
    required_arguments = 0
    optional_arguments = 0
    final_argument_whitespace = False
    option_spec = {}

    def run(self):
        # Simply insert an empty todolist node which will be replaced later
        # when process_todo_nodes is called
        return [todolist('')]

def process_todo_nodes(app, doctree, fromdocname):
    if not app.config['todo_include_todos']:
        for node in doctree.traverse(todo_node):
            node.parent.remove(node)

    # Replace all todolist nodes with a list of the collected todos.
    # Augment each todo with a backlink to the original location.
    env = app.builder.env

    if not hasattr(env, 'todo_all_todos'):
        env.todo_all_todos = []

    for node in doctree.traverse(todolist):
        if not app.config['todo_include_todos']:
            node.replace_self([])
            continue

        content = []

        for todo_info in env.todo_all_todos:
            para = nodes.paragraph(classes=['todo-source'])
            if app.config['todo_link_only']:
                description = _('<<original entry>>')
            else:
                description = (
                    _('(The <<original entry>> is located in %s, line %d.)') %
                    (todo_info['source'], todo_info['lineno'])
                )
            desc1 = description[:description.find('<<')]
            desc2 = description[description.find('>>') + 2:]
            para += nodes.Text(desc1, desc1)

            # Create a reference
            newnode = nodes.reference('', '', internal=True)
            innernode = nodes.emphasis(_('original entry'), _('original entry'))
            try:
                newnode['refuri'] = app.builder.get_relative_uri(
                    fromdocname, todo_info['docname'])
                newnode['refuri'] += '#' + todo_info['target']['refid']
            except NoUri:
                # ignore if no URI can be determined, e.g. for LaTeX output
                pass
            newnode.append(innernode)
            para += newnode
            para += nodes.Text(desc2, desc2)

            # (Recursively) resolve references in the todo content
            todo_entry = todo_info['todo']
            env.resolve_references(todo_entry, todo_info['docname'],
                                   app.builder)

            # Insert into the todolist
            content.append(todo_entry)
            content.append(para)

        node.replace_self(content)

def purge_todos(app, env, docname):
    if not hasattr(env, 'todo_all_todos'):
        return
    env.todo_all_todos = [todo for todo in env.todo_all_todos
                          if todo['docname'] != docname]

def merge_info(app, env, docnames, other):
    if not hasattr(other, 'todo_all_todos'):
        return
    if not hasattr(env, 'todo_all_todos'):
        env.todo_all_todos = []
    env.todo_all_todos.extend(other.todo_all_todos)

def visit_todo_node(self, node):
    self.visit_admonition(node)
    # self.visit_admonition(node, 'todo')

def depart_todo_node(self, node):
    self.depart_admonition(node)

def setup(app):
    app.add_event('todo-defined')
    app.add_config_value('todo_include_todos', False, 'html')
    app.add_config_value('todo_link_only', False, 'html')
    app.add_config_value('todo_emit_warnings', False, 'html')

    app.add_node(todolist)
    app.add_node(todo_node,
                 html=(visit_todo_node, depart_todo_node),
                 latex=(visit_todo_node, depart_todo_node),
                 text=(visit_todo_node, depart_todo_node),
                 man=(visit_todo_node, depart_todo_node),
                 texinfo=(visit_todo_node, depart_todo_node))

    app.add_directive('todo', Todo)
    app.add_directive('todolist', TodoList)
    app.connect('doctree-read', process_todos)
    app.connect('doctree-resolved', process_todo_nodes)
    app.connect('env-purge-doc', purge_todos)
    app.connect('env-merge-info', merge_info)
    return {'version': sphinx.__display_version__, 'parallel_read_safe': True}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const visitor_keys_1 = require("./visitor-keys");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isValidNode(x) {
    return x !== null && typeof x === 'object' && typeof x.type === 'string';
}
function getVisitorKeysForNode(allVisitorKeys, node) {
    const keys = allVisitorKeys[node.type];
    return (keys !== null && keys !== void 0 ? keys : []);
}
class SimpleTraverser {
    constructor({ enter }) {
        this.allVisitorKeys = visitor_keys_1.visitorKeys;
        this.enter = enter;
    }
    traverse(node, parent) {
        if (!isValidNode(node)) {
            return;
        }
        this.enter(node, parent);
        const keys = getVisitorKeysForNode(this.allVisitorKeys, node);
        if (keys.length < 1) {
            return;
        }
        for (const key of keys) {
            const childOrChildren = node[key];
            if (Array.isArray(childOrChildren)) {
                for (const child of childOrChildren) {
                    this.traverse(child, node);
                }
            }
            else {
                this.traverse(childOrChildren, node);
            }
        }
    }
}
function simpleTraverse(startingNode, options) {
    new SimpleTraverser(options).traverse(startingNode, undefined);
}
exports.simpleTraverse = simpleTraverse;
//# sourceMappingURL=simple-traverse.js.map


text:
/* ALL-ADMIN STYLES */
.applications .subPane {
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	border-radius: 10pt;
}

.applications .dragSource table {
	border-collapse: collapse !important;
}

.applications .dragSource table td:hover {
	background-color: #FF8 !important;
}

.applications textarea {
	font-size: 10px !important;
	white-space: pre-wrap !important;
}

.applications textarea,
.applications td {
	word-wrap: break-word !important;
	z-index: 900 !important;
	min-height: 25px !important;
}

.applications .dragSource textarea, .applications .dragSource td {
	min-height: 20px !important;
}

/* MAIN PANES */
.applications .rightPane {
	left: 780px !important;
}

/* DRAG SOURCE */
.applications .dragSource {
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	border-radius:8pt;

	background:#FFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	/*margin-top: 5px;*/
	width: 120px;
	height: 260px;
	min-height: 100px;

	text-align: left;
	/*color: #339;*/
	/*color: darkgreen;*/
	/*font-weight: bold;*/
	font-family: Verdana;
	font-size: 12px;
	border-color: #333;

	/* NEEDED SO THAT SCROLLBAR WILL SHOW */
	display: block !important;
	overflow:auto !important;
}

.dijitTabPaneWrapper .dijitTabContainerTop-container .dijitAlignClient,
.applications .dijitTabPaneWrapper,
.applications .tundra .dijitTabPaneWrapper,
.tundra .applications .dijitTabPaneWrapper {
	height: 100% !important;
}

.applications .dragSource table td:hover {
	background-color: #FF8 !important;
}

.applications .dojoDndItem .dojoDndItemOver {
	background-color: #FF8 !important;
}

.applications .dojoDndItem {
    min-height: 24px !important;
	padding-bottom: 2px !important;
}

/* SHOW LOCKED/UNLOCKED */
.applications .dragSource td {
	/*background: none repeat scroll 0 0 #FFF !important; */
	background-color: #FFF !important;
}

.applications .dragSource .dojoDndItem,
.applications .dragSource .dojoDndItemOver,
.applications .dragSource .dojoDndItemAnchor {
	/*background-color: #CCFFCC !important;*/
	background-color: #DAF0F2 !important;
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	border-radius:8pt;
}

.applications .dragSource .dojoDndContainerOver {
	border : inherit !important;
}

.applications .dragSource .dojoDndItemOver,
.applications .dragSource .dojoDndItemAnchor {
	background-color: #88FF88 !important;
	/*background-color: #DAF0F2 !important;*/
}

/* EDITING ROW */
.applications .editRow {
	width: 100% !important;
	height: auto !important;
	white-space: pre !important;
}

/* TAB BACKGROUND COLOUR */
.applications .dijitTabContent {
	/*background-color: #EEE;*/
}

/* TAB LABEL SIZE */
.applications .dijitTabInnerDiv .dijitTabContent {
	-moz-background-clip: border;
	-moz-background-inline-policy: continuous;
	-moz-background-origin: padding;
	position: relative;

	/* IF UNCOMMENTED PUTS A WHITE BLANK IN ADJACENT TAB WHEN NOT FOCUSED */
	/*background: transparent url(../images/tabContainerSprite.gif) repeat-x scroll 0 -350px;*/

	/* CHANGE THE HEIGHT OF THE TAB LABEL HERE */
	/*padding: 5px 3px 4px 4px;*/

	/*padding: 0px 0px 0px 0px !important;*/
}

/* DECREASE TABLE LABEL SIZE */
.applications .dijitTabInnerDiv {
	/*padding: 0px 0px 0px 0px !important;*/
}

/* TAB LABELS */
.applications .tabLabel {
	color: #243C5F !important;
	padding: 3px;
	border: solid 2px transparent;
	font-size: 14px;
	font-weight: bold;
}

.applications .dijitTabChecked .tabLabel {
	color: darkred !important;
	/*color: #055817;*/ /* dark green */
	font-weight: bold;
}

.applications .dijitFocused .tabLabel {
	padding: 3px;
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	border-radius:3pt;
	-moz-outline-style: none;
}

.applications .tabTitle {
	color: white;
	background-color: #264eea;
	text-align: center;
	vertical-align: middle;
	font-size: 20px;
	font-weight: bold;
	-moz-user-select: none !important;
}

/* PANES & CONTAINERS */

.applications .middlePane {
	left: 390px !important;
}

.applications .dijitTabContainer .tabStripButton {
    display: none;
    visibility: hidden;
    z-index: 12;
}

/* NO SCROLLBARS IN LEFT, MIDDLE AND RIGHT PANES */
.applications .dijitContentPane {
	overflow: hidden !important;
}

/* CONTAINERS HAVE WHITE BACKGROUND AND NO PADDING */
.applications .dijitBorderContainer {
	background-color: #FFF;
	padding: 0;
}

.applications .inputsTitlePane {
	background-color: #000;
}

/* CONTAINER HEIGHT */
.browserContainer {
	height:	900px;
}

.applications .dijitLayoutContainer {
	top: 0px;
	left: 0px;
}

.applications .dijitTabPaneWrapper {
	width: auto !important;
	/*top: 20px !important;*/
	/*border: none;*/
}

.applications .dijitTabPaneWrapper .dijitTabContainerTop-container .dijitAlignClient{
	height: auto;
}

.applications .groups .dijitContentPane .dijitTabPane .dijitTabContainerTop-dijitContentPane {
	width: auto !important;
}


text:
import * as angular from 'angular';

describe('messageBarDirective: <uif-message-bar />', () => {
    let $element: JQuery;
    let $scope: any;

    beforeEach(() => {
        angular.mock.module('officeuifabric.core');
        angular.mock.module('officeuifabric.components.messagebar');
    });

    beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => {
        $element = angular.element(`
        <uif-message-bar>
            <uif-content>
                {{message}}
            </uif-content>
            <uif-link ng-href="{{link.url}}">{{link.text}}</uif-link>
        </uif-message-bar>
        `);
        $scope = $rootScope;
        $compile($element)($scope);
        $scope.$digest();
        $element = jQuery($element[0]);
    }));

    it('should render HTML', (): void => {
        let divs: JQuery = $element.find('div');
        expect(divs.length).toBe(4, 'There should be 4 divs');

        let icon: JQuery = $element.find('i');
        expect(icon.length).toBe(1, 'There should be one i tag');

        let link: JQuery = $element.find('a');
        expect(link.length).toBe(1, 'There should be one a tag');

    });

    it('should be able to render uif-content message', (): void => {
        $scope.message = 'Lorem ipsum message';
        $scope.$digest();

        let content: JQuery = $element.find('span.uif-content');

        expect(content.html()).toContain('Lorem ipsum message', 'Message should be placed in uif-content block.');
    });

    it('should be able to render uif-link', inject(
        (
            $compile: Function,
            $rootScope: angular.IRootScopeService,
            $log: angular.ILogService) => {

            let scope: any = $rootScope.$new();
            scope.link = {};
            scope.link.url = 'http://ngofficeuifabric.com';
            scope.link.text = 'Lorem ipsum';

            let element: JQuery = angular.element(`
            <uif-message-bar>
                <uif-content>
                    {{message}}
                </uif-content>
                <uif-link ng-href="{{link.url}}">{{link.text}}</uif-link>
            </uif-message-bar>
            `);
            $compile(element)(scope);
            scope.$digest();

            element = jQuery(element[0]);
            let link: JQuery = element.find('.ms-Link');

            expect(link.attr('href')).toContain(scope.link.url, 'Link url should be set.');
            expect(link.html()).toContain(scope.link.text, 'Link Text should be set.');

        }
    ));

    it('should be validating uif-type attribute', inject(
        (
            $compile: Function,
            $rootScope: angular.IRootScopeService,
            $log: angular.ILogService) => {

            let scope: any = $rootScope.$new();

            expect($log.error.logs.length).toBe(0);

            let element: JQuery = angular.element(`
            <uif-message-bar uif-type="invalid">
                <uif-content>
                    {{message}}
                </uif-content>
                <uif-link ng-href="{{link.url}}">{{link.text}}</uif-link>
            </uif-message-bar>
            `);
            $compile(element)(scope);
            scope.$digest();
            element = jQuery(element[0]);

            expect($log.error.logs[0]).toContain('Error [ngOfficeUiFabric] officeuifabric.components.messagebar - Unsupported type: ' +
                'The type (\'invalid\') is not supported by the Office UI Fabric. ' +
                'Supported options are listed here: ' +
                'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/messagebar/' +
                'messageBarTypeEnum.ts');
        })
    );
    it('should be set icons for uif-type attribute', inject(
        (
            $compile: Function,
            $rootScope: angular.IRootScopeService,
            $log: angular.ILogService) => {

            let scope: any = $rootScope.$new();

            let element: JQuery = angular.element(`
            <uif-message-bar uif-type="error">
                <uif-content>
                    {{message}}
                </uif-content>
                <uif-link ng-href="{{link.url}}">{{link.text}}</uif-link>
            </uif-message-bar>
            `);
            $compile(element)(scope);
            scope.$digest();
            element = jQuery(element[0]);

            let icon: JQuery = element.find('.ms-Icon');
            expect(icon.hasClass('ms-Icon--xCircle')).toBe(true, 'icon for type error is set');
        })
    );

    it('should allow to interpolate uif-type value', inject(
        (
            $compile: Function,
            $rootScope: angular.IRootScopeService,
            $log: angular.ILogService) => {

            let scope: any = $rootScope.$new();

            scope.type = 'error';

            let element: JQuery = angular.element(`
            <uif-message-bar uif-type="{{type}}">
                <uif-content>
                    {{message}}
                </uif-content>
                <uif-link ng-href="{{link.url}}">{{link.text}}</uif-link>
            </uif-message-bar>
            `);
            $compile(element)(scope);
            scope.$digest();
            element = jQuery(element[0]);

            let icon: JQuery = element.find('.ms-Icon');
            expect(icon.hasClass('ms-Icon--xCircle')).toBe(true, 'icon for type error is set');
        })
    );
});


text:
//
//  TKCardModalViewController.m
//  Created by Devin Ross on 10/13/14.
//

#import "TKCardModalViewController.h"
#import "UIDevice+TKCategory.h"
#import "TKGlobal.h"
#import "UIGestureRecognizer+TKCategory.h"

@interface TKCardModalViewController () <UIGestureRecognizerDelegate>

@property (nonatomic,strong) UIDynamicAnimator *animator;
@property (nonatomic) UIAttachmentBehavior* attachmentBehavior;
@property (nonatomic,strong) UIPushBehavior *pushBehavior;
@property (nonatomic, strong) UIDynamicItemBehavior *itemBehavior;

@property (nonatomic,assign) CGFloat angle;
@property (nonatomic,assign) CGFloat magnitude;
@property (nonatomic,assign) CGPoint cardRestingPosition;

@property (nonatomic,strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic,strong) UIPanGestureRecognizer *panGesture;

@end

static const CGFloat _resistance = 0.0f;						// linear resistance applied to the image's dynamic item behavior
static const CGFloat _density = 1.0f;							// relative mass density applied to the image's dynamic item behavior
static const CGFloat _velocityFactor = 1.0f;					// affects how quickly the view is pushed out of the view
static const CGFloat _angularVelocityFactor = 1.0f;				// adjusts the amount of spin applied to the view during a push force, increases towards the view bounds
static const CGFloat _minimumVelocityRequiredForPush = 50.0f;	// defines how much velocity is required for the push behavior to be applied

@implementation TKCardModalViewController

- (instancetype) init{
	if(!(self=[super init])) return nil;
	self.modalPresentationStyle = UIModalPresentationCustom;
	self.transitioningDelegate = self;
	self.tapToDismissEnabled = YES;
	self.throwToDismissEnabled = YES;
	return self;
}
- (NSUInteger) supportedInterfaceOrientations{
	if([UIDevice padIdiom])
		return UIInterfaceOrientationMaskAll;
	return UIInterfaceOrientationMaskPortrait;
}

#pragma mark View Lifecycle
- (void) loadView{
	[super loadView];
	self.view.backgroundColor = [UIColor clearColor];

	self.visibleFrame = self.view.bounds;

	self.backgroundView = [[UIView alloc] initWithFrame:self.view.bounds];
	self.backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
	self.backgroundView.alpha = 0;
	[self.view addSubview:self.backgroundView];

	CGSize s = CGSizeMake(280, 200);
	CGRect alertRect = CGRectMakeWithSize( (CGFrameGetWidth(self.view)- s.width)/2.0f, (CGFrameGetHeight(self.view)- s.height)/2.0f, s);

	self.contentView = [[UIView alloc] initWithFrame:alertRect];
	self.contentView.backgroundColor = [UIColor whiteColor];
	self.contentView.layer.shadowOffset = CGSizeMake(0, 1);
	self.contentView.layer.shadowColor = [UIColor blackColor].CGColor;
	self.contentView.layer.shadowRadius = 3;
	self.contentView.layer.shadowOpacity = 0.1;
	self.contentView.layer.cornerRadius = 8;
	self.contentView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
	[self.view addSubview:self.contentView];

	self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
	self.panGesture.enabled = self.throwToDismissEnabled;
	[self.contentView addGestureRecognizer:self.panGesture];

	self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
	self.tapGesture.enabled = self.tapToDismissEnabled;
	self.tapGesture.delegate = self;
	[self.view addGestureRecognizer:self.tapGesture];

	self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

}
- (void) viewDidLoad{
	[super viewDidLoad];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void) viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];

	if (NSStringFromClass([UIInterpolatingMotionEffect class])) {
		UIInterpolatingMotionEffect *mx;

		mx = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
		mx.maximumRelativeValue = @(15);
		mx.minimumRelativeValue = @(-15);
		[self.contentView addMotionEffect:mx];

		mx = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
		mx.maximumRelativeValue = @(15);
		mx.minimumRelativeValue = @(-15);
		[self.contentView addMotionEffect:mx];
	}
}

- (void) keyboardWillShow:(NSNotification*)notification{

	NSValue *keyRectVal = notification.userInfo[UIKeyboardFrameEndUserInfoKey];
	CGRect keyFrame = [keyRectVal CGRectValue];

	CGRect bounds = self.view.bounds;
	bounds.origin.y = 20;
	bounds.size.height -= keyFrame.size.height;
	bounds.size.height -= 20;

	self.visibleFrame = bounds;

	[UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0.4 options:0 animations:^{
		self.contentView.center = CGPointMake(self.contentView.center.x, bounds.size.height/2);
	}completion:^(BOOL finished) {

	}];
}
- (void) keyboardWillHide:(NSNotification*)notification{

	self.visibleFrame = self.view.bounds;

	[UIView animateWithDuration:0.9 delay:0.3 usingSpringWithDamping:0.6 initialSpringVelocity:0.6 options:0 animations:^{
		self.contentView.center = CGPointMake(self.contentView.center.x, (CGFrameGetHeight(self.view)-20) / 2 + 20);
	}completion:nil];
}

- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
	CGPoint p = [touch locationInView:self.contentView.superview];
	if(gestureRecognizer == self.tapGesture && CGRectContainsPoint(self.contentView.frame, p))
		return NO;
	return YES;
}

- (void) tapped:(UITapGestureRecognizer*)sender{

	if(self.onlyAllowTapOffCardToDismiss){
		CGPoint p = [sender locationInView:self.contentView.superview];
		if(!CGRectContainsPoint(self.contentView.frame, p)) [self hide];
	}else
		[self hide];

}
- (void) pan:(UIPanGestureRecognizer*)gesture{
	if(!self.throwToDismissEnabled) return;

	UIView *view = gesture.view;
	UIView *cnt = view.superview;

	CGPoint p = [gesture locationInView:view.superview];
	CGPoint velocity = [gesture velocityInView:cnt];
	CGFloat magnitude = sqrt(pow(velocity.x,2) + pow(velocity.y, 2));
	UIOffset offset = UIOffsetMake(p.x - view.center.x, p.y - view.center.y);
	CGPoint o = CGPointMake(CGRectGetMidX(cnt.bounds), CGRectGetMidY(cnt.bounds));
	CGFloat angle = atan2(p.y-o.y, p.x-o.x);

	if(gesture.began){

		self.cardRestingPosition = self.contentView.center;

		[self.animator removeAllBehaviors];

		self.itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[view]];
		self.itemBehavior.elasticity = 0.0f;
		self.itemBehavior.friction = 0.2f;
		self.itemBehavior.allowsRotation = YES;
		self.itemBehavior.density = _density;
		self.itemBehavior.resistance = _resistance;
		[self.animator addBehavior:self.itemBehavior];

		self.attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:view offsetFromCenter:offset attachedToAnchor:p];
		[self.animator addBehavior:self.attachmentBehavior];

	}

	self.attachmentBehavior.anchorPoint = p;

	if(gesture.changed){
		self.angle = angle;
		self.magnitude = magnitude;
	}

	if(gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled){

		[self.animator removeAllBehaviors];
		CGPoint location = [gesture locationInView:cnt];
		CGPoint boxLocation = [gesture locationInView:view];

		// need to scale velocity values to tame down physics on the iPad
		CGFloat deviceVelocityScale = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 0.2f : 1.0f;
		CGFloat deviceAngularScale = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 0.7f : 1.0f;
		// factor to increase delay before `dismissAfterPush` is called on iPad to account for more area to cover to disappear
		//CGFloat deviceDismissDelay = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 1.8f : 1.0f;
		CGPoint velocity = [gesture velocityInView:self.view];
		CGFloat velocityAdjust = 10.0f * deviceVelocityScale;

		if (fabs(velocity.x / velocityAdjust) > _minimumVelocityRequiredForPush || fabs(velocity.y / velocityAdjust) > _minimumVelocityRequiredForPush) {

			self.pushBehavior = [[UIPushBehavior alloc] initWithItems:@[view] mode:UIPushBehaviorModeInstantaneous];
			self.pushBehavior.angle = 0.0f;
			self.pushBehavior.magnitude = 0.0f;

			UIOffset offsetFromCenter = UIOffsetMake(boxLocation.x - CGRectGetMidX(view.bounds), boxLocation.y - CGRectGetMidY(view.bounds));
			CGFloat radius = sqrtf(powf(offsetFromCenter.horizontal, 2.0f) + powf(offsetFromCenter.vertical, 2.0f));
			CGFloat pushVelocity = sqrtf(powf(velocity.x, 2.0f) + powf(velocity.y, 2.0f));

			// calculate angles needed for angular velocity formula
			CGFloat velocityAngle = atan2f(velocity.y, velocity.x);
			CGFloat locationAngle = atan2f(offsetFromCenter.vertical, offsetFromCenter.horizontal);
			if (locationAngle > 0) {
				locationAngle -= M_PI * 2;
			}

			// angle (θ) is the angle between the push vector (V) and vector component parallel to radius, so it should always be positive
			CGFloat angle = fabsf(fabsf(velocityAngle) - fabsf(locationAngle));
			// angular velocity formula: w = (abs(V) * sin(θ)) / abs(r)
			CGFloat angularVelocity = fabsf((fabsf(pushVelocity) * sinf(angle)) / fabsf(radius));

			// rotation direction is dependent upon which corner was pushed relative to the center of the view
			// when velocity.y is positive, pushes to the right of center rotate clockwise, left is counterclockwise
			CGFloat direction = (location.x < view.center.x) ? -1.0f : 1.0f;
			// when y component of velocity is negative, reverse direction
			if (velocity.y < 0) { direction *= -1; }

			// amount of angular velocity should be relative to how close to the edge of the view the force originated
			// angular velocity is reduced the closer to the center the force is applied
			// for angular velocity: positive = clockwise, negative = counterclockwise
			CGFloat xRatioFromCenter = fabsf(offsetFromCenter.horizontal) / (CGRectGetWidth(view.frame) / 2.0f);
			CGFloat yRatioFromCetner = fabsf(offsetFromCenter.vertical) / (CGRectGetHeight(view.frame) / 2.0f);

			// apply device scale to angular velocity
			angularVelocity *= deviceAngularScale;
			// adjust angular velocity based on distance from center, force applied farther towards the edges gets more spin
			angularVelocity *= ((xRatioFromCenter + yRatioFromCetner) / 2.0f);

			[self.itemBehavior addAngularVelocity:angularVelocity * _angularVelocityFactor * direction forItem:view];
			[self.animator addBehavior:self.pushBehavior];
			self.pushBehavior.pushDirection = CGVectorMake((velocity.x / velocityAdjust) * _velocityFactor, (velocity.y / velocityAdjust) * _velocityFactor);
			self.pushBehavior.active = YES;
			[self.animator addBehavior:self.pushBehavior];

			CGFloat dimension = MAX(CGFrameGetHeight(self.contentView),CGFrameGetWidth(self.contentView)) * 1.2;
			dimension = -MAX(dimension,420);

			UICollisionBehavior *collide = [[UICollisionBehavior alloc] initWithItems:@[view]];
			collide.translatesReferenceBoundsIntoBoundary = YES;
			[collide setTranslatesReferenceBoundsIntoBoundaryWithInsets:UIEdgeInsetsMake(dimension, dimension, dimension, dimension)];
			collide.collisionDelegate = self;
			[self.animator addBehavior:collide];

			// delay for dismissing is based on push velocity also
			return;
		}

		CGPoint pp = [self.view convertPoint:self.cardRestingPosition toView:cnt];
		UISnapBehavior *snapBehavior = [[UISnapBehavior alloc] initWithItem:view snapToPoint:pp];
		snapBehavior.damping = 0.85;
		[self.animator addBehavior:snapBehavior];

	}

}

- (void) show{
	id <UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
	[[delegate window].rootViewController presentViewController:self animated:YES completion:nil];
}
- (void) hide{
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark UIViewControllerTransitioningDelegate
- (NSTimeInterval) transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{

	UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

	if([toVC isKindOfClass:[self class]])
		return 0.8f;
	return 0.4f + 0.5f;
}
- (void) showAlertView:(id<UIViewControllerContextTransitioning>)transitionContext{

	UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

	UIView *containerView = [transitionContext containerView];
	[containerView addSubview:toVC.view];

	toVC.view.frame = CGRectMake(0, 0, CGRectGetWidth(containerView.frame), CGRectGetHeight(containerView.frame));

	CGFloat originalX = self.contentView.center.x;
	CGFloat originalMinX = CGFrameGetMinX(self.contentView);

	self.contentView.center = CGPointMake(originalX, -300);
	self.contentView.transform = CGRotate(-10 * M_PI / 180.0f);

	[UIView animateWithDuration:0.4 animations:^{
		self.backgroundView.alpha = 1;
	}];

	[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0 usingSpringWithDamping:0.7 initialSpringVelocity:0.3 options:0 animations:^{
		self.contentView.transform = CGAffineTransformIdentity;
		NSInteger y = (CGRectGetHeight(self.visibleFrame) - CGFrameGetHeight(self.contentView)) / 2;
		self.contentView.frame = CGRectMake(originalMinX, y, CGFrameGetWidth(self.contentView), CGFrameGetHeight(self.contentView));
	} completion:^(BOOL finished) {
		[transitionContext completeTransition:YES];
	}];

}
- (void) hideAlertView:(id<UIViewControllerContextTransitioning>)transitionContext{

	if(self.contentView.superview){

		if(!self.animator)
			self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

		[self.animator removeAllBehaviors];

		UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self.contentView]];
		gravity.magnitude = 3;
		[self.animator addBehavior:gravity];

		UIDynamicItemBehavior *behav = [[UIDynamicItemBehavior alloc] initWithItems:@[self.contentView]];
		behav.allowsRotation = YES;
		behav.friction = 0.5;

		CGFloat velocity = (arc4random() % 20) - 10.0f;
		velocity /= 100.0f;
		[behav addAngularVelocity:velocity forItem:self.contentView];
		[self.animator addBehavior:behav];

	}

	[UIView animateWithDuration:0.4 delay:0.4 options:0 animations:^{
		self.backgroundView.transform = CGAffineTransformIdentity;
		self.backgroundView.alpha = 0;
	} completion:^(BOOL finished){
		[self.view removeFromSuperview];
		[transitionContext completeTransition:YES];
	}];

}
- (void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{

	UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

	if([toVC isKindOfClass:[self class]])
		[self showAlertView:transitionContext];
	else
		[self hideAlertView:transitionContext];

}

- (id <UIViewControllerAnimatedTransitioning>) animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
	return self;
}
- (id <UIViewControllerAnimatedTransitioning>) animationControllerForDismissedController:(UIViewController *)dismissed{
	return self;
}
- (void) collisionBehavior:(UICollisionBehavior*)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p{
	[self.animator removeAllBehaviors];
	[self.contentView removeFromSuperview];
	[self hide];
}

#pragma mark Properties
- (void) setTapToDismissEnabled:(BOOL)tapToDismissEnabled{
	_tapToDismissEnabled = tapToDismissEnabled;
	self.tapGesture.enabled = tapToDismissEnabled;
}
- (void) setThrowToDismissEnabled:(BOOL)throwToDismissEnabled{
	_throwToDismissEnabled = throwToDismissEnabled;
	self.panGesture.enabled = throwToDismissEnabled;
}

@end


text:
using Buildron.Domain.Versions;
using UnityEngine;
#endregion

namespace Buildron.Infrastructure.Repositories
{
	public class PlayerPrefsVersionRepository : IVersionRepository
	{
		#region IVersionRepository implementation
		public void Save (Version version)
		{
			PlayerPrefs.SetString ("Version.ClientId", version.ClientId);
			PlayerPrefs.SetInt ("Version.ClientInstance", version.ClientInstance);
		}

		public Version Find ()
		{
			Version version = null;

			if (PlayerPrefs.HasKey ("Version.ClientId")) {
				version = new Version ();
				version.ClientId = PlayerPrefs.GetString ("Version.ClientId");
				version.ClientInstance = PlayerPrefs.GetInt ("Version.ClientInstance");
			}

			return version;
		}
		#endregion
	}
}


text:
import './bootstrap';
import './vue';

$(document).ready(function () {
    "use strict";

    $("body").tooltip({
        selector: "[data-toggle=tooltip]"
    });

    $('[data-toggle="popover"]').popover();

    /**
     * ScrollUp.
     */
    $.scrollUp({
        scrollName: "scrollUp",
        scrollDistance: 300,
        scrollFrom: "top",
        scrollSpeed: 1000,
        easingType: "easeInOutCubic",
        animation: "fade",
        animationInSpeed: 200,
        animationOutSpeed: 200,
        scrollText: '<i class="fa fa-chevron-up"></i>',
        scrollTitle: " ",
        scrollImg: 0,
        activeOverlay: 0,
        zIndex: 1001
    });

    /**
     * Navbar
     */
    var minWidth = 767,
        navbar = $('#change-navbar'),
        offset = navbar.offset(),
        width = window.innerWidth;

    if (navbar.length && width >= minWidth){
        $(document).scroll(function() {
            var scrollStart = $(this).scrollTop();
            if (scrollStart > (offset.top - 60)) {
                $('.navbar').attr('style', 'background-color: #FFFFFF  !important;');
                $('.navbar-hello-text').removeClass('text-white').attr('style', 'color: #506a85 !important;');
                $('.navbar-brand').removeClass('text-white').attr('style', 'color: #506a85 !important;');
                $('.btn-header-register-login').removeClass('btn-outline-primary-inverse').addClass('btn-outline-primary');
            } else {
                $('.navbar').attr('style', 'background-color: transparent !important;');
                $('.navbar-hello-text').addClass('text-white').removeAttr('style');
                $('.navbar-brand').addClass('text-white').removeAttr('style');
                $('.btn-header-register-login').removeClass('btn-outline-primary').addClass('btn-outline-primary-inverse');
            }
        });
    }
});

/*app = {

    init: function() {
        alert('test');
    }

};
module.exports = app;*/


text:
title: django.utils.html format_html Example Code
category: page
slug: django-utils-html-format-html-examples
sortorder: 500013705
toc: False
sidebartitle: django.utils.html format_html
meta: Python code examples for using the format_html function contained within Django's django.utils.html module.

[format_html](https://github.com/django/django/blob/master/django/utils/html.py)
is a function within the [Django](/django.html) project that is like
`str.format` but for [HTML](/hypertext-markup-language-html.html) content.
The function allows a program to safely create small HTML fragments to
render, most likely in an output webpaage.

Understanding these concepts are useful when coding with projects
that use Django's `format_html` function:

* [Django](/django.html) and [Django templates](/django-templates.html)
* [Web development](/web-development.html),
  [web frameworks](/web-frameworks.html) and
  [HTML](/hypertext-markup-language-html.html)
* [Angular](/angular.html) and [JavaScript](/javascript.html)

You can also view the [complete all topics page](/table-of-contents.html)
for even more resources.

## Example 1 from django-angular
[django-angular](https://github.com/jrief/django-angular)
([project examples website](https://django-angular.awesto.com/classic_form/))
is a library with helper code to make it easier to use
[Angular](/angular.html) as the front-end to [Django](/django.html) projects.
The code for django-angular is
[open source under the MIT license](https://github.com/jrief/django-angular/blob/master/LICENSE.txt).

[**django-angular / djng / templatetags / djng_tags.py**](https://github.com/jrief/django-angular/blob/master/djng/templatetags/djng_tags.py)

```python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import json

from django.template import Library
from django.template.base import Node, NodeList, TextNode, VariableNode
~~from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import get_language_from_request

from djng.core.urlresolvers import (get_all_remote_methods,
                                    get_current_remote_methods)

register = Library()

@register.simple_tag(name='djng_all_rmi')
def djng_all_rmi():
    """
    Returns a dictionary of all methods for all Views available for
    this project, marked with the ``@allow_remote_invocation``
    decorator. The return string can be used directly to initialize
    the AngularJS provider, such as
    ``djangoRMIProvider.configure({% djng_rmi_configs %});``
    """
    return mark_safe(json.dumps(get_all_remote_methods()))

@register.simple_tag(name='djng_current_rmi', takes_context=True)
def djng_current_rmi(context):
    """
    Returns a dictionary of all methods for the current View of
    this request, marked with the @allow_remote_invocation decorator.
    The return string can be used directly to initialize the
    AngularJS provider, such as
    ``djangoRMIProvider.configure({% djng_current_rmi %});``
    """
    return mark_safe(json.dumps(get_current_remote_methods(context.get('view'))))

@register.simple_tag(name='load_djng_urls', takes_context=True)
def djng_urls(context, *namespaces):
    raise DeprecationWarning(
        "load_djng_urls templatetag is deprecated and has " + \
        "been removed from this version of django-angular."
        "Please refer to documentation for updated way to " + \
        "manage django urls in angular.")

class AngularJsNode(Node):
    def __init__(self, django_nodelist, angular_nodelist, variable):
        self.django_nodelist = django_nodelist
        self.angular_nodelist = angular_nodelist
        self.variable = variable

    def render(self, context):
        if self.variable.resolve(context):
            return self.angular_nodelist.render(context)
        return self.django_nodelist.render(context)

@register.tag
def angularjs(parser, token):
    """
    Conditionally switch between AngularJS and Django variable
    expansion for ``{{`` and ``}}`` keeping Django's expansion
    for ``{%`` and ``%}``
    Usage::
        {% angularjs 1 %} or simply {% angularjs %}
            {% process variables through the AngularJS template engine %}
        {% endangularjs %}
        {% angularjs 0 %}
            {% process variables through the Django template engine %}
        {% endangularjs %}
        Instead of 0 and 1, it is possible to use a context variable.
    """
    bits = token.contents.split()
    if len(bits) < 2:
        bits.append('1')
    values = [parser.compile_filter(bit) for bit in bits[1:]]
    django_nodelist = parser.parse(('endangularjs',))
    angular_nodelist = NodeList()
    for node in django_nodelist:
        # convert all occurrences of VariableNode into a TextNode using the
        # AngularJS double curly bracket notation
        if isinstance(node, VariableNode):
            # convert Django's array notation into JS array notation
            tokens = node.filter_expression.token.split('.')
            token = tokens[0]
            for part in tokens[1:]:
                if part.isdigit():
                    token += '[%s]' % part
                else:
                    token += '.%s' % part
            node = TextNode('{{ %s }}' % token)
        angular_nodelist.append(node)
    parser.delete_first_token()
    return AngularJsNode(django_nodelist, angular_nodelist, values[0])

@register.simple_tag(name='djng_locale_script', takes_context=True)
def djng_locale_script(context, default_language='en'):
    """
    Returns a script tag for including the proper locale
    script in any HTML page. This tag determines the current
    language with its locale.
    Usage:
        <script src="{% static 'node_modules/angular-i18n/' %}
        {% djng_locale_script %}"></script>
    or, if used with a default language:
        <script src="{% static 'node_modules/angular-i18n/' %}
        {% djng_locale_script 'de' %}"></script>
    """
    language = get_language_from_request(context['request'])
    if not language:
        language = default_language
~~    return format_html('angular-locale_{}.js', language.lower())
```

## Example 2 from AuditLog
[Auditlog](https://github.com/jjkester/django-auditlog)
([project documentation](https://django-auditlog.readthedocs.io/en/latest/))
is a [Django](/django.html) app that logs changes to Python objects,
similar to the Django admin's logs but with more details and
output formats. Auditlog's source code is provided as open source under the
[MIT license](https://github.com/jjkester/django-auditlog/blob/master/LICENSE).

[**django-auditlog / src / auditlog / mixins.py**](https://github.com/jjkester/django-auditlog/blob/master/src/auditlog/mixins.py)

```python
import json

from django.conf import settings
try:
    from django.core import urlresolvers
except ImportError:
    from django import urls as urlresolvers
try:
    from django.urls.exceptions import NoReverseMatch
except ImportError:
    from django.core.urlresolvers import NoReverseMatch
~~from django.utils.html import format_html
from django.utils.safestring import mark_safe

MAX = 75

class LogEntryAdminMixin(object):

    def created(self, obj):
        return obj.timestamp.strftime('%Y-%m-%d %H:%M:%S')
    created.short_description = 'Created'

    def user_url(self, obj):
        if obj.actor:
            app_label, model = settings.AUTH_USER_MODEL.split('.')
            viewname = 'admin:%s_%s_change' % (app_label,
                                               model.lower())
            try:
                link = urlresolvers.reverse(viewname,
                                            args=[obj.actor.id])
            except NoReverseMatch:
                return u'%s' % (obj.actor)
~~            return format_html(u'<a href="{}">{}</a>',
~~                               link, obj.actor)

        return 'system'
    user_url.short_description = 'User'

    def resource_url(self, obj):
        app_label, model = obj.content_type.app_label,
                           obj.content_type.model
        viewname = 'admin:%s_%s_change' % (app_label, model)
        try:
            args = [obj.object_pk] if obj.object_id is \
                   None else [obj.object_id]
            link = urlresolvers.reverse(viewname, args=args)
        except NoReverseMatch:
            return obj.object_repr
        else:
~~            return format_html(u'<a href="{}">{}</a>',
~~                               link, obj.object_repr)
    resource_url.short_description = 'Resource'

    def msg_short(self, obj):
        if obj.action == 2:
            return ''  # delete
        changes = json.loads(obj.changes)
        s = '' if len(changes) == 1 else 's'
        fields = ', '.join(changes.keys())
        if len(fields) > MAX:
            i = fields.rfind(' ', 0, MAX)
            fields = fields[:i] + ' ..'
        return '%d change%s: %s' % (len(changes), s, fields)
    msg_short.short_description = 'Changes'

    def msg(self, obj):
        if obj.action == 2:
            return ''  # delete
        changes = json.loads(obj.changes)
        msg = '<table><tr><th>#</th><th>Field</th>' + \
              '<th>From</th><th>To</th></tr>'
        for i, field in enumerate(sorted(changes), 1):
            value = [i, field] + (['***', '***'] if field == \
                    'password' else changes[field])
~~            msg += format_html('<tr><td>{}</td><td>{}</td><td>' + \
~~                               '{}</td><td>{}</td></tr>', *value)

        msg += '</table>'
        return mark_safe(msg)
    msg.short_description = 'Changes'
```


text:
layout: post
published: true
main: true
title: "AMD's latest (patents) developments in CPU, GPU, package and more "
description: "AMD patent list that was published recently. Some Zen3 and CDNA foundation patents in the mix, packaging. AMD is also ramping up its Exascale Heterogenous Processor (EHP) IP."
picture: amdzen.gif

label_default: "Patent"
label_primary: "AMD"
label_info: "Fresh"
---
<!-- Main Container -->

AMD patent list that was published recently. Some Zen3 and CDNA foundation patents in the mix. AMD is also ramping up its [Exascale Heterogenous Processor (EHP)](https://www.techpowerup.com/214868/amd-details-exascale-heterogenous-processor-ehp-for-supercomputers) IP.

* [Side information for video data transmission](https://www.freepatentsonline.com/20200314434.pdf) : Methods for performing efficient video compression for wireless VR stream communication

* [Integrated circuit package with integrated voltage regulator](https://www.freepatentsonline.com/20200312766.pdf) : Looks like next gen CPU/GPU need an integrated voltage regulator

* [Auto generation and tuning tool for convolution kernels](https://www.freepatentsonline.com/20200302285.pdf) : Methods for implementing an auto generation and tuning tool for convolution kernels, which is a basic CDNA foundation.

* [Processing unit with mixed precision operations](https://www.freepatentsonline.com/20200293286.pdf) : More CDNA goodies.

* [Using Multiple Memory Elements in an Input-Output Memory Management Unit for Performing Virtual Address to Physical Address Translations](https://www.freepatentsonline.com/20200301849.pdf) : This has some potential for speeding up access to Storage class memory device.

* [Dynamic Instances Semantics](https://www.freepatentsonline.com/20200301681.pdf)

* [Multi-RDL structure packages and methods of fabricating the same](https://www.freepatentsonline.com/20200294923.pdf) : next CPU battlefield is the packaging tech

* [Detecting voice regions in a non-stationary noisy environment](https://www.freepatentsonline.com/20200294534.pdf) : Foray into mobile phone tech, or simply wants to compete with NVDIA RTX voice?

* [Fan-Out packages with warpage resistance](https://www.freepatentsonline.com/20200294914.pdf) : packaging, packaging, packaging

* [Method and apparatus for peer-to-peer messaging in heterogeneous machine clusters](https://www.freepatentsonline.com/20200293387.pdf) : this one is interesting, looks like thread aware RDMA type semantics... foundation for EHP

* [Pipeline including separate hardware data paths for different instruction types](https://www.freepatentsonline.com/20200293329.pdf) : Say hello to one of the Zen 3 foundations...

* [Implementing a micro-operation cache with compaction](https://www.freepatentsonline.com/20200285466.pdf) : Say hello to one of the Zen 3 foundations...

* [Home agent based cache transfer acceleration scheme](https://www.freepatentsonline.com/20190188155.pdf) : Systems, apparatuses, and methods for implementing a speculative probe mechanism

* [Probe placement for laser probing system](https://www.freepatentsonline.com/20200284837.pdf) : A great improvement in defect identification

* [Activation Function Functional Block for Electronic Devices](Activation Function Functional Block for Electronic Devices)

* [Speculative instruction wakeup to tolerate draining delay of memory ordering violation check buffers](https://www.freepatentsonline.com/20200319889.pdf) : remember the ["zero-bubble"](https://www.freepatentsonline.com/20170068539.pdf) branch prediction, this is a continuation of the same idea. In case you didn't know a bubble in the core pipeline is when it's idle either due to a memory stall or incorrect branch prediction wherein the entire pipeline has to be flushed and loaded with a new set of instructions, wasting precious execution cycles.

* [Method enabling virtual pages to be allocated with noncontiguous backing physical subpages](https://www.freepatentsonline.com/20200320016.pdf) :  ho.... this one is interesting, virtual page backed by fragmented physical page. Not sure of the practical use case but this can lead to some interesting stuff in the virtualization domain.

* [Dynamic interrupt rate control in computing systems](https://www.freepatentsonline.com/20190163251.pdf)

* [Precise suspend and resume of workloads in a processing unit](https://www.freepatentsonline.com/20190163527.pdf) : A method for support suspend/resume operations for dependent workloads executing on different pipelines in GPUs

* [Stochastic rounding logic](https://www.freepatentsonline.com/10628124.pdf) : Techniques and circuits are provided for stochastic rounding. Highly recommended to read the article referred to in the patent.

* [Near-memory hardened compute blocks for configurable computing substrates](https://www.freepatentsonline.com/10579557.pdf) : EHP foundations ... keep a close eye on this one.

* [ In-memory interconnect protocol configuration registers](https://www.freepatentsonline.com/9767028.pdf) : More EHP foundation

* [Onboard monitoring of voltage levels and droop events](https://www.freepatentsonline.com/10627883.pdf)

* [Multi-plane Transmission](https://www.freepatentsonline.com/20200314436.pdf)

* [Generating vectorized control flow using reconverging control flow graphs](https://www.freepatentsonline.com/20200310766.pdf)

* [Source clock recovery in wireless video systems](https://www.freepatentsonline.com/20200314469.pdf) : wireless console video ? probably VR/AR tech.

* [Platform Agnostic Atomic Operations](https://www.freepatentsonline.com/20200310684.pdf) : Atomic operations for GPU or FPGA... RDMA semantics, I see what you are doing here AMD, more EHP foundation

* [Timer for use dual voltage supplies](https://www.freepatentsonline.com/20200312389.pdf)

* [Metal zero power ground stub route to reduce cell area and improve cell placement at the chip level](https://www.freepatentsonline.com/20190155979.pdf)

* [Save and restore scoreboard](https://www.freepatentsonline.com/10403351.pdf) : Read [Loh's paper](https://www.cs.utah.edu/wondp/wondp2013-paper2-final.pdf) for a more palatable version of this patent.

* [Deskewing method for a physical layer interface on a multi-chip module](https://www.freepatentsonline.com/20200344039.pdf) : packaging interconnect

* [Buffer management for plug-in architectures in computation graph structures](https://www.freepatentsonline.com/20200344378.pdf)

* [Data sparsity monitoring during neural network training](https://www.freepatentsonline.com/20200342327.pdf)

* [Symmetrical Balanced C-element](https://www.freepatentsonline.com/20200358447.pdf)

* [Memory management in graphics and compute application programming interfaces](https://www.freepatentsonline.com/20200357093.pdf) : continuation of U.S. patent application Ser. No. 15/477,795, filed Apr. 3, 2017

* [System and method for scheduling instructions in a multithread simd architecture with a fixed number of registers](https://www.freepatentsonline.com/20200278947.pdf) : RDNA3 ...

* [Region-based image compression and decompression](https://www.freepatentsonline.com/20200280721.pdf)

* [Virtual Reality Beamforming](https://www.freepatentsonline.com/20200280862.pdf) : Methods for implementing enhanced beamforming training procedures in VR wireless communication.

* [Wave creation control with dynamic resource allocation](https://www.freepatentsonline.com/20190129756.pdf) : A method to determine the resource allocations of waves based on the average resource allocation and dispatching the spawned waves on the GPU.

* [Swizzling In 3D Stacked Memory](https://www.freepatentsonline.com/20190129651.pdf) : EHP ...

* [Hybrid lower-level cache inclusion policy for cache hierarchy having at least three caching levels](https://www.freepatentsonline.com/20190121748.pdf)

* [Processor with accelerated lock instruction operation](https://www.freepatentsonline.com/20200272463.pdf) : Another Zen3 foundation...

* [Hybrid Matrix Multiplication Pipeline](https://www.freepatentsonline.com/20200272687.pdf) : More CDNA

* [Method and apparatus for generating artificial intelligence resistant verification images](https://www.freepatentsonline.com/20200272726.pdf) : Hardware captcha ...

* [Preemptive cache writeback with transaction support](https://www.freepatentsonline.com/20190095330.pdf)

* [Compressing tags in software and hardware semi-sorted caches](https://www.freepatentsonline.com/10749545.pdf) : A data storage system which performs partial compression and decompression of cached data.

* [Domain Identifier and Device Identifier Translation by an Input-Output Memory Management Unit](https://www.freepatentsonline.com/20200334058.pdf)

* [Nwell and Subtrate Taps In Memory Layout](https://www.freepatentsonline.com/20200335142.pdf)

* [Asynchronous Buffer with Pointer Offsets](https://www.freepatentsonline.com/20190179777.pdf)

* [Semiconductor chip with stacked conductor lines and air gaps](https://www.freepatentsonline.com/20200328155.pdf): Air gaps in interlevel dielectric layers between adjacent conductor lines to counteract the capacitance increase associated with reduced line spacing.

* [Capacitive structure for memory write assist ](https://www.freepatentsonline.com/20190180798.pdf)

* [Land Pad Design for High Speed Terminals](https://www.freepatentsonline.com/20190181087.pdf)

* [Standard cell and power grid architectures with EUV lithography](https://www.freepatentsonline.com/10796061.html)
<!--End Main Container -->


text:
import React, { Component } from "react";

class Repo extends Component {
    render() {
        return (

{this.props.params.repoName}

        );
    }
}

export default Repo;


text:
#ifndef __SEARCHSPACE_1_2
#define __SEARCHSPACE_1_2

#include "Validator.h"
#include "ptree.h"
#include "graphconstruct.h"
#include "TIM.h"
#include "PartialPlan.h"

#include <queue>

namespace Planner {

// This is a singleton object....

class SearchSpace {
private:
// We need all these things to build a Validator object that can then be used to
// support the simulation process for execution of Happenings.
	VAL::DerivationRules derivRules;
	VAL::plan dummyPlan;
	VAL::Validator val;

	Inst::GraphFactory * gf;
	Inst::PlanGraph pg;

	typedef std::priority_queue<PartialPlan *,vector<PartialPlan *>,PartialPlanOrderer> PPQueue;
	PPQueue * ppq;

	bool hasOrder;
	PartialPlanOrder * myPPO;

	SearchSpace();
	SearchSpace(const SearchSpace &);

public:
	static SearchSpace & instance()
	{
		static SearchSpace ssp;
		return ssp;
	};

	~SearchSpace()
	{
		delete myPPO;
	};

	void setOrdering(PartialPlanOrder * ppo)
	{
		if(hasOrder)
		{
			PPQueue * ppq1 = new PPQueue(PartialPlanOrderer(ppo));

			while(!ppq->empty())
			{
				ppq1->push(ppq->top());
				ppq->pop();
			};
			delete ppq;
			ppq = ppq1;
			delete myPPO;
			myPPO = ppo;
		}
		else
		{
			ppq = new PPQueue(PartialPlanOrderer(ppo));
			myPPO = ppo;
			hasOrder = true;
		};
	};

	VAL::Validator * getVal() {return &val;};
	VAL::plan * getDummyPlan() {return &dummyPlan;};
	Inst::PlanGraph & getPG() {return pg;};

	void findPlan();
};

};

#endif


text:
namespace {

Profile* ProfileFromFrameTreeNodeID(int frame_tree_node_id) {
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  if (!web_contents)
    return nullptr;
  return Profile::FromBrowserContext(web_contents->GetBrowserContext());
}

void ReportProbeLatency(int frame_tree_node_id, base::TimeDelta probe_latency) {
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  if (!web_contents)
    return;

  PrefetchProxyTabHelper* tab_helper =
      PrefetchProxyTabHelper::FromWebContents(web_contents);
  if (!tab_helper)
    return;

  tab_helper->NotifyPrefetchProbeLatency(probe_latency);
}

void ReportProbeResult(int frame_tree_node_id,
                       const GURL& url,
                       PrefetchProxyProbeResult result) {
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  if (!web_contents)
    return;

  PrefetchProxyTabHelper* tab_helper =
      PrefetchProxyTabHelper::FromWebContents(web_contents);
  if (!tab_helper)
    return;

  tab_helper->ReportProbeResult(url, result);
}

void RecordCookieWaitTime(base::TimeDelta wait_time) {
  UMA_HISTOGRAM_CUSTOM_TIMES(
      "PrefetchProxy.AfterClick.Mainframe.CookieWaitTime", wait_time,
      base::TimeDelta(), base::Seconds(5), 50);
}

void NotifySubresourceManagerOfBadProbe(int frame_tree_node_id,
                                        const GURL& url) {
  Profile* profile = ProfileFromFrameTreeNodeID(frame_tree_node_id);
  if (!profile)
    return;

  PrefetchProxyService* service =
      PrefetchProxyServiceFactory::GetForProfile(profile);
  if (!service)
    return;

  PrefetchProxySubresourceManager* subresource_manager =
      service->GetSubresourceManagerForURL(url);
  if (!subresource_manager)
    return;

  subresource_manager->NotifyProbeFailed();
}

}  // namespace

PrefetchProxyURLLoaderInterceptor::PrefetchProxyURLLoaderInterceptor(
    int frame_tree_node_id)
    : frame_tree_node_id_(frame_tree_node_id) {}

PrefetchProxyURLLoaderInterceptor::~PrefetchProxyURLLoaderInterceptor() =
    default;

bool PrefetchProxyURLLoaderInterceptor::MaybeInterceptNoStatePrefetchNavigation(
    const network::ResourceRequest& tentative_resource_request) {
  Profile* profile = ProfileFromFrameTreeNodeID(frame_tree_node_id_);
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_);

  prerender::NoStatePrefetchManager* no_state_prefetch_manager =
      prerender::NoStatePrefetchManagerFactory::GetForBrowserContext(profile);
  if (!no_state_prefetch_manager)
    return false;

  if (!no_state_prefetch_manager->IsWebContentsPrefetching(web_contents))
    return false;

  PrefetchProxyService* service =
      PrefetchProxyServiceFactory::GetForProfile(profile);
  if (!service)
    return false;

  PrefetchProxySubresourceManager* manager =
      service->GetSubresourceManagerForURL(url_);
  if (!manager)
    return false;

  std::unique_ptr<PrefetchedMainframeResponseContainer> mainframe_response =
      manager->TakeMainframeResponse();
  if (!mainframe_response)
    return false;

  InterceptPrefetchedNavigation(tentative_resource_request,
                                std::move(mainframe_response));
  return true;
}

void PrefetchProxyURLLoaderInterceptor::MaybeCreateLoader(
    const network::ResourceRequest& tentative_resource_request,
    content::BrowserContext* browser_context,
    content::URLLoaderRequestInterceptor::LoaderCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  DCHECK(!loader_callback_);
  loader_callback_ = std::move(callback);
  url_ = tentative_resource_request.url;

  // If this method returns true, the navigation has already been intercepted.
  if (MaybeInterceptNoStatePrefetchNavigation(tentative_resource_request))
    return;

  std::unique_ptr<PrefetchedMainframeResponseContainer> prefetch =
      GetPrefetchedResponse(url_);
  if (!prefetch) {
    DoNotInterceptNavigation();
    return;
  }

  Profile* profile = ProfileFromFrameTreeNodeID(frame_tree_node_id_);
  if (!profile) {
    DoNotInterceptNavigation();
    return;
  }
  PrefetchProxyService* service =
      PrefetchProxyServiceFactory::GetForProfile(profile);
  if (!service) {
    DoNotInterceptNavigation();
    return;
  }

  // If the cookies associated with |url_| have changed since the initial
  // eligibility check, then we shouldn't use the prefetched resources.
  PrefetchProxyTabHelper* tab_helper = PrefetchProxyTabHelper::FromWebContents(
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_));
  if (tab_helper && tab_helper->HaveCookiesChanged(url_)) {
    DoNotInterceptNavigation();
    return;
  }

  if (service->origin_prober()->ShouldProbeOrigins()) {
    probe_start_time_ = base::TimeTicks::Now();
    base::OnceClosure on_success_callback =
        base::BindOnce(&PrefetchProxyURLLoaderInterceptor::
                           EnsureCookiesCopiedAndInterceptPrefetchedNavigation,
                       weak_factory_.GetWeakPtr(), tentative_resource_request,
                       std::move(prefetch));

    service->origin_prober()->Probe(
        url_.DeprecatedGetOriginAsURL(),
        base::BindOnce(&PrefetchProxyURLLoaderInterceptor::OnProbeComplete,
                       weak_factory_.GetWeakPtr(),
                       std::move(on_success_callback)));
    return;
  }
  // Inform the metrics collector that the main frame HTML was used and probing
  // was disabled.
  ReportProbeResult(frame_tree_node_id_, url_,
                    PrefetchProxyProbeResult::kNoProbing);

  EnsureCookiesCopiedAndInterceptPrefetchedNavigation(
      tentative_resource_request, std::move(prefetch));
}

void PrefetchProxyURLLoaderInterceptor::
    EnsureCookiesCopiedAndInterceptPrefetchedNavigation(
        const network::ResourceRequest& tentative_resource_request,
        std::unique_ptr<PrefetchedMainframeResponseContainer> prefetch) {
  // The TabHelper needs to copy cookies over to the main profile's cookie jar
  // before we can commit the mainframe so that subresources have the cookies
  // they need before being put on the wire.
  PrefetchProxyTabHelper* tab_helper = PrefetchProxyTabHelper::FromWebContents(
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_));
  if (tab_helper && tab_helper->IsWaitingForAfterSRPCookiesCopy()) {
    cookie_copy_start_time_ = base::TimeTicks::Now();
    tab_helper->SetOnAfterSRPCookieCopyCompleteCallback(base::BindOnce(
        &PrefetchProxyURLLoaderInterceptor::InterceptPrefetchedNavigation,
        weak_factory_.GetWeakPtr(), tentative_resource_request,
        std::move(prefetch)));
    return;
  }

  // Record that there was no wait time.
  RecordCookieWaitTime(base::TimeDelta());

  // If the cookies were already copied, commit now.
  InterceptPrefetchedNavigation(tentative_resource_request,
                                std::move(prefetch));
}

void PrefetchProxyURLLoaderInterceptor::InterceptPrefetchedNavigation(
    const network::ResourceRequest& tentative_resource_request,
    std::unique_ptr<PrefetchedMainframeResponseContainer> prefetch) {
  if (cookie_copy_start_time_) {
    base::TimeDelta wait_time =
        base::TimeTicks::Now() - *cookie_copy_start_time_;
    DCHECK_GT(wait_time, base::TimeDelta());
    RecordCookieWaitTime(wait_time);
  }

  NotifyPrefetchStatusUpdate(
      probe_start_time_.has_value()
          ? PrefetchProxyPrefetchStatus::kPrefetchUsedProbeSuccess
          : PrefetchProxyPrefetchStatus::kPrefetchUsedNoProbe);

  std::unique_ptr<PrefetchProxyFromStringURLLoader> url_loader =
      std::make_unique<PrefetchProxyFromStringURLLoader>(
          std::move(prefetch), tentative_resource_request);
  std::move(loader_callback_).Run(url_loader->ServingResponseHandler());
  // url_loader manages its own lifetime once bound to the mojo pipes.
  url_loader.release();
}

void PrefetchProxyURLLoaderInterceptor::DoNotInterceptNavigation() {
  std::move(loader_callback_).Run({});
}

void PrefetchProxyURLLoaderInterceptor::OnProbeComplete(
    base::OnceClosure on_success_callback,
    PrefetchProxyProbeResult result) {
  DCHECK(probe_start_time_.has_value());
  ReportProbeLatency(frame_tree_node_id_,
                     base::TimeTicks::Now() - probe_start_time_.value());
  ReportProbeResult(frame_tree_node_id_, url_, result);

  if (PrefetchProxyProbeResultIsSuccess(result)) {
    std::move(on_success_callback).Run();
    return;
  }

  // Notify the SubresourceManager for this url so that subresources should not
  // be loaded from the prefetch cache.
  NotifySubresourceManagerOfBadProbe(frame_tree_node_id_, url_);

  NotifyPrefetchStatusUpdate(
      PrefetchProxyPrefetchStatus::kPrefetchNotUsedProbeFailed);
  DoNotInterceptNavigation();
}

std::unique_ptr<PrefetchedMainframeResponseContainer>
PrefetchProxyURLLoaderInterceptor::GetPrefetchedResponse(const GURL& url) {
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_);
  if (!web_contents)
    return nullptr;

  PrefetchProxyTabHelper* tab_helper =
      PrefetchProxyTabHelper::FromWebContents(web_contents);
  if (!tab_helper)
    return nullptr;

  return tab_helper->TakePrefetchResponse(url);
}

void PrefetchProxyURLLoaderInterceptor::NotifyPrefetchStatusUpdate(
    PrefetchProxyPrefetchStatus status) const {
  content::WebContents* web_contents =
      content::WebContents::FromFrameTreeNodeId(frame_tree_node_id_);
  if (!web_contents) {
    return;
  }

  PrefetchProxyTabHelper* tab_helper =
      PrefetchProxyTabHelper::FromWebContents(web_contents);
  if (!tab_helper)
    return;

  DCHECK(url_.is_valid());
  tab_helper->OnPrefetchStatusUpdate(url_, status);
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports

# External imports

# Bokeh imports
from bokeh._testing.util.api import verify_all

# Module under test
import bokeh.application.handlers as bah

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

ALL = (
    'CodeHandler',
    'DirectoryHandler',
    'FunctionHandler',
    'Handler',
    'NotebookHandler',
    'ScriptHandler',
    'ServerLifecycleHandler',
)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

Test___all__ = verify_all(bah, ALL)


text:
package com.facebook.litho.widget;

import static com.facebook.litho.SizeSpec.UNSPECIFIED;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.widget.ImageView.ScaleType;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.ComponentLayout;
import com.facebook.litho.Diff;
import com.facebook.litho.DrawableMatrix;
import com.facebook.litho.MatrixDrawable;
import com.facebook.litho.Output;
import com.facebook.litho.R;
import com.facebook.litho.Size;
import com.facebook.litho.SizeSpec;
import com.facebook.litho.annotations.FromBoundsDefined;
import com.facebook.litho.annotations.MountSpec;
import com.facebook.litho.annotations.OnBind;
import com.facebook.litho.annotations.OnBoundsDefined;
import com.facebook.litho.annotations.OnCreateMountContent;
import com.facebook.litho.annotations.OnLoadStyle;
import com.facebook.litho.annotations.OnMeasure;
import com.facebook.litho.annotations.OnMount;
import com.facebook.litho.annotations.OnUnmount;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.ResType;
import com.facebook.litho.annotations.ShouldUpdate;
import com.facebook.litho.drawable.DrawableUtils;
import com.facebook.litho.utils.MeasureUtils;
import javax.annotation.Nullable;

/**
 * A component that is able to display drawable resources. It takes a drawable resource ID as prop.
 *
 * @uidocs
 * @prop drawable Drawable to display.
 * @prop scaleType Scale type for the drawable within the container.
 */
@MountSpec(isPureRender = true, poolSize = 30)
class ImageSpec {

  private static final ScaleType[] SCALE_TYPE = ScaleType.values();

  @OnLoadStyle
  static void onLoadStyle(
      ComponentContext c, Output<Drawable> drawable, Output<ScaleType> scaleType) {

    final TypedArray a = c.obtainStyledAttributes(R.styleable.Image, 0);

    for (int i = 0, size = a.getIndexCount(); i < size; i++) {
      final int attr = a.getIndex(i);

      if (attr == R.styleable.Image_android_src) {
        drawable.set(c.getAndroidContext().getResources().getDrawable(a.getResourceId(attr, 0)));
      } else if (attr == R.styleable.Image_android_scaleType) {
        scaleType.set(SCALE_TYPE[a.getInteger(attr, -1)]);
      }
    }

    a.recycle();
  }

  @OnMeasure
  static void onMeasure(
      ComponentContext c,
      ComponentLayout layout,
      int widthSpec,
      int heightSpec,
      Size size,
      @Prop(resType = ResType.DRAWABLE) @Nullable Drawable drawable) {
    if (drawable == null
        || drawable.getIntrinsicWidth() <= 0
        || drawable.getIntrinsicHeight() <= 0) {
      size.width = 0;
      size.height = 0;
      return;
    }

    final int intrinsicHeight = drawable.getIntrinsicHeight();
    final int intrinsicWidth = drawable.getIntrinsicWidth();

    if (SizeSpec.getMode(widthSpec) == UNSPECIFIED && SizeSpec.getMode(heightSpec) == UNSPECIFIED) {
      size.width = intrinsicWidth;
      size.height = intrinsicHeight;
      return;
    }

    final float aspectRatio = intrinsicWidth / (float) intrinsicHeight;
    MeasureUtils.measureWithAspectRatio(
        widthSpec, heightSpec, intrinsicWidth, intrinsicHeight, aspectRatio, size);
  }

  @OnBoundsDefined
  static void onBoundsDefined(
      ComponentContext c,
      ComponentLayout layout,
      @Prop(resType = ResType.DRAWABLE) @Nullable Drawable drawable,
      @Nullable @Prop(optional = true) ScaleType scaleType,
      Output<DrawableMatrix> drawableMatrix,
      Output<Integer> drawableWidth,
      Output<Integer> drawableHeight) {

    final int horizontalPadding = layout.getPaddingLeft() + layout.getPaddingRight();
    final int verticalPadding = layout.getPaddingTop() + layout.getPaddingBottom();

    if (ScaleType.FIT_XY == scaleType
        || drawable == null
        || drawable.getIntrinsicWidth() <= 0
        || drawable.getIntrinsicHeight() <= 0) {
      drawableMatrix.set(null);
      drawableWidth.set(layout.getWidth() - horizontalPadding);
      drawableHeight.set(layout.getHeight() - verticalPadding);
    } else {
      final DrawableMatrix matrix =
          DrawableMatrix.create(
              drawable,
              scaleType,
              layout.getWidth() - horizontalPadding,
              layout.getHeight() - verticalPadding);

      drawableMatrix.set(matrix);
      drawableWidth.set(drawable.getIntrinsicWidth());
      drawableHeight.set(drawable.getIntrinsicHeight());
    }
  }

  @OnCreateMountContent
  static MatrixDrawable onCreateMountContent(Context c) {
    return new MatrixDrawable();
  }

  @OnMount
  static void onMount(
      ComponentContext c,
      MatrixDrawable matrixDrawable,
      @Prop(resType = ResType.DRAWABLE) @Nullable Drawable drawable,
      @Nullable @FromBoundsDefined DrawableMatrix drawableMatrix) {
    matrixDrawable.mount(drawable, drawableMatrix);
  }

  @OnBind
  static void onBind(
      ComponentContext c,
      MatrixDrawable mountedDrawable,
      @FromBoundsDefined Integer drawableWidth,
      @FromBoundsDefined Integer drawableHeight) {
    mountedDrawable.bind(drawableWidth, drawableHeight);
  }

  @OnUnmount
  static void onUnmount(
      ComponentContext c,
      MatrixDrawable convertDrawable,
      @Prop(resType = ResType.DRAWABLE) @Nullable Drawable drawable) {
    convertDrawable.unmount();
  }

  @ShouldUpdate(onMount = true)
  static boolean shouldUpdate(
      @Prop(optional = true) Diff<ScaleType> scaleType,
      @Prop(resType = ResType.DRAWABLE) Diff<Drawable> drawable) {
    return scaleType.getNext() != scaleType.getPrevious()
        || !DrawableUtils.isEquivalentTo(drawable.getNext(), drawable.getPrevious());
  }
}


text:
const crypto = require('crypto');
const CONFIG = require('./config').CONFIG;
const assert = require('assert');

const SIGNATURE_ALGORITHM = 'sha256';

/**
 * Generates a HMAC-SHA1 digital signature for a bucket/key combination using the SECRET as the key
 * @param bucket the bucket name
 * @param key the key name
 * @returns {string} the digitally signed bucket+key combination
 */
const generateSignature = function (bucket, key) {
  assert(bucket !== undefined);
  assert(key !== undefined);
  assert(typeof CONFIG.SECRET === 'string', 'API key secret must be set for signatures to work');

  return crypto.createHmac(SIGNATURE_ALGORITHM, CONFIG.SECRET).update(internalId(bucket, key)).digest('hex');
};

/**
 * Given a bucket name and key, we'll return a S3 URL for it
 * @param bucket
 * @param key
 * @returns {string}
 */
const internalId = (bucket, key) => `s3://${bucket}/${key}`;

exports.formatTagValue = (value) => {
  if (value instanceof Array) {
    value = value.join(' ');
  }
  //we need to make sure we stay under the tag max length:
  let formattedValue = value.substr(0, 255);

  console.log('formatted tag value: ', formattedValue);
  return formattedValue;
};

exports.internalId = internalId;
exports.generateSignature = generateSignature;


text:
package com.msh.room.model.room;

import com.msh.room.dto.event.JudgeEvent;
import com.msh.room.dto.event.PlayerEvent;
import com.msh.room.dto.response.JudgeDisplayInfo;
import com.msh.room.dto.response.PlayerDisplayInfo;
import com.msh.room.dto.room.RoomStateData;
import com.msh.room.service.DataBaseService;

/**
 * Created by zhangruiqian on 2017/5/25.
 */
public interface RoomState {

    void setDataService(DataBaseService service);

    RoomStateData resolveJudgeEvent(JudgeEvent event);

    JudgeDisplayInfo displayJudgeInfo();

    RoomStateData resolvePlayerEvent(PlayerEvent event);

    PlayerDisplayInfo displayPlayerInfo(int seatNumber);
}


text:
# karma-redirect-preprocessor

> Preprocessor for serving files at custom URLs

In your code, you might have a line like:
```js
$.ajax('templates/landing.html').done(function(html) {
  loadView(html);
});
```
However, when running this code in Karma, `landing.html` will probably be served
to a URL like `/base/static/templates/landing.html`, in which case the above
AJAX won't work.

The `karma-redirect-preprocessor` can solve this problem by making karma serve
files at the correct URL.

Based off of [karma-ng-html2js-preprocessor](https://github.com/karma-runner/karma-ng-html2js-preprocessor).

## Installation

The easiest way is to keep `karma-redirect-preprocessor` as a devDependency in your `package.json`.
```json
{
  "devDependencies": {
    "karma": "~0.10",
    "karma-redirect-preprocessor": "~0.1"
  }
}
```

You can simple do it by:
```bash
npm install karma-redirect-preprocessor --save-dev
```

## Configuration
```js
// karma.conf.js
module.exports = function(config) {
  config.set({
    preprocessors: {
      '**/*.html': ['redirect']
    },

    files: [
      '*.js',
      '*.html',
      '*.html.ext',
      // if you wanna load template files in nested directories, you must use this
      '**/*.html'
    ],

    // if you have defined plugins explicitly, add karma-redirect-preprocessor
    // plugins: [
    //     <your plugins>
    //     'karma-redirect-preprocessor',
    // ]

    redirectPreprocessor: {
      // strip this from the file path
      stripPrefix: 'public/',
      stripSuffix: '.ext',
      // prepend this to the
      prependPrefix: 'served/',

      // or define a custom transform function
      cacheIdFromPath: function(filepath) {
        return cacheId;
      },

      // By default, any redirected files have their `included` property set to
      // false (see "How does it work?").  If you set dontInclude to false
      // however, the preprocessor will not mess with the `included` property.
      // dontInclude = false
    }
  });
};
```

## How does it work ?

This preprocessor rewrites your config file so that files are proxied to the
desired address.  See the [config documentation](http://karma-runner.github.io/0.13/config/configuration-file.html)
for information on proxies in karma.  By default, the preprocessor also sets the
[`included` property ](http://karma-runner.github.io/0.13/config/files.html) of
all redirected files to `false`.  This stops karma from including the files in
`<script>` tags, since the tests will probably be retrieving these files over
AJAX (and the files might not even be `js` files).

See the [test file](/test/e2e/karma.conf.js) for an example.

----

For more information on Karma see the [homepage].

[homepage]: http://karma-runner.github.com