text:
import scala.quoted._
import scala.quoted.autolift

import scala.language.implicitConversions

object TestFooErrors { // Defined in tests
  implicit object StringContextOps {
    inline def (inline ctx: StringContext).foo(inline args: Any*): List[(Boolean, Int, Int, Int, String)] = ${ Macro.fooErrors('ctx, 'args) }
  }
}

object Macro {

  def fooErrors(strCtxExpr: Expr[StringContext], argsExpr: Expr[Seq[Any]])(using QuoteContext): Expr[List[(Boolean, Int, Int, Int, String)]] = {
    (strCtxExpr, argsExpr) match {
      case ('{ StringContext(${Varargs(parts)}: _*) }, Varargs(args)) =>
        fooErrorsImpl(parts, args, argsExpr)
    case ('{ new StringContext(${Varargs(parts)}: _*) }, Varargs(args)) =>
      fooErrorsImpl(parts, args, argsExpr)
    }
  }

  def fooErrorsImpl(parts0: Seq[Expr[String]], args: Seq[Expr[Any]], argsExpr: Expr[Seq[Any]])(using QuoteContext)= {
    val errors = List.newBuilder[Expr[(Boolean, Int, Int, Int, String)]]
    // true if error, false if warning
    // 0 if part, 1 if arg, 2 if strCtx, 3 if args
    // index in the list if arg or part, -1 otherwise
    // offset, 0 if strCtx, args or arg
    // message as given
    val reporter = new dotty.internal.StringContextMacro.Reporter{
      private[this] var reported = false
      private[this] var oldReported = false
      def partError(message : String, index : Int, offset : Int) : Unit = {
        reported = true
        errors += '{ Tuple5(true, 0, $index, $offset, $message) }
      }
      def partWarning(message : String, index : Int, offset : Int) : Unit = {
        reported = true
        errors += '{ Tuple5(false, 0, $index, $offset, $message) }
      }

      def argError(message : String, index : Int) : Unit = {
        reported = true
        errors += '{ Tuple5(true, 1, $index, 0, $message) }
      }

      def strCtxError(message : String) : Unit = {
        reported = true
        errors += '{ Tuple5(true, 2, -1, 0, $message) }
      }
      def argsError(message : String) : Unit = {
        reported = true
        errors += '{ Tuple5(true, 3, -1, 0, $message) }
      }

      def hasReported() : Boolean = {
        reported
      }

      def resetReported() : Unit = {
        oldReported = reported
        reported = false
      }

      def restoreReported() : Unit = {
        reported = oldReported
      }
    }
    val parts = parts0.map { case Const(s) => s }
    dotty.internal.StringContextMacro.interpolate(parts.toList, args.toList, argsExpr, reporter) // Discard result
    Expr.ofList(errors.result())
  }
}


text:
<?php

class LayoutParser {

    private $version = -1;
    private $revision = -1;
    private $numObjects = -1;
    private $laps = -1;

    /** Base path for layouts. Ends on / */
    private $basePath;

    private $objects = array();

    const UNPACK = 'x6/Cversion/Crevision/vnumObjects/Claps/x';
    const PACK = 'a6CCvCC';

    public function __construct($path) {
        if (substr($path, -1) != '/') {
            $path .= '/';
        }

        $this->basePath = $path;
    }

    public function __toString()
    {
        $retVal  = "Version: ".$this->version."\n";
        $retVal .= "Revision: ".$this->revision."\n";
        $retVal .= "NumObjects: ".count($this->objects)."\n";
        $retVal .= "Laps: ".$this->laps."\n";

        $retVal .= "Objects: ".$this->laps."\n---------------------------------------\n\n";
        foreach ($this->objects as $obj)
        {
            $retVal .= (string) $obj."\n";
        }

        return $retVal;
    }

    /**
     * Reads a layout from the file.
     * @param shortTrackName Track name like FE1 or BL1
     * @param Layoutname Name for the layout behind the BL1_
     */
    public function parseLayout($shortTrackName, $layoutName) {
        $lyt = file_get_contents($this->basePath . $shortTrackName . '_' . $layoutName . '.lyt');

        foreach (unpack(Layout::UNPACK, substr($lyt, 0, 12)) as $property => $value) {
            $this->$property = $value;
        }

        for ($i = 0; $i < $this->numObjects; $i++) {
            $object = new LayoutObject(substr($lyt, 12 + $i * 8, 8));
            // stored with xyindex key to easily find objects again
            $this->objects[$object->x().':'.$object->y()] = $object;
        }
    }

    /**
     * Whether or not the object is an marshal object
     * @return boolean
     */
    private function isMarshal($object) {
        return $object instanceof MarshalObject
        ||    $object->type() == LayoutObject::OBJ_MARSHALL
        ||    $object->type() == LayoutObject::OBJ_MARSHALL_LEFT
        ||    $object->type() == LayoutObject::OBJ_MARSHALL_RIGHT;
    }
    /**
     * Write the layout in a file.
     * @param shortTrackName Track name like FE1 or BL1
     * @param Layoutname Name for the layout behind the BL1_
     */
    public function writeLayout($shortTrackName, $layoutName) {
        $out = pack(self::PACK, 'LFSLYT', $this->version, $this->revision, count($this->objects), $this->laps, 0x01);

        foreach ($this->objects as $object) {
            $out .= $object->pack();
        }

        $lyt = file_put_contents($this->basePath . $shortTrackName . '_' . $layoutName . '.lyt', $out);
    }

    public function clearLayout() {
        $this->objects = array();
    }

    public function addObject($obj) {
        // send insim add packet...
        $this->removeObject();
        $this->objects[$obj->x().':'.$obj->y()] = $obj;
    }

    public function removeObject($obj) {
        // send insim remove packet...
        unset($this->objects[$obj->x().':'.$obj->y()]);
    }

    public function findObject($x, $y)
    {
        return isset($this->objects[$x.$y.$index])?$this->objects[$x.$y.$index]:null;
    }
}

?>

redpajama_set_name: RedPajamaGithub


text:
package com.flowpowered.engine.scheduler.input;

import java.util.LinkedList;
import java.util.Queue;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;

import com.flowpowered.api.input.InputSnapshot;
import com.flowpowered.api.input.KeyboardEvent;
import com.flowpowered.api.input.MouseEvent;
import com.flowpowered.commons.TPSMonitor;
import com.flowpowered.commons.queue.SubscribableQueue;
import com.flowpowered.commons.ticking.TickingElement;
import com.flowpowered.engine.FlowClient;
import com.flowpowered.engine.FlowEngine;
import com.flowpowered.engine.network.FlowSession;
import com.flowpowered.engine.network.message.InputSnapshotMessage;

public class InputThread extends TickingElement {
    private static final int TPS = 60;
    private final FlowEngine engine;
    private final FlowClient client;
    private boolean mouseCreated = false, keyboardCreated = false;
    private final SubscribableQueue<KeyboardEvent> keyboardQueue = new SubscribableQueue<>(false);
    private final SubscribableQueue<MouseEvent> mouseQueue = new SubscribableQueue<>(false);
    private final SubscribableQueue<InputSnapshot> inputQueue = new SubscribableQueue<>(false);

    private volatile InputSnapshot lastSnapshot = new InputSnapshot();

    private final TPSMonitor tpsMonitor = new TPSMonitor();
    public int getTPS() {
        return tpsMonitor.getTPS();
    }

    public InputThread(FlowEngine engine, FlowClient client) {
        super("input", TPS);
        this.engine = engine;
        this.client = client;
    }

    @Override
    public void onStart() {
        System.out.println("Input start");

        keyboardQueue.becomePublisher();
        mouseQueue.becomePublisher();
        inputQueue.becomePublisher();

        tpsMonitor.start();
    }

    @Override
    public void onTick(long dt) {
        // Exit game if we're asked to
        if (isCloseRequested()) {
            stop();
        }
        // Tries to create the input, only does so if it already hasn't been created
        createInputIfNecessary();
        LinkedList<KeyboardEvent> currentKeys = new LinkedList<>();
        LinkedList<MouseEvent> currentMouse = new LinkedList<>();
        if (keyboardCreated) {
            // For every keyboard event
            while (Keyboard.next()) {
                // Create a new event
                final KeyboardEvent event = new KeyboardEvent(Keyboard.getEventKey(), Keyboard.getEventKeyState());
                currentKeys.add(event);
                // Add to the queues, if we don't have an empty queue, return, there's nothing more to add
                if (!keyboardQueue.add(event)) {
                    break;
                }
            }
        }
        if (mouseCreated) {
            // For every mouse event
            while (Mouse.next()) {
                // Create a new event
                final MouseEvent event = new MouseEvent(
                        Mouse.getEventX(), Mouse.getEventY(),
                        Mouse.getEventDX(), Mouse.getEventDY(),
                        Mouse.getEventDWheel(),
                        Mouse.getEventButton(), Mouse.getEventButtonState());
                currentMouse.add(event);
                // Add to the queues, if we don't have an empty queue, return, there's nothing more to add
                if (!mouseQueue.add(event)) {
                    break;
                }
            }
        }
        InputSnapshot newSnapshot = lastSnapshot.withChanges(dt / 1e9f, Mouse.isGrabbed(), currentKeys, currentMouse);
        inputQueue.add(newSnapshot);

        FlowSession session = client.getSession();
        if (session != null) {
            session.send(new InputSnapshotMessage(dt / 1e9f, Mouse.isGrabbed(), currentKeys, currentMouse));
        }
        lastSnapshot = newSnapshot;
        tpsMonitor.update();
    }

    private void createInputIfNecessary() {
        if (!keyboardCreated) {
            if (Display.isCreated()) {
                if (!Keyboard.isCreated()) {
                    try {
                        Keyboard.create();
                        keyboardCreated = true;
                    } catch (LWJGLException ex) {
                        throw new RuntimeException("Could not create keyboard", ex);
                    }
                } else {
                    keyboardCreated = true;
                }
            }
        }
        if (!mouseCreated) {
            if (Display.isCreated()) {
                if (!Mouse.isCreated()) {
                    try {
                        Mouse.create();
                        mouseCreated = true;
                    } catch (LWJGLException ex) {
                        throw new RuntimeException("Could not create mouse", ex);
                    }
                } else {
                    mouseCreated = true;
                }
                Mouse.setClipMouseCoordinatesToWindow(false);
            }
        }
    }

    @Override
    public void onStop() {
        System.out.println("Input stop");

        // We make sure to end of the game, else there's no way to stop it normally (no input!)
        engine.stop(null);
        if (Keyboard.isCreated()) {
            Keyboard.destroy();
        }
        keyboardCreated = false;
        keyboardQueue.unsubscribeAll();
        if (Mouse.isCreated()) {
            Mouse.destroy();
        }
        mouseCreated = false;
        mouseQueue.unsubscribeAll();
        inputQueue.unsubscribeAll();
    }

    public Queue<InputSnapshot> getInputQueue() {
        return inputQueue;
    }

    public void subscribeToInput() {
        inputQueue.subscribe();
    }

    public void unsubscribeToInput() {
        inputQueue.unsubscribe();
    }

    public Queue<KeyboardEvent> getKeyboardQueue() {
        return keyboardQueue;
    }

    public Queue<MouseEvent> getMouseQueue() {
        return mouseQueue;
    }

    public void subscribeToKeyboard() {
        keyboardQueue.subscribe();
    }

    public void subscribeToMouse() {
        mouseQueue.subscribe();
    }

    public void unsubscribeToKeyboard() {
        keyboardQueue.unsubscribe();
    }

    public void unsubscribeToMouse() {
        mouseQueue.unsubscribe();
    }

    public boolean isActive() {
        return Display.isCreated() && Display.isActive();
    }

    public boolean isCloseRequested() {
        return Display.isCreated() && Display.isCloseRequested();
    }

    public void setMouseGrabbed(boolean grabbed) {
        if (Mouse.isCreated()) {
            Mouse.setGrabbed(grabbed);
        }
    }

    public boolean isMouseGrabbed() {
        return Mouse.isCreated() && Mouse.isGrabbed();
    }

    public int getMouseX() {
        if (Mouse.isCreated()) {
            return Mouse.getX();
        }
        return 0;
    }

    public int getMouseY() {
        if (Mouse.isCreated()) {
            return Mouse.getY();
        }
        return 0;
    }

    public boolean isKeyDown(int key) {
        return Keyboard.isCreated() && Keyboard.isKeyDown(key);
    }

    public boolean isButtonDown(int button) {
        return Mouse.isCreated() && Mouse.isButtonDown(button);
    }
}


text:
import { IQueryOptions, IRetsStream, IQueryResponse } from './client'

export interface IClientSearch {
    stream: {
      /**
       * headerInfo []
       * data [result]
       */
      query (
        resourceType: string,
        classType: string,
        query: string,
        options?: IQueryOptions,
        rawData?: boolean,
        parserEncoding?: string): {
          retsStream: IRetsStream
        }
    }
    /**
     * perform a query using DMQL2 -- pass resource, class, and query, and options
     */
    query (resourceType: string, classType: string, query: string, options?: IQueryOptions, parserEncoding?: string): Promise<IQueryResponse>
}


text:
{% extends 'pybb/base.html' %}
{% load pybb_tags i18n staticfiles %}

{% block title %}{% trans 'Editing the post' %}{% endblock title %}

{% block extra_head %}
    {{ block.super }}
    {{ form.media.css }}
{% endblock %}
{% block extra_script %}
    {{ block.super }}
    {{ form.media.js }}
    <script type="text/javascript" src="{% static 'pybb/js/jquery.formset.min.js' %}"></script>
{% endblock %}

{% block content %}
    <h1>{% trans 'Editing the post' %}</h1>
    {% include "pybb/post_form.html" %}
{% endblock content %}

{% block breadcrumb %}
    {% with extra_crumb="Edit post" %}
        {% include "pybb/breadcrumb.html" %}
    {% endwith %}

{% endblock %}


text:
package docker

import (
	"encoding/json"
	"fmt"
	"github.com/dotcloud/docker/archive"
	"github.com/dotcloud/docker/utils"
	"io"
	"io/ioutil"
	"net/url"
	"os"
	"path"
	"reflect"
	"regexp"
	"strings"
)

type BuildFile interface {
	Build(io.Reader) (string, error)
	CmdFrom(string) error
	CmdRun(string) error
}

type buildFile struct {
	runtime *Runtime
	srv     *Server

	image        string
	maintainer   string
	config       *Config
	context      string
	verbose      bool
	utilizeCache bool
	rm           bool

	tmpContainers map[string]struct{}
	tmpImages     map[string]struct{}

	out io.Writer
}

func (b *buildFile) clearTmp(containers map[string]struct{}) {
	for c := range containers {
		tmp := b.runtime.Get(c)
		b.runtime.Destroy(tmp)
		fmt.Fprintf(b.out, "Removing intermediate container %s\n", utils.TruncateID(c))
	}
}

func (b *buildFile) CmdFrom(name string) error {
	image, err := b.runtime.repositories.LookupImage(name)
	if err != nil {
		if b.runtime.graph.IsNotExist(err) {
			remote, tag := utils.ParseRepositoryTag(name)
			if err := b.srv.ImagePull(remote, tag, b.out, utils.NewStreamFormatter(false), nil, nil, true); err != nil {
				return err
			}
			image, err = b.runtime.repositories.LookupImage(name)
			if err != nil {
				return err
			}
		} else {
			return err
		}
	}
	b.image = image.ID
	b.config = &Config{}
	if b.config.Env == nil || len(b.config.Env) == 0 {
		b.config.Env = append(b.config.Env, "HOME=/", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
	}
	return nil
}

func (b *buildFile) CmdMaintainer(name string) error {
	b.maintainer = name
	return b.commit("", b.config.Cmd, fmt.Sprintf("MAINTAINER %s", name))
}

func (b *buildFile) CmdRun(args string) error {
	if b.image == "" {
		return fmt.Errorf("Please provide a source image with `from` prior to run")
	}
	config, _, _, err := ParseRun([]string{b.image, "/bin/sh", "-c", args}, nil)
	if err != nil {
		return err
	}

	cmd := b.config.Cmd
	b.config.Cmd = nil
	MergeConfig(b.config, config)

	defer func(cmd []string) { b.config.Cmd = cmd }(cmd)

	utils.Debugf("Command to be executed: %v", b.config.Cmd)

	if b.utilizeCache {
		if cache, err := b.srv.ImageGetCached(b.image, b.config); err != nil {
			return err
		} else if cache != nil {
			fmt.Fprintf(b.out, " ---> Using cache\n")
			utils.Debugf("[BUILDER] Use cached version")
			b.image = cache.ID
			return nil
		} else {
			utils.Debugf("[BUILDER] Cache miss")
		}
	}

	cid, err := b.run()
	if err != nil {
		return err
	}
	if err := b.commit(cid, cmd, "run"); err != nil {
		return err
	}

	return nil
}

func (b *buildFile) FindEnvKey(key string) int {
	for k, envVar := range b.config.Env {
		envParts := strings.SplitN(envVar, "=", 2)
		if key == envParts[0] {
			return k
		}
	}
	return -1
}

func (b *buildFile) ReplaceEnvMatches(value string) (string, error) {
	exp, err := regexp.Compile("(\\\\\\\\+|[^\\\\]|\\b|\\A)\\$({?)([[:alnum:]_]+)(}?)")
	if err != nil {
		return value, err
	}
	matches := exp.FindAllString(value, -1)
	for _, match := range matches {
		match = match[strings.Index(match, "$"):]
		matchKey := strings.Trim(match, "${}")

		for _, envVar := range b.config.Env {
			envParts := strings.SplitN(envVar, "=", 2)
			envKey := envParts[0]
			envValue := envParts[1]

			if envKey == matchKey {
				value = strings.Replace(value, match, envValue, -1)
				break
			}
		}
	}
	return value, nil
}

func (b *buildFile) CmdEnv(args string) error {
	tmp := strings.SplitN(args, " ", 2)
	if len(tmp) != 2 {
		return fmt.Errorf("Invalid ENV format")
	}
	key := strings.Trim(tmp[0], " \t")
	value := strings.Trim(tmp[1], " \t")

	envKey := b.FindEnvKey(key)
	replacedValue, err := b.ReplaceEnvMatches(value)
	if err != nil {
		return err
	}
	replacedVar := fmt.Sprintf("%s=%s", key, replacedValue)

	if envKey >= 0 {
		b.config.Env[envKey] = replacedVar
	} else {
		b.config.Env = append(b.config.Env, replacedVar)
	}
	return b.commit("", b.config.Cmd, fmt.Sprintf("ENV %s", replacedVar))
}

func (b *buildFile) CmdCmd(args string) error {
	var cmd []string
	if err := json.Unmarshal([]byte(args), &cmd); err != nil {
		utils.Debugf("Error unmarshalling: %s, setting cmd to /bin/sh -c", err)
		cmd = []string{"/bin/sh", "-c", args}
	}
	if err := b.commit("", cmd, fmt.Sprintf("CMD %v", cmd)); err != nil {
		return err
	}
	b.config.Cmd = cmd
	return nil
}

func (b *buildFile) CmdExpose(args string) error {
	ports := strings.Split(args, " ")
	b.config.PortSpecs = append(ports, b.config.PortSpecs...)
	return b.commit("", b.config.Cmd, fmt.Sprintf("EXPOSE %v", ports))
}

func (b *buildFile) CmdUser(args string) error {
	b.config.User = args
	return b.commit("", b.config.Cmd, fmt.Sprintf("USER %v", args))
}

func (b *buildFile) CmdInsert(args string) error {
	return fmt.Errorf("INSERT has been deprecated. Please use ADD instead")
}

func (b *buildFile) CmdCopy(args string) error {
	return fmt.Errorf("COPY has been deprecated. Please use ADD instead")
}

func (b *buildFile) CmdEntrypoint(args string) error {
	if args == "" {
		return fmt.Errorf("Entrypoint cannot be empty")
	}

	var entrypoint []string
	if err := json.Unmarshal([]byte(args), &entrypoint); err != nil {
		b.config.Entrypoint = []string{"/bin/sh", "-c", args}
	} else {
		b.config.Entrypoint = entrypoint
	}
	if err := b.commit("", b.config.Cmd, fmt.Sprintf("ENTRYPOINT %s", args)); err != nil {
		return err
	}
	return nil
}

func (b *buildFile) CmdWorkdir(workdir string) error {
	b.config.WorkingDir = workdir
	return b.commit("", b.config.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
}

func (b *buildFile) CmdVolume(args string) error {
	if args == "" {
		return fmt.Errorf("Volume cannot be empty")
	}

	var volume []string
	if err := json.Unmarshal([]byte(args), &volume); err != nil {
		volume = []string{args}
	}
	if b.config.Volumes == nil {
		b.config.Volumes = NewPathOpts()
	}
	for _, v := range volume {
		b.config.Volumes[v] = struct{}{}
	}
	if err := b.commit("", b.config.Cmd, fmt.Sprintf("VOLUME %s", args)); err != nil {
		return err
	}
	return nil
}

func (b *buildFile) addRemote(container *Container, orig, dest string) error {
	file, err := utils.Download(orig, ioutil.Discard)
	if err != nil {
		return err
	}
	defer file.Body.Close()

	// If the destination is a directory, figure out the filename.
	if strings.HasSuffix(dest, "/") {
		u, err := url.Parse(orig)
		if err != nil {
			return err
		}
		path := u.Path
		if strings.HasSuffix(path, "/") {
			path = path[:len(path)-1]
		}
		parts := strings.Split(path, "/")
		filename := parts[len(parts)-1]
		if filename == "" {
			return fmt.Errorf("cannot determine filename from url: %s", u)
		}
		dest = dest + filename
	}

	return container.Inject(file.Body, dest)
}

func (b *buildFile) addContext(container *Container, orig, dest string) error {
	origPath := path.Join(b.context, orig)
	destPath := path.Join(container.RootfsPath(), dest)
	// Preserve the trailing '/'
	if strings.HasSuffix(dest, "/") {
		destPath = destPath + "/"
	}
	if !strings.HasPrefix(origPath, b.context) {
		return fmt.Errorf("Forbidden path: %s", origPath)
	}
	fi, err := os.Stat(origPath)
	if err != nil {
		return fmt.Errorf("%s: no such file or directory", orig)
	}
	if fi.IsDir() {
		if err := archive.CopyWithTar(origPath, destPath); err != nil {
			return err
		}
		// First try to unpack the source as an archive
	} else if err := archive.UntarPath(origPath, destPath); err != nil {
		utils.Debugf("Couldn't untar %s to %s: %s", origPath, destPath, err)
		// If that fails, just copy it as a regular file
		if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
			return err
		}
		if err := archive.CopyWithTar(origPath, destPath); err != nil {
			return err
		}
	}
	return nil
}

func (b *buildFile) CmdAdd(args string) error {
	if b.context == "" {
		return fmt.Errorf("No context given. Impossible to use ADD")
	}
	tmp := strings.SplitN(args, " ", 2)
	if len(tmp) != 2 {
		return fmt.Errorf("Invalid ADD format")
	}

	orig, err := b.ReplaceEnvMatches(strings.Trim(tmp[0], " \t"))
	if err != nil {
		return err
	}

	dest, err := b.ReplaceEnvMatches(strings.Trim(tmp[1], " \t"))
	if err != nil {
		return err
	}

	cmd := b.config.Cmd
	b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) ADD %s in %s", orig, dest)}

	b.config.Image = b.image
	// Create the container and start it
	container, _, err := b.runtime.Create(b.config, "")
	if err != nil {
		return err
	}
	b.tmpContainers[container.ID] = struct{}{}

	if err := container.EnsureMounted(); err != nil {
		return err
	}
	defer container.Unmount()

	if utils.IsURL(orig) {
		if err := b.addRemote(container, orig, dest); err != nil {
			return err
		}
	} else {
		if err := b.addContext(container, orig, dest); err != nil {
			return err
		}
	}

	if err := b.commit(container.ID, cmd, fmt.Sprintf("ADD %s in %s", orig, dest)); err != nil {
		return err
	}
	b.config.Cmd = cmd
	return nil
}

func (b *buildFile) run() (string, error) {
	if b.image == "" {
		return "", fmt.Errorf("Please provide a source image with `from` prior to run")
	}
	b.config.Image = b.image

	// Create the container and start it
	c, _, err := b.runtime.Create(b.config, "")
	if err != nil {
		return "", err
	}
	b.tmpContainers[c.ID] = struct{}{}
	fmt.Fprintf(b.out, " ---> Running in %s\n", utils.TruncateID(c.ID))

	// override the entry point that may have been picked up from the base image
	c.Path = b.config.Cmd[0]
	c.Args = b.config.Cmd[1:]

	var errCh chan error

	if b.verbose {
		errCh = utils.Go(func() error {
			return <-c.Attach(nil, nil, b.out, b.out)
		})
	}

	//start the container
	if err := c.Start(); err != nil {
		return "", err
	}

	if errCh != nil {
		if err := <-errCh; err != nil {
			return "", err
		}
	}

	// Wait for it to finish
	if ret := c.Wait(); ret != 0 {
		return "", fmt.Errorf("The command %v returned a non-zero code: %d", b.config.Cmd, ret)
	}

	return c.ID, nil
}

// Commit the container <id> with the autorun command <autoCmd>
func (b *buildFile) commit(id string, autoCmd []string, comment string) error {
	if b.image == "" {
		return fmt.Errorf("Please provide a source image with `from` prior to commit")
	}
	b.config.Image = b.image
	if id == "" {
		cmd := b.config.Cmd
		b.config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
		defer func(cmd []string) { b.config.Cmd = cmd }(cmd)

		if b.utilizeCache {
			if cache, err := b.srv.ImageGetCached(b.image, b.config); err != nil {
				return err
			} else if cache != nil {
				fmt.Fprintf(b.out, " ---> Using cache\n")
				utils.Debugf("[BUILDER] Use cached version")
				b.image = cache.ID
				return nil
			} else {
				utils.Debugf("[BUILDER] Cache miss")
			}
		}

		container, warnings, err := b.runtime.Create(b.config, "")
		if err != nil {
			return err
		}
		for _, warning := range warnings {
			fmt.Fprintf(b.out, " ---> [Warning] %s\n", warning)
		}
		b.tmpContainers[container.ID] = struct{}{}
		fmt.Fprintf(b.out, " ---> Running in %s\n", utils.TruncateID(container.ID))
		id = container.ID
		if err := container.EnsureMounted(); err != nil {
			return err
		}
		defer container.Unmount()
	}

	container := b.runtime.Get(id)
	if container == nil {
		return fmt.Errorf("An error occured while creating the container")
	}

	// Note: Actually copy the struct
	autoConfig := *b.config
	autoConfig.Cmd = autoCmd
	// Commit the container
	image, err := b.runtime.Commit(container, "", "", "", b.maintainer, &autoConfig)
	if err != nil {
		return err
	}
	b.tmpImages[image.ID] = struct{}{}
	b.image = image.ID
	return nil
}

// Long lines can be split with a backslash
var lineContinuation = regexp.MustCompile(`\s*\\\s*\n`)

func (b *buildFile) Build(context io.Reader) (string, error) {
	// FIXME: @creack "name" is a terrible variable name
	name, err := ioutil.TempDir("", "docker-build")
	if err != nil {
		return "", err
	}
	if err := archive.Untar(context, name); err != nil {
		return "", err
	}
	defer os.RemoveAll(name)
	b.context = name
	filename := path.Join(name, "Dockerfile")
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return "", fmt.Errorf("Can't build a directory with no Dockerfile")
	}
	fileBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	dockerfile := string(fileBytes)
	dockerfile = lineContinuation.ReplaceAllString(dockerfile, "")
	stepN := 0
	for _, line := range strings.Split(dockerfile, "\n") {
		line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
		// Skip comments and empty line
		if len(line) == 0 || line[0] == '#' {
			continue
		}
		tmp := strings.SplitN(line, " ", 2)
		if len(tmp) != 2 {
			return "", fmt.Errorf("Invalid Dockerfile format")
		}
		instruction := strings.ToLower(strings.Trim(tmp[0], " "))
		arguments := strings.Trim(tmp[1], " ")

		method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
		if !exists {
			fmt.Fprintf(b.out, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
			continue
		}

		stepN += 1
		fmt.Fprintf(b.out, "Step %d : %s %s\n", stepN, strings.ToUpper(instruction), arguments)

		ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
		if ret != nil {
			return "", ret.(error)
		}

		fmt.Fprintf(b.out, " ---> %v\n", utils.TruncateID(b.image))
	}
	if b.image != "" {
		fmt.Fprintf(b.out, "Successfully built %s\n", utils.TruncateID(b.image))
		if b.rm {
			b.clearTmp(b.tmpContainers)
		}
		return b.image, nil
	}
	return "", fmt.Errorf("An error occurred during the build\n")
}

func NewBuildFile(srv *Server, out io.Writer, verbose, utilizeCache, rm bool) BuildFile {
	return &buildFile{
		runtime:       srv.runtime,
		srv:           srv,
		config:        &Config{},
		out:           out,
		tmpContainers: make(map[string]struct{}),
		tmpImages:     make(map[string]struct{}),
		verbose:       verbose,
		utilizeCache:  utilizeCache,
		rm:            rm,
	}
}


text:
require 'rails_helper'

RSpec.describe "items/edit", type: :view do
  before(:each) do
    @item = assign(:item, Item.create!(
      :name => "MyString",
      :buy_link => "MyString",
      :official_website => "MyString"
    ))
  end

  it "renders the edit item form" do
    render

    assert_select "form[action=?][method=?]", item_path(@item), "post" do

      assert_select "input#item_name[name=?]", "item[name]"

      assert_select "input#item_buy_link[name=?]", "item[buy_link]"

      assert_select "input#item_official_website[name=?]", "item[official_website]"
    end
  end
end


text:
class HostnameResolver
{
public:
	HostnameResolver(const HostnameResolver&) = delete;
	HostnameResolver& operator=(const HostnameResolver&) = delete;
	HostnameResolver(HostnameResolver&&) noexcept = delete;
	HostnameResolver& operator=(HostnameResolver&&) noexcept = delete;

private:
	HostnameResolver() = default;
	~HostnameResolver() = default;

	std::mutex _mutex;
	std::map<std::string, std::tuple<int, std::vector<in_addr>, time_t>> _cache;

public:
	static HostnameResolver& getInstance()
	{
		static HostnameResolver instance;
		return instance;
	}

	static std::tuple<int, std::vector<in_addr>> resolve(std::string host);
};


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCore extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{

		//if (!Schema::hasTable('units'))
      	Schema::create('units',function($t)
		{
			$t->increments('id');
			$t->integer('type_id')->default(0);
			$t->integer('children_type_id')->default(0);
			$t->integer('created_by')->default(0);
			$t->integer('updated_by')->default(0);
			$t->tinyInteger('main')->default(0);
			$t->string('code',255);
			$t->tinyInteger('level')->default(1);
			$t->integer('sort')->default(1);
			$t->integer('parent_id')->default(0);
			$t->string('url',255);
			$t->string('name',255);
			$t->string('title',255);
			$t->integer('image_id')->default(0);
			$t->string('meta_title',255);
			$t->string('meta_keywords',255);
			$t->string('meta_description',255);
			$t->dateTime('public_date');
			$t->string('template',255);
			$t->text('short_content');
          	$t->longText('content');
			$t->integer('count')->default(0);
			$t->tinyInteger('active')->default(0);
			$t->timestamps();
			$t->softDeletes();
		});

		Schema::create('units_childrens',function($t)
		{
			$t->integer('unit_id');
			$t->integer('children_id');
			$t->tinyInteger('level')->default(1);
		});

		Schema::create('types',function($t)
		{
			$t->increments('id');
			$t->string('code',255);
			$t->string('name',255);
			$t->integer('template_id')->default(0);
			$t->tinyInteger('default')->default(0);
		});

		Schema::create('groups',function($t)
		{
			$t->increments('id');
			$t->string('code',255);
			$t->string('name',255);
		});

		Schema::create('group_unit',function($t)
		{
			$t->integer('group_id');
			$t->integer('unit_id');
            $t->integer('sort')->default(1);
		});

		Schema::create('settings',function($t)
		{
			$t->increments('id');
			$t->string('code',255);
			$t->string('name',255);
			$t->string('description',255);
			$t->string('type',255);
			$t->integer('value_int');
			$t->string('value_string',255);
			$t->text('value_text');
            $t->integer('sort')->default(1);
			$t->unique('code');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::dropIfExists('units');
		Schema::dropIfExists('units_childrens');
     	Schema::dropIfExists('groups');
     	Schema::dropIfExists('group_unit');
        Schema::dropIfExists('types');
        Schema::dropIfExists('settings');
	}

}


text:
package sun.jvm.hotspot.bugspot;

import sun.jvm.hotspot.oops.*;

/** Wrapper class which describes line number information for Java
    class files. The line number table is converted into this
    representation on demand. These objects are then sorted by line
    number for fast lookup when setting breakpoints in a particular
    source file. */

public class JavaLineNumberInfo {
  private InstanceKlass klass;
  private Method method;
  private int startBCI;
  private int lineNumber;

  public JavaLineNumberInfo(InstanceKlass klass,
                            Method method,
                            int startBCI,
                            int lineNumber) {
    this.klass = klass;
    this.method = method;
    this.startBCI = startBCI;
    this.lineNumber = lineNumber;
  }

  public InstanceKlass getKlass()      { return klass; }
  public Method        getMethod()     { return method; }
  public int           getStartBCI()   { return startBCI; }
  public int           getLineNumber() { return lineNumber; }
}


text:
import sys
from optparse import OptionParser

from . import __version__
from . import generator

def parse_options():
    """Parses landslide's command line options"""

    parser = OptionParser(
        usage="%prog [options] input.md ...",
        description="Generates a HTML5 slideshow from Markdown or other formats.",
        version="%prog " + __version__)

    parser.add_option(
        "-b", "--debug",
        action="store_true",
        dest="debug",
        help="Will display any exception trace to stdout.",
        default=False)

    parser.add_option(
        "-d", "--destination",
        dest="destination_file",
        help="The path to the to the destination html file. Default: presentation.html.",
        metavar="FILE",
        default="presentation.html")

    parser.add_option(
        "-e", "--encoding",
        dest="encoding",
        help="The encoding of your files. Default: utf8.",
        metavar="ENCODING",
        default="utf8")

    parser.add_option(
        "-i", "--embed",
        action="store_true",
        dest="embed",
        help="Embed stylesheet and javascript contents, base64-encoded images and objects in presentation to make a "
             "standalone document.",
        default=False)

    parser.add_option(
        "-l", "--linenos",
        type="choice",
        choices=generator.VALID_LINENOS,
        dest="linenos",
        help="How to output linenos in source code. Three options available: "
             "no (no line numbers); "
             "inline (inside <pre> tag); "
             "table (lines numbers in another cell, copy-paste friendly).",
        default="inline",
    )

    parser.add_option(
        "-m", "--max-toc-level",
        type="int",
        dest="maxtoclevel",
        help="Limits the TOC level generation to a specific level.",
        default=2)

    parser.add_option(
        "-M", "--mod",
        dest="theme_mod",
        help="Comma-separated list of theme modifiers by name. "
        "Available: wide16x9, showpagenums.",
        default='')

    parser.add_option(
        "-o", "--direct-output",
        action="store_true",
        dest="direct",
        help="Prints the generated HTML code to stdout.",
        default=False)

    parser.add_option(
        "-P", "--no-presenter-notes",
        action="store_false",
        dest="presenter_notes",
        help="Don't include presenter notes in the output.",
        default=True)

    parser.add_option(
        "-q", "--quiet",
        action="store_false",
        dest="verbose",
        help="Won't write anything to stdout (silent mode).",
        default=False)

    parser.add_option(
        "-r", "--relative",
        action="store_true",
        dest="relative",
        help="Make your presentation asset links relative to current working dir; "
             "This may be useful if you intend to publish your html "
             "presentation online.",
        default=False,
    )

    parser.add_option(
        "-t", "--theme",
        dest="theme",
        help="A theme name, or path to a landlside theme directory",
        default='default')

    parser.add_option(
        "-v", "--verbose",
        action="store_true",
        dest="verbose",
        help="Write informational messages to stdout (enabled by default).",
        default=True)

    parser.add_option(
        "-x", "--extensions",
        dest="extensions",
        help="Comma-separated list of extensions for Markdown.",
        default='',
    )

    parser.add_option(
        "-w", "--watch",
        action="store_true",
        dest="watch",
        help="Watch source directory for changes and regenerate slides.",
        default=False
    )

    options, args = parser.parse_args()

    if not args:
        parser.print_help()
        sys.exit(1)

    return options, args[0]

def log(message, type):
    """Log notices to stdout and errors to stderr"""

    (sys.stdout if type == 'notice' else sys.stderr).write(message + "\n")

def run(input_file, options):
    """Runs the Generator using parsed options."""

    options.logger = log
    generator.Generator(input_file, **options.__dict__).execute()

def main():
    """Main program entry point"""

    options, input_file = parse_options()

    if options.debug:
        run(input_file, options)
    else:
        try:
            run(input_file, options)
        except Exception as e:
            sys.stderr.write("Error: %s\n" % e)
            sys.exit(1)


text:
Alpha version.

>An authentication plugin based on [KeyCloak] (http://keycloak.org) for [Aurelia] (http://www.aurelia.io/) applications.

## Important Note
The hidden Keycloak `iframe` that is used to check token update status is turned off by default in this plugin: `checkLoginIframe: false`.  This is to get around a limitation within Aurelia.  This setting requires your code to manually check and/or refresh the token when making API calls.  That is problemmatic. Since the plug-in can be made to operate without an Iframe a simple singleton can be used.  If you have an interest in CORS, REST behaviors, and interoperability with Keycloak, let me know via the issues board.  Kind regards and happy coding.
## Get Started

* Install Aurelia-Keycloak using jspm:
```bash
jspm install aurelia-keycloak
```

* Install Aurelia-Keycloak using Aurelia CLI:
```bash
# Create new Aurelia project
au new

# npm install aurelia-keycloak and add to package.json
npm install git+https://git@github.com/waynepennington/aurelia-keycloak --save
```

Add following to aurelia_project/aurelia.json in the bundles.dependencies section
```json
{
    "name": "aurelia-keycloak",
    "path": "../node_modules/aurelia-keycloak/dist/amd",
    "main": "index"
}
```
Now you can replace the app.js and app.html in the new Aurelia CLI project with the Example model and view below (making sure you change the `export class Welcome` in the model to `export class App`.

* Add keycloak configuration and initialization settings:
Follow Keycloak directions for creating a keycloak.json configuration file.  Put this file in the same directory as your application's index.html file. Refer to the keycloak javascript adapter [documentation] (https://keycloak.gitbooks.io) for its initialization options and API.

* Add plugin to your app's main.js:  This example assumes your keycloak.json is in your root directory.  This code will immediately cause the login screen to appear.
```javascript
export function configure(aurelia) {
    aurelia.use
        .standardConfiguration()
        .developmentLogging()
        .plugin('aurelia-keycloak', {initOptions:{ onLoad: 'login-required' }})
        };

    aurelia.start().then(a => a.setRoot());
}
```

* To defer login, use the following:
```javascript
export function configure(aurelia) {
    aurelia.use
        .standardConfiguration()
        .developmentLogging()
        .plugin('aurelia-keycloak')
        };

    aurelia.start().then(a => a.setRoot());
}
```
Then, construct a login button within your code to call the keycloak login function.
* Rather than use a keycloak.json file, you can insert the installation config with the plugin declaration
```javascript
        .plugin('aurelia-keycloak',
        {
            install:
            {
                "realm": "yourrealm",
                "realm-public-key": "MIIBIjOMLD2DhzrohVDQNClzmh5pv1Enr3L/lM9KPExJgb4i6+8cQolMgKkANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjCYoc4FlNRMOYRxqpbBq852Tdm/E7h5Ndc2RQsLyoEHCO0AgVSe6HoNkkch2/UnazBdaHUkt+4krXH9o1fyQKhzqjhZnpycxgUMRuPnfAoXrHrNgR6vvsWf/G7/WMi6v1Kp8Q8v8e6UphetFJmjR87f/+0D10ZKeZNkWX3evQn8Yp2/2JferjxeW0GYsOdBpwJhqIzCKeoS7L+3j5yzdBiap5azjHZCl6tZjfyFHm7pln/i6QS3gvIEK2w+PxqOrDTKVSO4huU4quNCpGZE3PN3Nrjlc0ItYwIDAQAB",
                "auth-server-url": "https://yourkeycloakserver.com/auth",
                "ssl-required": "external",
                "resource": "a_realm_resource",
                "public-client": true
            }
            initOptions:{ onLoad: 'login-required' }
        }
```
* Or, you can just reference wherever the keycloak.json file is located
```javascript
    .plugin('aurelia-keycloak',
    {
        install: "c:/mydirectory/keycloak.json",
        initOptions:{ onLoad: 'login-required' }
    }
```

**Using with your ViewModel:**

```javascript
import {inject} from 'aurelia-framework';
import {AuthService} from 'aurelia-keycloak';

@inject(AuthService)
export class ViewModel {
    constructor() {
        this.keycloak = AuthService.keycloak;

            }
}
```
See keycloak API and the example js-console for the many examples using its functionality.

## Example API Usage with Aurelia
**Model**
```javascript
import {AuthService} from 'aurelia-keycloak';

import {inject} from 'aurelia-framework';

@inject(AuthService)
export class Welcome {
    heading = 'Welcome to Aurelia-Keycloak!';
    result = "";
    eventHistory = "";

    constructor() {
        self = this;
        this.keycloak = AuthService.keycloak;
        //set callbacks
        this.keycloak.onAuthSuccess = function () {
            self.eventNotice('Auth Success');
        };
        this.keycloak.onAuthError = function () {
            self.eventNotice('Auth Error');
        };
        this.keycloak.onAuthRefreshSuccess = function () {
            self.eventNotice('Auth Refresh Success');
        };
        this.keycloak.onAuthRefreshError = function () {
            self.eventNotice('Auth Refresh Error');
        };
        this.keycloak.onAuthLogout = function () {
            self.eventNotice('Auth Logout');
        };
        this.keycloak.onTokenExpired = function () {
            self.eventNotice('Access token expired.');
        };
    }
    showResults(data) {
        if (typeof data === 'object') {
            data = JSON.stringify(data, null, '  ');
        }
        this.result = data;
    }
    eventNotice(notice) {
        this.eventHistory = new Date().toLocaleString() + "\t" + notice + "\n" + this.eventHistory;
    }
    loadProfile() {
        this.keycloak.loadUserProfile().success(function (profile) {
            self.showResults(profile);
        }).error(function () {
            self.showResults('Failed to load profile');
        });
    }
    loadUserInfo() {
        this.keycloak.loadUserInfo().success(function (userInfo) {
            self.showResults(userInfo);
        }).error(function () {
            self.showResults('Failed to load user info');
        });
    }
    refreshToken(minValidity) {

        this.keycloak.updateToken(minValidity).success(function (refreshed) {
            if (refreshed) {
                self.showResults(this.keycloak.tokenParsed);
            } else {
                self.showResults('Token not refreshed, valid for ' + Math.round(this.keycloak.tokenParsed.exp + this.keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
            }
        }).error(function () {
            showResults('Failed to refresh token');
        });

    }
    showExpires() {
        if (!this.keycloak.tokenParsed) {
            self.showResults("Not authenticated");
            return;
        }
        var o = 'Token Expires:\t\t' + new Date((this.keycloak.tokenParsed.exp + this.keycloak.timeSkew) * 1000).toLocaleString() + '\n';
        o += 'Token Expires in:\t' + Math.round(this.keycloak.tokenParsed.exp + this.keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds\n';
        if (this.keycloak.refreshTokenParsed) {
            o += 'Refresh Token Expires:\t' + new Date((this.keycloak.refreshTokenParsed.exp + this.keycloak.timeSkew) * 1000).toLocaleString() + '\n';
            o += 'Refresh Expires in:\t' + Math.round(this.keycloak.refreshTokenParsed.exp + this.keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds';
        }
        self.showResults(o);
    }
}
```
**View**
```html
<template>
  <section class="au-animate">
    <h2>${heading}</h2>
    <div>
    <button click.trigger ="keycloak.login()">Login</button>
    <button click.trigger ="keycloak.logout()">Logout</button>
    <button click.trigger="refreshToken(9999)">Refresh Token</button>
    <button click.trigger="refreshToken(30)">Refresh Token (if <30s validity)</button>
    <button click.trigger="loadProfile()">Get Profile</button>
    <button click.trigger="loadUserInfo()">Get User Info</button>
    <button click.trigger="showResults(keycloak.tokenParsed)">Show Token</button>
    <button click.trigger="showResults(keycloak.refreshTokenParsed)">Show Refresh Token</button>
    <button click.trigger="showResults(keycloak.idTokenParsed)">Show ID Token</button>
    <button click.trigger="showExpires()">Show Expires</button>
    <button click.trigger="showResults(keycloak)">Show Details</button>
    <button click.trigger="showResults(keycloak.createLoginUrl())">Show Login URL</button>
    <button click.trigger="showResults(keycloak.createLogoutUrl())">Show Logout URL</button>
    <button click.trigger="showResults(keycloak.createRegisterUrl())">Show Register URL</button>

   </div>
<h2>Result</h2>
<pre style="background-color: #ddd; border: 1px solid #ccc; padding: 10px; word-wrap: break-word; white-space: pre-wrap;">${result}</pre>

<h2>Events</h2>
<pre style="background-color: #ddd; border: 1px solid #ccc; padding: 10px; word-wrap: break-word; white-space: pre-wrap;">${eventHistory}</pre>

  </section>
</template>

```
## Building from src

To build this plugin from the source, follow these steps.

* Ensure that you have [Node.js](http://nodejs.org) installed. This is what our tooling will depend on to compile the plugin.

* Inside of the project folder, execute the following command:

```shell
npm install
```

* Ensure that you have Gulp installed globally, using the following command:

```shell
npm install -g gulp
```

* Ensure that you have JSPM installed globally, using the following command:

```shell
npm install -g jspm
```

* To build the plugin, run:

```shell
gulp build
```

* You will then find the compiled code in the 'dist' folder, in three different module formats: AMD, CommonJS and ES6.

## Running The Tests

To run the unit tests (there are none currently), please make sure you follow the above steps and then follow each step below to get the testing environment setup.

* Ensure that the [Karma](http://karma-runner.github.io/) CLI is installed. If it is not installed, then install it using the following command:

  ```shell
  npm install -g karma-cli
  ```

* Install the browser client-side dependencies with JSPM:

  ```shell
  jspm install aurelia-keycloak
  ```
* No testing yet.  ... You can now run the tests with this command:

  ```shell
  karma start
  ```


text:
1390

1392

Dorman I Conquers Southern Dormania
The south of Dormania was far less populous than the Imperial heartland but nevertheless provided the first stiff resistance Dorman encountered.  Malidal in particular was ruled by a powerful and intelligent archmage who successfully countered many of Dorman's attempted tricks.  Nevertheless Dorman was successful over only a couple of years in conquering all of southern Dormania.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of filterzm</title>
  <meta name="keywords" content="filterzm">
  <meta name="description" content="FILTERZM          Zero-phase 1-D digital filter (memory efficient).">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2003 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../../m2html.css">

Home >  chronux_2_00 > spikesort > utility > datatools > filterzm.m

filterzm

PURPOSE

FILTERZM          Zero-phase 1-D digital filter (memory efficient).

SYNOPSIS

function Y = filterzm(B, X)

DESCRIPTION

FILTERZM          Zero-phase 1-D digital filter (memory efficient).
   Y = FILTERZ(B, X) filters the data in vector X with the FIR filter
   given by the vector B to create the filtered data Y, shifting the
   filter to give zero-phase delay.  The process is equivalent to
   convolution with the time-reversed and shifted filter B:
   For P = ceil((length(B)+1)/2),
     y(n) = ... + x(n-1)*b(P+1) + x(n)*b(P) + x(n+1)*b(P-1) + ...

   If X is a matrix, FILTERZM operates along the columns.  X is not
   allowed to be of dimension greater than 2.

   FILTERZM(B, X) is similar to FILTER2(B,X,'same'), except that FILTERZM
   operates on non-double data, avoiding the memory penalty of converting
   an entire data array to double precision.  It is analogous in this
   respect to FILTERM and follows the same datatype conventions as that
   function.  However, by restricting usage only to FIR filters, FILTERZM
   provides zero-phase delay filtering and is faster than FILTERM(B,1,X).

   See also FILTERM, FILTER2.

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

SOURCE CODE

0001 function Y = filterzm(B, X)
0002 %FILTERZM          Zero-phase 1-D digital filter (memory efficient).
0003 %   Y = FILTERZ(B, X) filters the data in vector X with the FIR filter
0004 %   given by the vector B to create the filtered data Y, shifting the
0005 %   filter to give zero-phase delay.  The process is equivalent to
0006 %   convolution with the time-reversed and shifted filter B:
0007 %   For P = ceil((length(B)+1)/2),
0008 %     y(n) = ... + x(n-1)*b(P+1) + x(n)*b(P) + x(n+1)*b(P-1) + ...
0009 %
0010 %   If X is a matrix, FILTERZM operates along the columns.  X is not
0011 %   allowed to be of dimension greater than 2.
0012 %
0013 %   FILTERZM(B, X) is similar to FILTER2(B,X,'same'), except that FILTERZM
0014 %   operates on non-double data, avoiding the memory penalty of converting
0015 %   an entire data array to double precision.  It is analogous in this
0016 %   respect to FILTERM and follows the same datatype conventions as that
0017 %   function.  However, by restricting usage only to FIR filters, FILTERZM
0018 %   provides zero-phase delay filtering and is faster than FILTERM(B,1,X).
0019 %
0020 %   See also FILTERM, FILTER2.
0021
0022 % Based on from TMW's FILTER.
0023 %  The following commented code tests FILTERMZ against FILTER:
0024 %   (also, monitor memory usage to see memory advantage)
0025 % X = int8(rand(2^22,2)*64);   B = fir1(6, 0.1);
0026 % disp('Running FILTER ...');   drawnow;  tic;
0027 % Y  = int8(filter(B, 1, double(X)));  t(1) = toc;
0028 % disp('Running FILTERZM ...');  drawnow;  tic;
0029 % YM = filterzm(B, X);                 t(2) = toc;
0030 % check = ceil(rand(1e6,1)*length(X));
0031 % mse = sqrt(sum(double(Y(check))-double(YM(check)).^2));
0032 % printf('FILTER: %4.3f sec   FILTERZM: %4.3f sec    (APPROX) MSE: %5.3f', t(1), t(2), mse);
0033
0034
0035 % # elements to process at once: for some reason ~2^11-2^13 seems to work
0036 % best (probably cpu cache, although the range is similar on computers
0037 % with different cache sizes ...) & exact powers of 2 sometimes cause
0038 % hiccups ... so heuristically, 2000 seems reasonable
0039 chunksize = 2000;
0040
0041 %%%%%%%%%%%%%%%%%%%%%%%%%%%% Check Inputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%
0042 % input data check
0043 if (ndims(X) > 2), error('FILTERZM is undefined for arrays of dimension greater than 2.');  end;
0044 if (isvectord(X) == 2), T = 1;  X = X';  else  T = 0;  end;  % col vect for now
0045 [M,N] = size(X);
0046
0047 % Massage filter into proper shape
0048 if (~isvectord(B)),  error('The FIR filter B must be 1-dimensional.');  end;
0049 if (isvectord(B) == 2), B = B';  end;  % force column vector
0050 B = flipud(B);
0051 P = (length(B)-1)/2;  Pt = floor(P);  Pb = ceil(P);  % top/bot filter overhang
0052
0053 % data type check
0054 switch (class(X)),
0055     case 'double',              convert = @double;
0056     case {'uint8','int8'},    convert = @int8;
0057     case {'uint16','int16'},  convert = @int16;
0058     case {'uint32','int32'},  convert = @int32;
0059     otherwise, error('X must be a numeric data type.');
0060 end
0061
0062
0063 %%%%%%%%%%%%%%%%%%%%%%%%%% Do the Filtering %%%%%%%%%%%%%%%%%%%%%%%%%%
0064 if (isa(X, 'double') || M < chunksize),  % no point chunking if double
0065     Y = conv2(double(X), B, 'same');
0066     Y = feval(convert, Y);
0067 else
0068     % Perform the filtering in chunks so that only a portion of the data
0069     % needs to be expanded to double at any given time.
0070     Y = repmat(feval(convert,0), size(X));
0071     X = [repmat(feval(convert,0), [Pt+1, N]);  X;  repmat(feval(convert,0), [Pb+1, N])];
0072     for start = 1:chunksize:M
0073         finish = min(M, start+chunksize-1);
0074         chunk = conv2(double((X(start:(finish+Pt+Pb+2),:))),B,'same');
0075         Y(start:finish,:) = feval(convert, chunk((Pt+2):(end-Pb-1),:));
0076     end
0077 end
0078
0079
0080 %%%%%%%%%%%%%%%%%%%%%%%%%% Clean Up Outputs %%%%%%%%%%%%%%%%%%%%%%%%%%
0081 if (T),  Y = Y';  end;   % if input was row vect, keep same orientation

<address>Generated on Fri 15-Aug-2008 11:35:42 by m2html © 2003</address>


text:
package com.conveyal.analyst.server.utils;

import com.conveyal.analyst.server.AnalystMain;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import models.Shapefile;
import org.opentripplanner.analyst.PointSet;
import org.opentripplanner.analyst.SampleSet;
import org.opentripplanner.analyst.broker.JobStatus;
import org.opentripplanner.analyst.cluster.AnalystClusterRequest;
import org.opentripplanner.analyst.cluster.ResultEnvelope;
import org.opentripplanner.graph_builder.GraphBuilder;
import org.opentripplanner.profile.IsochroneGenerator;
import org.opentripplanner.profile.RepeatedRaptorProfileRouter;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.impl.DefaultStreetVertexIndexFactory;
import org.opentripplanner.standalone.CommandLineParameters;
import org.opentripplanner.standalone.Router;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.function.Predicate;

/**
 * Rudimentary queue manager (for testing purposes only) that performs local computation.
 * Does not have any logic for graph affinity or anything of that sort, or even high-priority vs.
 * low priority.
 */
public class LocalQueueManager extends QueueManager {
    private static final Logger LOG = LoggerFactory.getLogger(LocalQueueManager.class);

    /** the callbacks */
    private Multimap<String, Predicate<JobStatus>> callbacks = HashMultimap.create();

    private Router router;

    LocalQueueManager () {
        LOG.warn("Working offline; this is intended for testing only and will not perform well under load; additionally it does not support multipoint requests.");
    }

    @Override public void enqueue(Collection<AnalystClusterRequest> requests) {
        LOG.error("Multipoint requests are unsupported in local mode.");
    }

    @Override public ResultEnvelope getSinglePoint(AnalystClusterRequest req) throws IOException {
        return compute(req);
    }

    @Override public void addCallback(String jobId, Predicate<JobStatus> callback) {
        callbacks.put(jobId, callback);
    }

    @Override public void cancelJob(String jobId) {
        LOG.warn("Job cancellation is not implemented when working offline. We recommend you use a computation cluster.");
    }

    /** compute a result envelope */
    private ResultEnvelope compute (AnalystClusterRequest req) {
        LOG.debug("handling {}", req);

        if (req.profileRequest == null)
            throw new UnsupportedOperationException("Only profile requests are supported locally");

        // check the graph
        if (router == null || !req.graphId.equals(router.id)) {
            buildGraph(req.graphId);
        }

        // get the pointset
        PointSet ps;

        boolean isochrone = req.destinationPointsetId == null;

        if (!isochrone)
            ps = Shapefile.getShapefile(req.destinationPointsetId).getPointSet();
        else
            ps = PointSet.regularGrid(router.graph.getExtent(), IsochroneGenerator.GRID_SIZE_METERS);

        SampleSet ss = new SampleSet(ps, router.graph.getSampleFactory());

        RepeatedRaptorProfileRouter rrpr = new RepeatedRaptorProfileRouter(router.graph, req.profileRequest, ss);
        ResultEnvelope re = rrpr.route();
        re.destinationPointsetId = req.destinationPointsetId;
        re.jobId = req.jobId;
        re.profile = true;
        re.id = req.id;

        return re;
    }

    /** build a graph */
    private synchronized void buildGraph (String graphId) {
        if (router != null && graphId.equals(router.id))
            return;

        File graphDir = new File(AnalystMain.config.getProperty("application.data"), "graphs");
        graphDir = new File(graphDir, graphId);
        LOG.info("Building graph {} from files in {}", graphId, graphDir);

        CommandLineParameters params = new CommandLineParameters();
        params.build = graphDir;
        params.inMemory = true;
        GraphBuilder gbt = GraphBuilder.forDirectory(params, params.build);
        gbt.run();
        Graph g = gbt.getGraph();
        g.routerId = graphId;
        g.index(new DefaultStreetVertexIndexFactory());
        g.index.clusterStopsAsNeeded();
        router = new Router(graphId, g);
        LOG.info("Done building graph");
    }
}


text:
package zeros;

import splice.ga.BasicChromosome;
import splice.ga.ChromosomeFactory;
import splice.ga.crossovers.SinglePointCrossover;
import splice.ga.genes.IntegerListGene;
import splice.ga.mutators.RandomIntegerMutator;

@SuppressWarnings("rawtypes")
public class ZerosChromosomeFactory extends ChromosomeFactory {
	private int size;
	private int maxValue;

	public ZerosChromosomeFactory(int size, int maxValue) {
		this.size = size;
		this.maxValue = maxValue;
	}

    public void initialize() {
        setMutator(new RandomIntegerMutator(maxValue));
        setCrossover(new SinglePointCrossover<Integer>());
        setGene(new IntegerListGene(size, maxValue));
    }

	@Override
	public BasicChromosome getRandomChromosome() {
		return new ZerosChromosome();
	}

}


text:
{-# LANGUAGE TupleSections #-}
module  Haskell99Pointfree.P24
    (
    ) where

import System.Random
import Control.Lens
import Control.Applicative
import Control.Monad
import Data.Bool.HT
import Control.Monad
import Data.List (nub)
--using nub with take
p24_2 :: Int -> Int -> IO (Maybe [Int])
p24_2 = liftM2 ( `if'` return Nothing) . (>) <*>   ( . (randomRs  . (1,))) . (flip fmap newStdGen .) . (.) . ( . nub) . (Just .) . take
{-
--using until
p24_3 :: Int -> Int -> IO (Maybe [Int])
-}


text:
This package allows you to read and write Torch data from and to [HDF5](http://en.wikipedia.org/wiki/Hierarchical_Data_Format) files. The format is fast,
flexible, and supported by a wide range of other software - including **MATLAB**,
**Python**, and **R**.

[![Build Status](https://travis-ci.org/deepmind/torch-hdf5.png?branch=master)](https://travis-ci.org/deepmind/torch-hdf5)
## Usage

For further information, please consult [the user manual](doc/usage.md).


text:
module GlobalSign
  class Contract
    attr_accessor :first_name, :last_name, :phone_number, :email

    def initialize(first_name:, last_name:, phone_number:, email:)
      @first_name   = first_name
      @last_name    = last_name
      @phone_number = phone_number
      @email        = email
    end
  end
end


text:
<?php

Class Vservices {

	private $_apiUrl;
	private $_curlObj;
	private $_userId;
	private $_password;

	private $_httpUser;
	private $_httpPasswd;

	public function __construct() {
	}
	public function setApiUrl($url) {
		$this->_apiUrl = $url;
	}

	public function setConnection($curl) {
		$this->_curlObj = $curl;
	}

	public function setUserId ($userId) {
		$this->_userId = $userId;
	}

	public function setPassword ($password) {
		$this->_password = $password;
	}

	public function getPrivateTree () {
		$this->_curlObj->create($this->_apiUrl. 'space/dir/isgetall/1');
		$this->_curlObj->option(CURLOPT_BUFFERSIZE, 10);
		$this->_curlObj->options(array(CURLOPT_BUFFERSIZE => 10));
                $post =  $this->_userId ? array('userid' => $this->_userId) : array();
		$this->_curlObj->post($post);
		return $this->_curlObj->execute();
	}

    public function getPreview ($fileId) {
		$this->_curlObj->create($this->_apiUrl. 'space/preview/');
		$this->_curlObj->option(CURLOPT_BUFFERSIZE, 10);
		$this->_curlObj->options(array(CURLOPT_BUFFERSIZE => 10));
                $post =  $this->_userId ? array('fileId' => $fileId,'userId' => $this->_userId) : array();
		$this->_curlObj->post($post);
		return $this->_curlObj->execute();
	}

	/**
	 * $aryParams
	 *
	 * @param unknown $action
	 * @param unknown $aryParams
	 */
	public function actionExecute ($action, $aryParams = array(), $module = 'space') {
		$url = $this->_apiUrl. $module .'/'.$action;

		$this->_curlObj->create($url);
		$this->_curlObj->option(CURLOPT_BUFFERSIZE, 10);
		$this->_curlObj->option(CURLOPT_HEADER, 0);
		$this->_curlObj->option(CURLOPT_FAILONERROR, FALSE);

		if ($this->_httpUser && $this->_httpPasswd) {
			$this->_curlObj->http_login($this->_httpUser, $this->_httpPasswd);
		}

		if ($this->_userId) $aryParams['userid'] = $this->_userId;
		if (count($aryParams) > 0) $this->_curlObj->post($aryParams);

		$result = $this->_curlObj->execute();

		/*$serverIP = gethostbyname (parse_url($this->_apiUrl, PHP_URL_HOST));
		$mapFunc = function($k, $v)
					{
						return "$k/$v";
					};

		$paramStr = array_map($mapFunc, array_keys($aryParams), array_values($aryParams));

		$logApiURL = $url . '/' . implode('/',$paramStr);
		$logMsg = "=========\n" . date('Y-m-d H:i:s') ."\n".'FILE: '. __FILE__ . ' -- LINE:'. __LINE__ . "\n" .'API Result: '."\n------\n". var_export($result, true). "\n------\n" . 'ACTION: '. var_export($logApiURL, true) . "\n" .'PARAMS: '. var_export($aryParams, true). "\n".'API SERVER IP: '.$serverIP. "\n========="."\n\n";
		error_log($logMsg, 3, dirname(dirname(dirname(__FILE__))).'/logs/api.log');*/

		return $result;
	}

	public function __destruct() {

	}
}


text:
module Junkfood

  ##
  # The Junkfood::Ceb module is the namespace for the Command-Query
  # Responsibility Separation component of Junkfood.
  module Ceb
  end
end

require 'junkfood/ceb/base_command'
require 'junkfood/ceb/base_event'
require 'junkfood/ceb/bus'


text:
require 'session'

class SuitesRunner
  TEST_SUITES = [
    [:rspec, 'RSpec', 'RSpec'],
    [:test_unit, 'TestUnit', 'Test::Unit'],
    [:minitest, 'Minitest', 'MiniTest']
  ]

  attr_reader :bash

  def initialize
    @bash = Session::Bash.new
  end

  def run
    TEST_SUITES.each_with_index do |(path, class_fragment, desc), i|
      puts "----------------" unless i == 0
      run_examples(path, class_fragment, desc)
      puts
    end
  end

  def run_examples(path, class_fragment, desc)
    path = File.expand_path("../suites/#{path}/runner.rb", __FILE__)
    # From http://www.eglug.org/node/946
    bash.execute "exec 3>&1", :out => STDOUT, :err => STDERR
    # XXX: why are we checking for this warning here...
    bash.execute "ruby -W #{path} 2>&1 >&3 3>&- | grep -v 'warning: useless use of' 3>&-; STATUS=${PIPESTATUS[0]}", :out => STDOUT, :err => STDERR
    status = bash.execute("echo $STATUS")[0].to_s.strip.to_i
    bash.execute "exec 3>&-", :out => STDOUT, :err => STDERR
    unless status == 0
      raise "#{desc} Suite Failed"
    end
  end
end

if $0 == __FILE__
  SuitesRunner.new.run
end


text:
#ifndef _DEBUGCONSOLE_H_
#define _DEBUGCONSOLE_H_

#include <string>
#include <windows.h>

/** Manages a Debug Console.
 * The DebugConsole manages a debug console. This is mainly a standard
 * windows console that can be used for output.
 *
 * @author Rodrigo Reyes <reyes@charabia.net>
 */

class DebugConsole
{
 private:
  HANDLE m_out;
  HANDLE m_in;

 public:

  /**
   * The default constructor
   */
  DebugConsole();

  /**
   * Creates a console with a given title.
   * This constructor creates the console and set up the title of the
   * console windows with the name passed as parameter.
   *
   * @param title the title of the console
   */
  DebugConsole(const std::string& title);

  /**
   * Output a line of text to the console.
   * @param str the text string
   */
  void writeline(const std::string& str);

  /// Makes the console to wait a key press.
  void waitKey();

};

#endif


text:
<?php
namespace Payum\AuthorizeNet\Aim\Action;

use Payum\Core\Action\ActionInterface;
use Payum\Core\Action\GatewayAwareAction;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Model\PaymentInterface;
use Payum\Core\Request\Convert;
use Payum\Core\Request\GetCurrency;

class ConvertPaymentAction extends GatewayAwareAction
{
    /**
     * {@inheritDoc}
     *
     * @param Convert $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var PaymentInterface $payment */
        $payment = $request->getSource();

        $this->gateway->execute($currency = new GetCurrency($payment->getCurrencyCode()));
        $divisor = pow(10, $currency->exp);

        $details = ArrayObject::ensureArrayObject($payment->getDetails());
        $details['amount'] = $payment->getTotalAmount() / $divisor;
        $details['invoice_num'] = $payment->getNumber();
        $details['description'] = $payment->getDescription();
        $details['email'] = $payment->getClientEmail();
        $details['cust_id'] = $payment->getClientId();

        $request->setResult((array) $details);
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof Convert &&
            $request->getSource() instanceof PaymentInterface &&
            $request->getTo() == 'array'
        ;
    }
}


text:
title: Docker CE Edge documentation
description: Information about current Docker Edge releases
keywords: engine, edge, installation
current_edge: 17.04
---

The current Docker CE Edge release is {{ page.current_edge }}. The Docker CE
Edge channel provides monthly releases which allow you to try new features of
Docker and verify bug fixes quickly. Edge releases are only supported for one
month, and a given Edge release will not receive any updates once a new edge
release is available.

Stable releases are not published to the Edge channel, so Linux repository users
still need to subscribe to the stable channel as well.

Commercial support is not available for Docker CE.

For information about all Docker release channels and expectations about
support, see [Docker channels](/engine/installation/#docker-channels).

This page lists features that are only available in Docker CE Edge releases.
Where applicable, the API and CLI reference documentation has been updated to
reflect these features, but **full documentation for a given feature may not be
available until a Docker CE Stable release incorporates the feature**.

### Docker CE Edge new features

17.04

#### Docker CE Edge 17.04

The following major features and changes are included in Docker CE Edge 17.04.
Continue reading, or go straight to [API and CLI](#api-and-cli),
[Daemon](#daemon), [Dockerfile](#dockerfile), [Services](#services), or
[Stacks](#stacks).

[Read the full release notes](https://github.com/moby/moby/releases/tag/v17.04.0-ce){: target="_blank" class="_" }

##### API and CLI

- Add [version 1.28](/engine/reference/api/v1.28/) of the Docker API.

- Add `--device-cgroup-rule` flag to give containers access to devices that appear
  after the container is started. {% include github-pr.md pr="22563" %}

- Allow swarm nodes to join with `--availability=drain` to prevent them from
  taking non-manager workloads. {% include github-pr.md pr="24993" %}

- Add `publish` and `expose` filters to `docker ps`, so that containers can be
  filtered by port or port range for TCP or UDP protocols {% include github-pr.md pr="27557" %}

- Add `--no-trunc` and `--format` flags to the `docker service ls` command, and
  as well as the ability to specify the default format for `docker service ls`
  using the `ServicesFormat` option to the Docker CLI. Also add a
  `docker stack services` command. {% include github-pr.md pr="28199" %}

- Add ability to filter plugins by whether they are enabled or disabled in
  `docker plugin ls` output. {% include github-pr.md pr="28627" %}

- Add `mode` option to `--log-opts` flag for both `docker` and `dockerd`. If set
  to `non-blocking`, and the log buffer fills up, log messages will be lost, but
  the container will not block. The `max-buffer-size` option controls the
  maximum size of the ring buffer. Defaults to `blocking`, which will cause the
  container to block if messages cannot be logged. See
  [Options for all drivers](/engine/admin/logging/overview.md#options-for-all-drivers).
  {% include github-pr.md pr="28762" %}

- It is no longer possible to inadvertently pull images on an architecture where
  they will not run. {% include github-pr.md pr="29001" %}

- It is now possible to create AWS log groups when using the AWS logging driver.
  See [`awslogs-create-group`](engine/admin/logging/awslogs.md#awslogs-create-group).
  {% include github-pr.md pr="29504" %}

- Add the ability to filter `docker network ls` output by creation time, using
  the `{% raw %}{{CreatedAt}}{% endraw %}` format specifier.
  {% include github-pr.md pr="29900" %}

- Named but untagged images are now removed if you run `docker image prune` if
  `--dangling-only` is set to `true`. {% include github-pr.md pr="30330" %}

- Add `--add-host` flag to `docker build`, which will add entries to the
  `/etc/hosts` file of a container created from that image. The `/etc/hosts`
  file is not saved within the image itself. {% include github-pr.md pr="30383" %}

- Prevent `docker network ls` from pulling all the endpoints, to reduce
  impact on the network. {% include github-pr.md pr="30673" %}

- Windows-specific commands and options no longer show in command help text on
  non-Windows clients. {% include github-pr.md pr="30780" %}

- When you specify an IP address when running `docker network connect`, the
  IP address is now checked for validity. {% include github-pr.md pr="30807" %}

- Add the ability to customize bind-mount consistency to be more appropriate
  for some platforms and workloads. Options are `consistent` (the default),
  `cached`, or `delegated`. {% include github-pr.md pr="31047" %}

##### Daemon

- Docker Daemon logging settings no longer affect the `docker build` command.
  {% include github-pr.md pr="29552" %}

- Add a `registry-mirrors` configuration option for the Docker daemon, which
  replaces the daemon's registry mirrors with a new set of registry mirrors.
  {% include github-pr.md pr="29650" %}

- Add the ability to specify the default shared memory size for the Docker
  daemon, using the `--default-shm-size` or the `default-shm-size` key in
  `daemon.json`. {% include github-pr.md pr="29692" %}

- Add a `no-new-privileges` configuration option for the Docker daemon, which
  prevents unprivileged containers from gaining new privileges.
  {% include github-pr.md pr="29984" %}

- If a Docker client communicates with an older daemon and attempts to perform
  an operation not supported by the daemon, an error is printed, which shows
  the API versions of both the client and daemon.
  {% include github-pr.md pr="30187" %}

- The Docker daemon no longer depends upon `sqlite`. This change means that it
  is not possible to upgrade the Docker daemon from version 1.9 directly to the
  latest version. It is recommended to upgrade from one major version to the
  next, in sequence. {% include github-pr.md pr="30208" %}

##### Dockerfile

- Using the pattern `**/` in a Dockerfile now (correctly) behaves the same as
  `**`. {% include github-pr.md pr="29043" %}

- Time values less than 1 second are no longer allowed in health-check options
  in the Dockerfile. {% include github-pr.md pr="31177" %}

##### Services

- When a service is updated with both `--secret-add` and `--secret-rm` in the
  same operation, the order of operations is now changed so that the
  `--secret-rm` always occurs first. {% include github-pr.md pr="29802" %}

- Add the ability to create or update a service to be read-only using the
  `--read-only` flag. {% include github-pr.md pr="30162" %}

- Docker now updates swarm nodes if the swarm configuration is updated.
  {% include github-pr.md pr="30259" %}

- Add topology-aware placement preferences for Swarm services. This feature
  allows services to be balanced over nodes based on a particular user-defined
  property, such as which datacenter or rack they are located in.
  See [Control service scale and placement](/engine/swarm/services.md#control-service-scale-and-placement).
  {% include github-pr.md pr="30725" %}

- Add the ability to customize the stop signal which will be sent to nodes, when
  creating or updating a service. {% include github-pr.md pr="30754" %}

- Add the ability to address a secret by name or prefix, as well as ID, when
  updating it. {% include github-pr.md pr="30856" %}

- Add the ability to roll back to a previous version of a service if an
  updated service fails to deploy. Several flags are available at service
  creation or update,to control the rollback action, failure threshold,
  monitoring delay, rollback delay, and parallelism.
  {% include github-pr.md pr="31108" %}

- Add the ability to specify the stream when using the Docker service logs API.
  {% include github-pr.md pr="31313" %}

- Add `--tail` and `--since` flags to `docker service logs` command, to filter
  the logs by time or to show the tail of the logs and show new content as it
  is logged. {% include github-pr.md pr="31500" %}

- Add a `--verbose` flag to the `docker inspect` command. For swarm networks,
  this flag shows all nodes and services attached to the network.
  {% include github-pr.md pr="31710" %}

##### Stacks

- Compose file version 3.2 is now supported. This includes support for different
  types of endpoints and expands the options you can use when specifying mounts.
  {% include github-pr.md pr="31795" %}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href = "https://github.com/fluidicon.png">

    <title>IT202/project4</title>

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

      project4
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>

              IT202

            About

              <button class="btn btn-secondary dropdown-toggle nav-link" type="button" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="background-color: transparent; border-color: none;">
                Info
              </button>

Version 2.0

                Repository
                Project Prompt

Author Webpage

                Walden1995.github.io

About Game

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

Your Ship is the one centered at the bottom of the screen.

Controls

Left Arrow or A to move left, Right Arrow or D to move left.

Use the Up Arrow or W key to increase velocity, or the Down Arrow and S key to decrease velocity.

The faster you go the more the coins are worth, but the harder it is to avoid the enemies.

You can use the J and K keys or the Page up and Page Down keys to fire the cannons.

As you progress through the game, the difficulty will increase. But so to will the rewards!

Be warned, the enemies are quite erratic. and will eventually crowd you in.

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

hi

      <canvas width="480" height="270"></canvas>


text:
//**************************************************************************************************
// File: ac_tan_pwl.h
//
// Description: Provides piece-wise linear implementations of the
//    tangent function for the AC (tm) Datatypes: ac_fixed, ac_float,
//    ac_ieee_float.
//
//    The inputs to each function in this header must be positive and
//    must lie in the domain of [0, pi/2)
//
// Usage:
//    A sample testbench and its implementation looks like this:
//
//    #include <ac_math/ac_tan_pwl.h>
//    using namespace ac_math;
//
//    typedef ac_fixed<18, 2, false, AC_RND, AC_SAT> input_type;
//    typedef ac_fixed<64, 32, false, AC_RND, AC_SAT> output_type;
//
//    #pragma hls_design top
//    void project(
//      const input_type &input,
//      output_type &output
//    )
//    {
//      ac_tan_pwl(input,output);
//    }
//
//    #ifndef __SYNTHESIS__
//    #include <mc_scverify.h>
//
//    CCS_MAIN(int arg, char **argc)
//    {
//      input_type input = 0.25;
//      output_type output;
//      CCS_DESIGN(project)(input, output);
//      CCS_RETURN (0);
//    }
//    #endif
//
// Notes:
//    This file uses C++ function overloading and templates for various datatype
//    implementations. Attempting to call it with a type that is not implemented will
//    result in a compile-time error.
//
//    This file uses the ac_reciprocal_pwl() function from ac_reciprocal_pwl.h as well as
//    the ac_shift_left() function from ac_shift.h.
//
// Revision History:
//    3.4.3  - dgb - Updated compiler checks to work with MS VS 2019
//    3.3.0  - CAT-25797, waived CNS violations and fixed FXD violations reported by CDesignChecker.
//    3.2.4  - CAT-24698, Added floating point support.
//    3.1.2  - Improved bitwidth calculations for PWL.
//    2.0.10 - Official open-source release as part of the ac_math library.
//
//**************************************************************************************************

#ifndef _INCLUDED_AC_TAN_PWL_H_
#define _INCLUDED_AC_TAN_PWL_H_

// The functions use default template parameters, which are only supported by C++11 or later
// compiler standards. Hence, the user should be informed if they are not using those standards.
#if (defined(__GNUC__) && (__cplusplus < 201103L))
#error Please use C++11 or a later standard for compilation.
#endif
#if (defined(_MSC_VER) && (_MSC_VER < 1920) && !defined(__EDG__))
#error Please use Microsoft VS 2019 or a later standard for compilation.
#endif

#include <ac_int.h>
// Include headers for data types supported by these implementations
#include <ac_fixed.h>

#if !defined(__SYNTHESIS__) && defined(AC_TAN_PWL_H_DEBUG)
#include <iostream>
#endif

#include <ac_math/ac_reciprocal_pwl.h>
#include <ac_math/ac_shift.h>

//******************************************************************************************
// Function: ac_tan_pwl (for ac_fixed)
//
// Description:
//    Calculation of tangent of real inputs, passed as ac_fixed
//    variables. Inputs and outputs must both be unsigned.
//
// Usage:
//    See above example code for usage.
//
// Notes:
//    The PWL implementation utilizes 8 segments, which has a small impact
//    on accuracy.
//    The ac_fixed implementation also serves as the PWL-based "backbone"
//    for the ac_float and ac_ieee_float versions.
//
//******************************************************************************************

namespace ac_math
{
  template<ac_q_mode pwl_Q = AC_TRN,
           int W, int I, ac_q_mode Q, ac_o_mode O,
           int outW, int outI, ac_q_mode outQ, ac_o_mode outO>
  void ac_tan_pwl(
    const ac_fixed<W, I, false, Q, O> &input,
    ac_fixed<outW, outI, false, outQ, outO> &output
  )
  {
    #ifdef ASSERT_ON_INVALID_INPUT
    AC_ASSERT(input < 1.5704021453857421875, "Input must not exceed pi/2");
    #endif

    // Store the approximate value of 89.17 degrees in radian
    const ac_fixed<11, 1, false> sat_limit = 1.556640625;
    ac_fixed<outW, outI, false, outQ, outO> output_temp;

    // Start of code outputted by ac_tan_pwl_lutgen.cpp
    // NOTE: Any change from the default PWL implementation using values generated by the lutgen file is not guaranteed to give a monotonically increasing PWL output,
    // owing to errors incurred in quantizing the double slope/intercept values to fixed point. The user must change the slope-intercept values themself to ensure monotonicity.

    // The number of fractional bits for the LUT values is chosen by first finding the maximum absolute error over the domain of the PWL
    // when double-precision values are used for LUT values. This error will correspond to a number of fractional bits that are always
    // guaranteed to be error-free, for fixed-point PWL outputs.
    // This number of fractional bits is found out by the formula:
    // nbits = abs(ceil(log2(abs_error_max)) - 1
    // The number of fractional bits hereafter used to store the LUT values is nbits + 2.
    // For this particular PWL implementation, the number of fractional bits is 10.
    const int n_frac_bits = 10;
    // Initialization for PWL LUT
    const unsigned n_segments_lut = 8;
    const ac_fixed<n_frac_bits, 0, false> m_lut[n_segments_lut] = {.0986328125, .099609375, .1044921875, .1103515625, .1201171875, .1328125, .15234375, .1787109375};
    const ac_fixed<n_frac_bits, 0, false> c_lut[n_segments_lut] = {.0, .0986328125, .1982421875, .3037109375, .4140625, .5341796875, .6669921875, .8193359375};
    // Domain of PWL
    const ac_fixed<n_frac_bits, 0, false> x_max_lut = .78515625;
    const ac_fixed<1, 1, false> x_min_lut = 0.0;
    const ac_fixed<14, 4, false> sc_constant_lut = 10.1884765625;

    // End of code outputted by ac_tan_pwl_lutgen.cpp

    // If the input equals or exceeds pi/4, we halve it and use the formula tan(2*x) = 2*tan(x) / (1 - tan(x)^2) to get the tan value.
    // You will only need to add an extra fractional bit if the number of integer bits is greater than or equal to zero, because only then
    // will the input have a chance of exceeding pi/4, and only then will halving be required.

    // The intermediate variable for the input can have a maximum of 20 fractional bits. This maximum is chosen empirically, to limit the
    // area used while also making sure that the error values are the same, up to 3 decimal places, as they would be if we were to not use the
    // 20-bit maximum.
    const int n_f_b_int = AC_MIN(19, W - I) + int(I >= 0);
    const int I_int = AC_MIN(I, 1);
    const int W_int = I_int + n_f_b_int;
    ac_fixed<W_int, I_int, false, Q, O> input_int;
    bool input_exceeds_pi_by_4;
    // Keep in mind that the input can only exceed pi/4 if the number of integer bits is greater than or equal to zero.
    #pragma hls_waive CNS
    if (I >= 0) { input_exceeds_pi_by_4 = (input >= x_max_lut) ? true : false; }

    #pragma hls_waive CNS
    if ((I >= 0) && input_exceeds_pi_by_4) { input_int = (ac_fixed<W_int + 1, I_int, false, Q, O>)input >> 1; }
    else { input_int = input; }

    const int int_bits = ac::nbits<n_segments_lut - 1>::val;
    // Compute tan using pwl.
    // Scale the input from 0 to n_segments_lut
    ac_fixed<n_frac_bits + int_bits, int_bits, false> x_in_sc = (input_int - x_min_lut) * sc_constant_lut;
    // Take out the fractional bits of the scaled input
    ac_fixed<n_frac_bits, 0, false> x_in_sc_frac;
    x_in_sc_frac.set_slc(0, x_in_sc.template slc<n_frac_bits>(0));
    ac_int<int_bits, false> index;
    // The integer part of the input is the index of the LUT table
    index = x_in_sc.to_int();
    // The precision given below will ensure that there is no precision lost in the assignment to output_pwl, hence rounding for the variable is switched off by default.
    // However, if the user wishes to use less fractional bits and turn rounding on instead, they are welcome to do so by giving a different value for pwl_Q.
    typedef ac_fixed<2*n_frac_bits, 0, false, pwl_Q> output_pwl_type;
    output_pwl_type output_pwl = m_lut[index]*x_in_sc_frac + c_lut[index];

    // As mentioned earlier, if the input equals or exceeds pi/4, we use the formula tan(2*x) = 2*tan(x) / (1 - tan(x)^2) to get the tan value.
    #pragma hls_waive CNS
    if ((I >= 0) && input_exceeds_pi_by_4) {
      // The bitwidths for the following two declarations were chosen after careful, exhaustive testing to make sure that there were negligible error penalties while using
      // the lowest possible bitwidths, so as to limit the area used, preserve monotonicity and optimize QofR. These bitwidths are optimized for a domain of [0, pi/4) and
      // 8 segments. The user may have to change them in order to suit their own design, in case they change the number of segments and/or the domain.
      ac_fixed<16, 0, false, pwl_Q> one_minus_tan_theta_by_2_sqr = 1 - output_pwl * output_pwl;
      ac_fixed<16, 6, false, pwl_Q> recip_value;
      // Use the reciprocal_pwl function to calculate 1 / (1 - tan(x)^2)
      ac_math::ac_reciprocal_pwl<pwl_Q>(one_minus_tan_theta_by_2_sqr, recip_value);
      output_temp = 2 * output_pwl * recip_value;
    } else {
      output_temp = output_pwl;
    }

    // If input crosses or equals 89.17 degrees (roughly), set the output to saturate
    #pragma hls_waive CNS
    if (input >= sat_limit) { output_temp.template set_val<AC_VAL_MAX>(); }

    output = output_temp;

    #if !defined(__SYNTHESIS__) && defined(AC_TAN_PWL_H_DEBUG)
    std::cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << std::endl;
    std::cout << "input           = " << input << std::endl;
    std::cout << "sc_constant_lut = " << sc_constant_lut << std::endl;
    std::cout << "input_int       = " << input_int << std::endl;
    std::cout << "x_in_sc         = " << x_in_sc << std::endl;
    std::cout << "output_pwl      = " << output_pwl << std::endl;
    std::cout << "output_temp     = " << output_temp << std::endl;
    std::cout << "output          = " << output << std::endl;
    #endif
  }

//******************************************************************************************
// Function: ac_tan_pwl (for ac_float)
//
// Description:
//    Calculation of tangent of real inputs, passed as ac_float
//    variables.
//
// Usage:
//    A sample testbench and its implementation looks like this:
//
//    #include <ac_math/ac_tan_pwl.h>
//    using namespace ac_math;
//
//    typedef ac_float<10, 1, 6, AC_TRN> input_type;
//    typedef ac_float<16, 1, 9, AC_TRN> output_type;
//
//    #pragma hls_design top
//    void project(
//      const input_type &input,
//      output_type &output
//    )
//    {
//      ac_tan_pwl(input,output);
//    }
//
//    #ifndef __SYNTHESIS__
//    #include <mc_scverify.h>
//
//    CCS_MAIN(int arg, char **argc)
//    {
//      input_type input = 0.25;
//      output_type output;
//      CCS_DESIGN(project)(input, output);
//      CCS_RETURN (0);
//    }
//    #endif
//
// Notes:
//    This implementation relies on the ac_fixed implementation of ac_tan_pwl.
//
//******************************************************************************************

  template<ac_q_mode pwl_Q = AC_TRN,
           int W, int I, int E, ac_q_mode Q,
           int outW, int outI, int outE, ac_q_mode outQ>
  void ac_tan_pwl(
    const ac_float<W, I, E, Q> &input,
    ac_float<outW, outI, outE, outQ> &output
  )
  {
    #ifdef ASSERT_ON_INVALID_INPUT
    AC_ASSERT(input >= 0, "Input must be positive.");
    AC_ASSERT(input < 1.57040202617645263671875, "Input must not exceed pi/2");
    #endif

    // Input is always assumed to be positive -> sign bit is unnecessary.
    ac_fixed<W - 1, I - 1, false> mantVal = input.mantissa();
    int exp_val = input.exp().to_int();
    // Intermediate ac_fixed variables to store the value of inputs and outputs
    // and enable compatibility with ac_fixed implementation.
    ac_fixed<22, 1, false, AC_RND> tan_input_fi;
    // tan_input_fi = mantVal*2^(exp_val) = mantVal << exp_val
    // Use ac_shift_left instead of "<<" operator to ensure rounding.
    // Saturation is not required because the input is assumed to never exceed pi/2.
    ac_math::ac_shift_left(mantVal, exp_val, tan_input_fi);
    ac_fixed<36, 7, false> tan_output_fi;
    ac_tan_pwl<pwl_Q>(tan_input_fi, tan_output_fi);
    // Convert ac_fixed output to ac_float by using a constructor.
    ac_float<outW, outI, outE, outQ> output_temp(tan_output_fi);

    output = output_temp;
  }

// For this section of the code to work, the user must include ac_std_float.h in their testbench before including the tan header,
// so as to have the code import the ac_std_float and ac_ieee_float datatypes, and define the __AC_STD_FLOAT_H macro.
  #ifdef __AC_STD_FLOAT_H
//=========================================================================
// Function: ac_tan_pwl (for ac_std_float)
//
// Description:
//    Calculation of tangent of real inputs, passed as ac_std_float
//    variables.
//
// Usage:
//    A sample testbench and its implementation looks like this:
//
//    // IMPORTANT: ac_std_float.h header file must be included in testbench,
//    // before including ac_tan_pwl.h.
//    #include <ac_std_float.h>
//    #include <ac_math/ac_tan_pwl.h>
//    using namespace ac_math;
//
//    typedef ac_std_float<32, 8> input_type;
//    typedef ac_std_float<32, 8> output_type;
//
//    #pragma hls_design top
//    void project(
//      const input_type &input,
//      output_type &output
//    )
//    {
//      ac_tan_pwl(input, output);
//    }
//
//    #ifndef __SYNTHESIS__
//    #include <mc_scverify.h>
//
//    CCS_MAIN(int arg, char **argc)
//    {
//      input_type input(0.25);
//      output_type output;
//      CCS_DESIGN(project)(input, output);
//      CCS_RETURN (0);
//    }
//    #endif
//
//-------------------------------------------------------------------------

  template <ac_q_mode pwl_Q = AC_TRN, int W, int E, int outW, int outE>
  void ac_tan_pwl(
    const ac_std_float<W, E> &input,
    ac_std_float<outW, outE> &output
  )
  {
    ac_float<outW - outE + 1, 2, outE> output_ac_fl; // Equivalent ac_float representation for output.
    ac_tan_pwl<pwl_Q>(input.to_ac_float(), output_ac_fl); // Call ac_float version.
    ac_std_float<outW, outE> output_temp(output_ac_fl); // Convert output ac_float to ac_std_float.
    output = output_temp;
  }

//=========================================================================
// Function: ac_tan_pwl (for ac_ieee_float)
//
// Description:
//    Calculation of tangent of real inputs, passed as ac_ieee_float
//    variables.
//
// Usage:
//    A sample testbench and its implementation looks like this:
//
//    // IMPORTANT: ac_std_float.h header file must be included in testbench,
//    // before including ac_tan_pwl.h.
//    #include <ac_std_float.h>
//    #include <ac_math/ac_tan_pwl.h>
//    using namespace ac_math;
//
//    typedef ac_ieee_float<binary32> input_type;
//    typedef ac_ieee_float<binary32> output_type;
//
//    #pragma hls_design top
//    void project(
//      const input_type &input,
//      output_type &output
//    )
//    {
//      ac_tan_pwl(input, output);
//    }
//
//    #ifndef __SYNTHESIS__
//    #include <mc_scverify.h>
//
//    CCS_MAIN(int arg, char **argc)
//    {
//      input_type input(0.25);
//      output_type output;
//      CCS_DESIGN(project)(input, output);
//      CCS_RETURN (0);
//    }
//    #endif
//
//-------------------------------------------------------------------------

  template<ac_q_mode pwl_Q = AC_TRN,
           ac_ieee_float_format Format,
           ac_ieee_float_format outFormat>
  void ac_tan_pwl(
    const ac_ieee_float<Format> &input,
    ac_ieee_float<outFormat> &output
  )
  {
    typedef ac_ieee_float<outFormat> T_out;
    const int outW = T_out::width;
    const int outE = T_out::e_width;
    ac_float<outW - outE + 1, 2, outE> output_ac_fl; // Equivalent ac_float representation for output.
    ac_tan_pwl<pwl_Q>(input.to_ac_float(), output_ac_fl); // Call ac_float version.
    ac_ieee_float<outFormat> output_temp(output_ac_fl); // Convert output ac_float to ac_ieee_float.
    output = output_temp;
  }
  #endif

  // The following version enables a return-by-value.
  template<class T_out, ac_q_mode pwl_Q = AC_TRN, class T_in>
  T_out ac_tan_pwl(const T_in &input)
  {
    T_out output;
    ac_tan_pwl(input, output);
    return output;
  }

}

#endif // _INCLUDED_AC_TAN_PWL_H_


text:
namespace NpDeck.Detectors
{
    public interface IDetector
    {
        Result Detect();
    }
}


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'

import fetch from 'isomorphic-fetch'
import Loading from './Loading'
import {imgUrl} from '../util'

class HomeList extends Component {
    static propTypes = {
        stories: PropTypes.array,
        loading: PropTypes.bool
    }

    constructor(props) {
        super(props);
        this.renderStories = this.renderStories.bind(this)
    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    renderStories () {
        let stories = this.props.stories;
    //    console.log(stories);

        return stories.map((item,i) => {
            if(item.images && item.images.length>0){
                return

{item.title}

            }else{
                return

{item.title}

            }
        })
    }

    render() {
        return (

                    {this.renderStories()}

                {this.props.loading ? <Loading /> : null}

        );
    }
}

export default HomeList


text:
SampleCode
==========

This repository is basically to host all the sample code that I have written just for fun or as a part of an assignment.


text:
import os
import shutil

def extract2folder(file_list, dst_folder):
    for file in file_list:
        src = file
        dst = os.path.join(dst_folder, os.path.basename(file))
        # shutil.copyfile(src, dst)
        open(dst, 'a').close()