text:
package helpers

import (
	"bytes"
	"html/template"
	"os/exec"
	"unicode/utf8"

	"github.com/miekg/mmark"
	"github.com/mitchellh/mapstructure"
	"github.com/russross/blackfriday"
	"github.com/spf13/cast"
	bp "github.com/spf13/hugo/bufferpool"
	jww "github.com/spf13/jwalterweatherman"
	"github.com/spf13/viper"

	"strings"
	"sync"
)

// Length of the summary that Hugo extracts from a content.
var SummaryLength = 70

// Custom divider  let's user define where summarization ends.
var SummaryDivider = []byte("")

// Blackfriday holds configuration values for Blackfriday rendering.
type Blackfriday struct {
	Smartypants     bool
	AngledQuotes    bool
	Fractions       bool
	HrefTargetBlank bool
	SmartDashes     bool
	LatexDashes     bool
	PlainIDAnchors  bool
	Extensions      []string
	ExtensionsMask  []string
}

// NewBlackfriday creates a new Blackfriday filled with site config or some sane defaults
func NewBlackfriday() *Blackfriday {
	combinedParam := map[string]interface{}{
		"smartypants":     true,
		"angledQuotes":    false,
		"fractions":       true,
		"hrefTargetBlank": false,
		"smartDashes":     true,
		"latexDashes":     true,
		"plainIDAnchors":  false,
	}

	siteParam := viper.GetStringMap("blackfriday")
	if siteParam != nil {
		siteConfig := cast.ToStringMap(siteParam)

		for key, value := range siteConfig {
			combinedParam[key] = value
		}
	}

	combinedConfig := &Blackfriday{}
	if err := mapstructure.Decode(combinedParam, combinedConfig); err != nil {
		jww.FATAL.Printf("Failed to get site rendering config\n%s", err.Error())
	}

	return combinedConfig
}

var blackfridayExtensionMap = map[string]int{
	"noIntraEmphasis":        blackfriday.EXTENSION_NO_INTRA_EMPHASIS,
	"tables":                 blackfriday.EXTENSION_TABLES,
	"fencedCode":             blackfriday.EXTENSION_FENCED_CODE,
	"autolink":               blackfriday.EXTENSION_AUTOLINK,
	"strikethrough":          blackfriday.EXTENSION_STRIKETHROUGH,
	"laxHtmlBlocks":          blackfriday.EXTENSION_LAX_HTML_BLOCKS,
	"spaceHeaders":           blackfriday.EXTENSION_SPACE_HEADERS,
	"hardLineBreak":          blackfriday.EXTENSION_HARD_LINE_BREAK,
	"tabSizeEight":           blackfriday.EXTENSION_TAB_SIZE_EIGHT,
	"footnotes":              blackfriday.EXTENSION_FOOTNOTES,
	"noEmptyLineBeforeBlock": blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK,
	"headerIds":              blackfriday.EXTENSION_HEADER_IDS,
	"titleblock":             blackfriday.EXTENSION_TITLEBLOCK,
	"autoHeaderIds":          blackfriday.EXTENSION_AUTO_HEADER_IDS,
	"definitionLists":        blackfriday.EXTENSION_DEFINITION_LISTS,
}

var stripHTMLReplacer = strings.NewReplacer("\n", " ", "
", "\n", "
", "\n", "
", "\n")

var mmarkExtensionMap = map[string]int{
	"tables":                 mmark.EXTENSION_TABLES,
	"fencedCode":             mmark.EXTENSION_FENCED_CODE,
	"autolink":               mmark.EXTENSION_AUTOLINK,
	"laxHtmlBlocks":          mmark.EXTENSION_LAX_HTML_BLOCKS,
	"spaceHeaders":           mmark.EXTENSION_SPACE_HEADERS,
	"hardLineBreak":          mmark.EXTENSION_HARD_LINE_BREAK,
	"footnotes":              mmark.EXTENSION_FOOTNOTES,
	"noEmptyLineBeforeBlock": mmark.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK,
	"headerIds":              mmark.EXTENSION_HEADER_IDS,
	"autoHeaderIds":          mmark.EXTENSION_AUTO_HEADER_IDS,
}

// StripHTML accepts a string, strips out all HTML tags and returns it.
func StripHTML(s string) string {

	// Shortcut strings with no tags in them
	if !strings.ContainsAny(s, "<>") {
		return s
	}
	s = stripHTMLReplacer.Replace(s)

	// Walk through the string removing all tags
	b := bp.GetBuffer()
	defer bp.PutBuffer(b)

	inTag := false
	for _, r := range s {
		switch r {
		case '<':
			inTag = true
		case '>':
			inTag = false
		default:
			if !inTag {
				b.WriteRune(r)
			}
		}
	}
	return b.String()
}

// StripEmptyNav strips out empty  tags from content.
func StripEmptyNav(in []byte) []byte {
	return bytes.Replace(in, []byte("\n\n\n"), []byte(``), -1)
}

// BytesToHTML converts bytes to type template.HTML.
func BytesToHTML(b []byte) template.HTML {
	return template.HTML(string(b))
}

// GetHtmlRenderer creates a new Renderer with the given configuration.
func GetHTMLRenderer(defaultFlags int, ctx *RenderingContext) blackfriday.Renderer {
	renderParameters := blackfriday.HtmlRendererParameters{
		FootnoteAnchorPrefix:       viper.GetString("FootnoteAnchorPrefix"),
		FootnoteReturnLinkContents: viper.GetString("FootnoteReturnLinkContents"),
	}

	b := len(ctx.DocumentID) != 0

	if b && !ctx.getConfig().PlainIDAnchors {
		renderParameters.FootnoteAnchorPrefix = ctx.DocumentID + ":" + renderParameters.FootnoteAnchorPrefix
		renderParameters.HeaderIDSuffix = ":" + ctx.DocumentID
	}

	htmlFlags := defaultFlags
	htmlFlags |= blackfriday.HTML_USE_XHTML
	htmlFlags |= blackfriday.HTML_FOOTNOTE_RETURN_LINKS

	if ctx.getConfig().Smartypants {
		htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
	}

	if ctx.getConfig().AngledQuotes {
		htmlFlags |= blackfriday.HTML_SMARTYPANTS_ANGLED_QUOTES
	}

	if ctx.getConfig().Fractions {
		htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
	}

	if ctx.getConfig().HrefTargetBlank {
		htmlFlags |= blackfriday.HTML_HREF_TARGET_BLANK
	}

	if ctx.getConfig().SmartDashes {
		htmlFlags |= blackfriday.HTML_SMARTYPANTS_DASHES
	}

	if ctx.getConfig().LatexDashes {
		htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
	}

	return &HugoHtmlRenderer{
		blackfriday.HtmlRendererWithParameters(htmlFlags, "", "", renderParameters),
	}
}

func getMarkdownExtensions(ctx *RenderingContext) int {
	flags := 0 | blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES | blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK | blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS | blackfriday.EXTENSION_FOOTNOTES |
		blackfriday.EXTENSION_HEADER_IDS | blackfriday.EXTENSION_AUTO_HEADER_IDS |
		blackfriday.EXTENSION_DEFINITION_LISTS
	for _, extension := range ctx.getConfig().Extensions {
		if flag, ok := blackfridayExtensionMap[extension]; ok {
			flags |= flag
		}
	}
	for _, extension := range ctx.getConfig().ExtensionsMask {
		if flag, ok := blackfridayExtensionMap[extension]; ok {
			flags &= ^flag
		}
	}
	return flags
}

func markdownRender(ctx *RenderingContext) []byte {
	return blackfriday.Markdown(ctx.Content, GetHTMLRenderer(0, ctx),
		getMarkdownExtensions(ctx))
}

func markdownRenderWithTOC(ctx *RenderingContext) []byte {
	return blackfriday.Markdown(ctx.Content,
		GetHTMLRenderer(blackfriday.HTML_TOC, ctx),
		getMarkdownExtensions(ctx))
}

// mmark
func GetMmarkHtmlRenderer(defaultFlags int, ctx *RenderingContext) mmark.Renderer {
	renderParameters := mmark.HtmlRendererParameters{
		FootnoteAnchorPrefix:       viper.GetString("FootnoteAnchorPrefix"),
		FootnoteReturnLinkContents: viper.GetString("FootnoteReturnLinkContents"),
	}

	b := len(ctx.DocumentID) != 0

	if b && !ctx.getConfig().PlainIDAnchors {
		renderParameters.FootnoteAnchorPrefix = ctx.DocumentID + ":" + renderParameters.FootnoteAnchorPrefix
		// renderParameters.HeaderIDSuffix = ":" + ctx.DocumentId
	}

	htmlFlags := defaultFlags
	htmlFlags |= mmark.HTML_FOOTNOTE_RETURN_LINKS

	return &HugoMmarkHtmlRenderer{
		mmark.HtmlRendererWithParameters(htmlFlags, "", "", renderParameters),
	}
}

func GetMmarkExtensions(ctx *RenderingContext) int {
	flags := 0
	flags |= mmark.EXTENSION_TABLES
	flags |= mmark.EXTENSION_FENCED_CODE
	flags |= mmark.EXTENSION_AUTOLINK
	flags |= mmark.EXTENSION_SPACE_HEADERS
	flags |= mmark.EXTENSION_CITATION
	flags |= mmark.EXTENSION_TITLEBLOCK_TOML
	flags |= mmark.EXTENSION_HEADER_IDS
	flags |= mmark.EXTENSION_AUTO_HEADER_IDS
	flags |= mmark.EXTENSION_UNIQUE_HEADER_IDS
	flags |= mmark.EXTENSION_FOOTNOTES
	flags |= mmark.EXTENSION_SHORT_REF
	flags |= mmark.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
	flags |= mmark.EXTENSION_INCLUDE

	for _, extension := range ctx.getConfig().Extensions {
		if flag, ok := mmarkExtensionMap[extension]; ok {
			flags |= flag
		}
	}
	return flags
}

func MmarkRender(ctx *RenderingContext) []byte {
	return mmark.Parse(ctx.Content, GetMmarkHtmlRenderer(0, ctx),
		GetMmarkExtensions(ctx)).Bytes()
}

func MmarkRenderWithTOC(ctx *RenderingContext) []byte {
	return mmark.Parse(ctx.Content,
		GetMmarkHtmlRenderer(0, ctx),
		GetMmarkExtensions(ctx)).Bytes()
}

// ExtractTOC extracts Table of Contents from content.
func ExtractTOC(content []byte) (newcontent []byte, toc []byte) {
	origContent := make([]byte, len(content))
	copy(origContent, content)
	first := []byte(`

`)

	last := []byte(`

`)

	replacement := []byte(`

`)

	startOfTOC := bytes.Index(content, first)

	peekEnd := len(content)
	if peekEnd > 70+startOfTOC {
		peekEnd = 70 + startOfTOC
	}

	if startOfTOC < 0 {
		return StripEmptyNav(content), toc
	}
	// Need to peek ahead to see if this nav element is actually the right one.
	correctNav := bytes.Index(content[startOfTOC:peekEnd], []byte(`<li><a href="#`))
	if correctNav < 0 { // no match found
		return content, toc
	}
	lengthOfTOC := bytes.Index(content[startOfTOC:], last) + len(last)
	endOfTOC := startOfTOC + lengthOfTOC

	newcontent = append(content[:startOfTOC], content[endOfTOC:]...)
	toc = append(replacement, origContent[startOfTOC+len(first):endOfTOC]...)
	return
}

// RenderingContext holds contextual information, like content and configuration,
// for a given content renderin.g
type RenderingContext struct {
	Content    []byte
	PageFmt    string
	DocumentID string
	Config     *Blackfriday
	configInit sync.Once
}

func (c *RenderingContext) getConfig() *Blackfriday {
	c.configInit.Do(func() {
		if c.Config == nil {
			c.Config = NewBlackfriday()
		}
	})
	return c.Config
}

// RenderBytesWithTOC renders a []byte with table of contents included.
func RenderBytesWithTOC(ctx *RenderingContext) []byte {
	switch ctx.PageFmt {
	default:
		return markdownRenderWithTOC(ctx)
	case "markdown":
		return markdownRenderWithTOC(ctx)
	case "asciidoc":
		return []byte(GetAsciidocContent(ctx.Content))
	case "mmark":
		return MmarkRenderWithTOC(ctx)
	case "rst":
		return []byte(GetRstContent(ctx.Content))
	}
}

// RenderBytes renders a []byte.
func RenderBytes(ctx *RenderingContext) []byte {
	switch ctx.PageFmt {
	default:
		return markdownRender(ctx)
	case "markdown":
		return markdownRender(ctx)
	case "asciidoc":
		return []byte(GetAsciidocContent(ctx.Content))
	case "mmark":
		return MmarkRender(ctx)
	case "rst":
		return []byte(GetRstContent(ctx.Content))
	}
}

// TotalWords returns an int of the total number of words in a given content.
func TotalWords(s string) int {
	return len(strings.Fields(s))
}

// WordCount takes content and returns a map of words and count of each word.
func WordCount(s string) map[string]int {
	m := make(map[string]int)
	for _, f := range strings.Fields(s) {
		m[f]++
	}

	return m
}

// RemoveSummaryDivider removes summary-divider  from content.
func RemoveSummaryDivider(content []byte) []byte {
	return bytes.Replace(content, SummaryDivider, []byte(""), -1)
}

// TruncateWords takes content and an int and shortens down the number
// of words in the content down to the number of int.
func TruncateWords(s string, max int) string {
	words := strings.Fields(s)
	if max > len(words) {
		return strings.Join(words, " ")
	}

	return strings.Join(words[:max], " ")
}

func TruncateWordsByRune(words []string, max int) (string, bool) {
	count := 0
	for index, word := range words {
		if count >= max {
			return strings.Join(words[:index], " "), true
		}
		runeCount := utf8.RuneCountInString(word)
		if len(word) == runeCount {
			count++
		} else if count+runeCount < max {
			count += runeCount
		} else {
			for ri, _ := range word {
				if count >= max {
					truncatedWords := append(words[:index], word[:ri])
					return strings.Join(truncatedWords, " "), true
				} else {
					count++
				}
			}
		}
	}

	return strings.Join(words, " "), false
}

// TruncateWordsToWholeSentence takes content and an int
// and returns entire sentences from content, delimited by the int
// and whether it's truncated or not.
func TruncateWordsToWholeSentence(words []string, max int) (string, bool) {
	if max >= len(words) {
		return strings.Join(words, " "), false
	}

	for counter, word := range words[max:] {
		if strings.HasSuffix(word, ".") ||
			strings.HasSuffix(word, "?") ||
			strings.HasSuffix(word, ".\"") ||
			strings.HasSuffix(word, "!") {
			upper := max + counter + 1
			return strings.Join(words[:upper], " "), (upper < len(words))
		}
	}

	return strings.Join(words[:max], " "), true
}

// GetAsciidocContent calls asciidoctor or asciidoc as an external helper
// to convert AsciiDoc content to HTML.
func GetAsciidocContent(content []byte) string {
	cleanContent := bytes.Replace(content, SummaryDivider, []byte(""), 1)

	path, err := exec.LookPath("asciidoctor")
	if err != nil {
		path, err = exec.LookPath("asciidoc")
		if err != nil {
			jww.ERROR.Println("asciidoctor / asciidoc not found in $PATH: Please install.\n",
				"                 Leaving AsciiDoc content unrendered.")
			return (string(content))
		}
	}

	jww.INFO.Println("Rendering with", path, "...")
	cmd := exec.Command(path, "--no-header-footer", "--safe", "-")
	cmd.Stdin = bytes.NewReader(cleanContent)
	var out bytes.Buffer
	cmd.Stdout = &out
	if err := cmd.Run(); err != nil {
		jww.ERROR.Println(err)
	}

	return out.String()
}

// GetRstContent calls the Python script rst2html as an external helper
// to convert reStructuredText content to HTML.
func GetRstContent(content []byte) string {
	cleanContent := bytes.Replace(content, SummaryDivider, []byte(""), 1)

	path, err := exec.LookPath("rst2html")
	if err != nil {
		path, err = exec.LookPath("rst2html.py")
		if err != nil {
			jww.ERROR.Println("rst2html / rst2html.py not found in $PATH: Please install.\n",
				"                 Leaving reStructuredText content unrendered.")
			return (string(content))
		}
	}

	cmd := exec.Command(path, "--leave-comments")
	cmd.Stdin = bytes.NewReader(cleanContent)
	var out bytes.Buffer
	cmd.Stdout = &out
	if err := cmd.Run(); err != nil {
		jww.ERROR.Println(err)
	}

	rstLines := strings.Split(out.String(), "\n")
	for i, line := range rstLines {
		if strings.HasPrefix(line, "") {
			rstLines = (rstLines[i+1 : len(rstLines)-3])
		}
	}
	return strings.Join(rstLines, "\n")
}


text:
<manifest package="com.perchlive.broadcast.sdk"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Required for AWS uploading -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- Required for A/V Capture -->
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.CAMERA"/>

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true">

        <service
            android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
            android:enabled="true" />

    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
package org.jooq.lambda;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * @author Lukas Eder
 */
public class CheckedRunnableTest {

    @Test
    public void testCheckedRunnable() {
        Runnable test = Unchecked.runnable(
            () -> {
                throw new Exception("runnable");
            }
        );

        assertRunnable(test, UncheckedException.class);
    }

    @Test
    public void testCheckedRunnableWithCustomHandler() {
        Runnable test = Unchecked.runnable(
            () -> {
                throw new Exception("runnable");
            },
            e -> {
                throw new IllegalStateException(e);
            }
        );

        assertRunnable(test, IllegalStateException.class);
    }

    private <E extends RuntimeException> void assertRunnable(Runnable test, Class<E> type) {
        assertNotNull(test);
        try {
            test.run();
            fail();
        }
        catch (RuntimeException e) {
            assertException(type, e, "runnable");
        }
    }

    private <E extends RuntimeException> void assertException(Class<E> type, RuntimeException e, String message) {
        assertEquals(type, e.getClass());
        assertEquals(Exception.class, e.getCause().getClass());
        assertEquals(message, e.getCause().getMessage());
    }
}


text:
Projeto responsável pelas apis que irão controlar os passos de um robô no território de Marte.

## Tecnologias utilizadas

* Linguagem Java - Versão 1.8 (Oracle 1.8.0_121)

* Spring Boot - Framerwork Web para geração das API's (versão 2.0.0) com Netty

* Maven 3 - Ferramenta de Build.

O repositório utilizado é o Github, onde utilizei o Git flow com a branch develop e master para gerenciar o fonte.

Para realizar o CI usei o Travis com a plataforma Pass Heroku para relizar o deploy da API.

Na pasta postman tem um projeto que poderá ser importado para testar na plataforma Heroku (novo item).

Quando realizo um push o pull request, automanticamente o Travis já efetuar o build e realizava o deploy no heroku.

![Travis](https://github.com/ander-f-silva/control-robot-api/blob/develop/images/travis.png)

Para acessar a serviços usados acione a url (POST) https://control-robot-api.herokuapp.com/rest/mars/${commands}

Payload de retorno:

```
{
    "x": 2,
    "y": 0,
    "orientation": "S"
}
```
## Evidências:

1. Teste no Postman:

https://github.com/ander-f-silva/control-robot-api/wiki/Evid%C3%AAncia-POSTMAN---Teste-sobre-os-servi%C3%A7os

2. Teste no Junit:

https://github.com/ander-f-silva/control-robot-api/wiki/Evid%C3%AAncia-JUNIT---Teste-unit%C3%A1rio

## Gestão do Projeto e técnicas para construção da API

Organizei as atividade usando Kaban com Zenhub e TDD para realizar os testes e construção no design das classes.


text:
using content::BrowserThread;

InProcessImporterBridge::InProcessImporterBridge(ProfileWriter* writer,
                                                 ImporterHost* host)
    : writer_(writer),
      host_(host) {
}

void InProcessImporterBridge::AddBookmarks(
    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
    const string16& first_folder_name) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddBookmarks, writer_, bookmarks,
                 first_folder_name));
}

void InProcessImporterBridge::AddHomePage(const GURL& home_page) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddHomepage, writer_, home_page));
}

#if defined(OS_WIN)
void InProcessImporterBridge::AddIE7PasswordInfo(
    const IE7PasswordInfo& password_info) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddIE7PasswordInfo, writer_, password_info));
}
#endif  // OS_WIN

void InProcessImporterBridge::SetFavicons(
    const std::vector<history::ImportedFaviconUsage>& favicons) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddFavicons, writer_, favicons));
}

void InProcessImporterBridge::SetHistoryItems(
    const history::URLRows &rows,
    history::VisitSource visit_source) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddHistoryPage, writer_, rows, visit_source));
}

void InProcessImporterBridge::SetKeywords(
    const std::vector<TemplateURL*>& template_urls,
    bool unique_on_host_and_path) {
  ScopedVector<TemplateURL> owned_template_urls;
  std::copy(template_urls.begin(), template_urls.end(),
            std::back_inserter(owned_template_urls));
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddKeywords, writer_,
                 base::Passed(&owned_template_urls), unique_on_host_and_path));
}

void InProcessImporterBridge::SetPasswordForm(
    const content::PasswordForm& form) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ProfileWriter::AddPasswordForm, writer_, form));
}

void InProcessImporterBridge::NotifyStarted() {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ImporterHost::NotifyImportStarted, host_));
}

void InProcessImporterBridge::NotifyItemStarted(importer::ImportItem item) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ImporterHost::NotifyImportItemStarted, host_, item));
}

void InProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ImporterHost::NotifyImportItemEnded, host_, item));
}

void InProcessImporterBridge::NotifyEnded() {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ImporterHost::NotifyImportEnded, host_));
}

string16 InProcessImporterBridge::GetLocalizedString(int message_id) {
  return l10n_util::GetStringUTF16(message_id);
}

InProcessImporterBridge::~InProcessImporterBridge() {}


text:
import unittest

from django.test import Client
from django.test.testcases import SimpleTestCase
from django.shortcuts import resolve_url

from todo.forms import TodoForm

class SimpleTest(SimpleTestCase):

    def setUp(self):
        self.client = Client()

    def test_view_list(self):
        response = self.client.get(resolve_url("list"))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,"index.html")

    def test_view_create(self):
        response = self.client.get(resolve_url("add"))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,"add.html")

    def test_create(self):
        response = self.client.post(resolve_url("add"), {"activity":"esto es un texto"}, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,"index.html")
        self.assertTemplateUsed(response.context['list'].count(),0)

    def test_form_invalid(self):
        todo = TodoForm()
        self.assertEqual(todo.is_valid(),False)

    def test_form(self):
        todo = TodoForm({"activity":"esto es un texto"})
        self.assertEqual(todo.is_valid(), True)


text:
/**
 *
 */
package handemapper.gui.util;

import handemapper.common.recognition.Gesture;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author Chris
 *
 */
public final class Gestures {

	private static final String defaultXmlFilePath = "/gestures.xml";

	public static final List<Gesture> load() {
		return load(defaultXmlFilePath);
	}

	public static final List<Gesture> load(String xmlFilePath) {
		final List<Gesture> list = new ArrayList<Gesture>();
		Document xmlDoc = null;
		NodeList nodes, childNodes, paramNodes;
		Node node, childNode, paramNode;
		Map<String,String> gestureMap = new HashMap<String,String>();
		Map<String,String> paramMap = new HashMap<String,String>();

		try {
			xmlDoc = read(xmlFilePath);
			//TODO parse the doc for the gestures...
			//list.addAll(parseDocument(xmlDoc));
			nodes = xmlDoc.getElementsByTagName("gesture");
			for (int i = 0; i < nodes.getLength(); i++) {
				gestureMap.clear();
				node = nodes.item(i);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					System.out.println("node=[" + node.getNodeName() + "]");
					childNodes = node.getChildNodes();
					for (int j = 0; j < childNodes.getLength(); j++) {
						childNode = childNodes.item(j);
						if (childNode.getNodeType() == Node.ELEMENT_NODE) {
							System.out.println("  --> node=[" + childNode.getNodeName() + " => " + childNode.getTextContent() + "]");
							if ("parameters".equals(childNode.getNodeName())) {
								paramNodes = childNode.getChildNodes();
								paramMap = new HashMap<String,String>();
								for (int k = 0; k < paramNodes.getLength(); k++) {
									paramNode = paramNodes.item(k);
									if (paramNode.getNodeType() == Node.ELEMENT_NODE) {
										paramMap.put(paramNode.getNodeName(), paramNode.getTextContent());
									}
								}
							}
							else {
								gestureMap.put(childNode.getNodeName(), childNode.getTextContent());
							}
						}
					}
					if (!gestureMap.isEmpty() && gestureMap.containsKey("class")) {
						Gesture gesture = null;
						try {
							Class<?> gClass = Class.forName(gestureMap.get("class"));
							gesture = (Gesture)gClass.newInstance();
							gesture.setName(gestureMap.get("name"));
							gesture.setDescription(gestureMap.get("description"));
							gesture.setEnabled(Boolean.parseBoolean(gestureMap.get("isEnabled")));
						}
						catch (Exception ex) {
							ex.printStackTrace();
						}
						finally {
							if (gesture != null) {
								list.add(gesture);
							}
						}
					}
				}
			}
		}
		catch (ParserConfigurationException | SAXException | IOException e) {
			e.printStackTrace();
		}

		return list;
	}

	private static final Document read(String xmlFilePath)
			throws ParserConfigurationException, SAXException, IOException
	{
		DocumentBuilderFactory dbf;
		DocumentBuilder dbr;
		Document doc = null;

		InputStream in = Gestures.class.getResourceAsStream(xmlFilePath);

		if (in != null) {
			dbf = DocumentBuilderFactory.newInstance();
			dbf.setIgnoringComments(true);
			dbf.setNamespaceAware(false);
		    dbf.setValidating(false);

			dbr = dbf.newDocumentBuilder();
			doc = dbr.parse(in);
		}
		else
			throw new IOException("Unable to get resource: " + xmlFilePath);

		return doc;
	}

}


text: Daft Punk samples. For a thing. Don't ask.


text:
<?php

/**
 * This resource is used to get user information stored in google.
 *
 * @package  SXAPI.Resource.Google
 * @author   Dev Team <dev@startx.fr>
 * @see      defaultGoogleResource
 * @link     https://github.com/startxfr/sxapi/wiki/Resource
 */
class listaccountAnalyticsGoogleResource extends defaultGoogleResource implements IResource {

    protected $services = array();

    public function readAction() {
        $api = Api::getInstance();
        $api->logDebug(910, "Start executing '" . __FUNCTION__ . "' on '" . get_class($this) . "' resource", $this->getResourceTrace(__FUNCTION__, false), 3);
        try {
            $input = $api->getInput();
            $sessElPosition = $input->getElementPosition($this->getConfig('path'));
            $nextPath = $input->getElement($sessElPosition + 1);
            $accounts = $this->getService("Analytics")->management_accounts->listManagementAccounts();
            if ($nextPath !== null) {
                // recherche d'une clef en particulier
                $message = sprintf($this->getConfig('message_service_read', 'message service read'), 1, $api->getInput('user')->get('_id'));
                $api->logInfo(910, "'" . __FUNCTION__ . "' in '" . get_class($this) . "' return $nextPath=" . $user[$nextPath], $this->getResourceTrace(__FUNCTION__, false), 1);
                return array(true, $message, $accounts['items'][$nextPath]);
            } else {
                //affichage de toutes les clefs
                $message = sprintf($this->getConfig('message_service_read', 'message service read'), count($user), $api->getInput('user')->get('_id'));
                $api->logInfo(910, "'" . __FUNCTION__ . "' in '" . get_class($this) . "' return " . $message, $this->getResourceTrace(__FUNCTION__, false), 1);
                return array(true, $message, $accounts['items']);
            }
        } catch (Exception $exc) {
            $api->logError(910, "Error on '" . __FUNCTION__ . "' for '" . get_class($this) . "' return : " . $exc->getMessage(), $exc);
            return array(false, $exc->getCode(), $exc->getMessage());
        }
        return true;
    }

}

?>


text:
package org.apache.archiva.model;

/**
 *
 *         This object is only used for the XML backup / restore
 * features of Archiva.
 *         This object is not serialized to the Database.
 *
 *
 * @version $Revision$ $Date$
 */
@SuppressWarnings( "all" )
public class ArchivaAll
    implements java.io.Serializable
{

      //--------------------------/
     //- Class/Member Variables -/
    //--------------------------/

    /**
     * Field artifacts.
     */
    private java.util.List<ArchivaArtifactModel> artifacts;

    /**
     * Field repositoryMetadata.
     */
    private java.util.List<ArchivaRepositoryMetadata> repositoryMetadata;

    /**
     * Field modelEncoding.
     */
    private String modelEncoding = "UTF-8";

      //-----------/
     //- Methods -/
    //-----------/

    /**
     * Method addArtifact.
     *
     * @param archivaArtifactModel
     */
    public void addArtifact( ArchivaArtifactModel archivaArtifactModel )
    {
        getArtifacts().add( archivaArtifactModel );
    } //-- void addArtifact( ArchivaArtifactModel )

    /**
     * Method addRepositoryMetadata.
     *
     * @param archivaRepositoryMetadata
     */
    public void addRepositoryMetadata( ArchivaRepositoryMetadata archivaRepositoryMetadata )
    {
        getRepositoryMetadata().add( archivaRepositoryMetadata );
    } //-- void addRepositoryMetadata( ArchivaRepositoryMetadata )

    /**
     * Method getArtifacts.
     *
     * @return List
     */
    public java.util.List<ArchivaArtifactModel> getArtifacts()
    {
        if ( this.artifacts == null )
        {
            this.artifacts = new java.util.ArrayList<ArchivaArtifactModel>();
        }

        return this.artifacts;
    } //-- java.util.List<ArchivaArtifactModel> getArtifacts()

    /**
     * Get the modelEncoding field.
     *
     * @return String
     */
    public String getModelEncoding()
    {
        return this.modelEncoding;
    } //-- String getModelEncoding()

    /**
     * Method getRepositoryMetadata.
     *
     * @return List
     */
    public java.util.List<ArchivaRepositoryMetadata> getRepositoryMetadata()
    {
        if ( this.repositoryMetadata == null )
        {
            this.repositoryMetadata = new java.util.ArrayList<ArchivaRepositoryMetadata>();
        }

        return this.repositoryMetadata;
    } //-- java.util.List<ArchivaRepositoryMetadata> getRepositoryMetadata()

    /**
     * Method removeArtifact.
     *
     * @param archivaArtifactModel
     */
    public void removeArtifact( ArchivaArtifactModel archivaArtifactModel )
    {
        getArtifacts().remove( archivaArtifactModel );
    } //-- void removeArtifact( ArchivaArtifactModel )

    /**
     * Method removeRepositoryMetadata.
     *
     * @param archivaRepositoryMetadata
     */
    public void removeRepositoryMetadata( ArchivaRepositoryMetadata archivaRepositoryMetadata )
    {
        getRepositoryMetadata().remove( archivaRepositoryMetadata );
    } //-- void removeRepositoryMetadata( ArchivaRepositoryMetadata )

    /**
     * Set the artifacts field.
     *
     * @param artifacts
     */
    public void setArtifacts( java.util.List<ArchivaArtifactModel> artifacts )
    {
        this.artifacts = artifacts;
    } //-- void setArtifacts( java.util.List )

    /**
     * Set the modelEncoding field.
     *
     * @param modelEncoding
     */
    public void setModelEncoding( String modelEncoding )
    {
        this.modelEncoding = modelEncoding;
    } //-- void setModelEncoding( String )

    /**
     * Set the repositoryMetadata field.
     *
     * @param repositoryMetadata
     */
    public void setRepositoryMetadata( java.util.List<ArchivaRepositoryMetadata> repositoryMetadata )
    {
        this.repositoryMetadata = repositoryMetadata;
    } //-- void setRepositoryMetadata( java.util.List )

    private static final long serialVersionUID = 3259707008803111764L;

}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: John Abraham <john.abraham.in@gmail.com>
 */

#ifndef MODE_H
#define MODE_H

#include "common.h"

class Mode: public QWidget
{
public:
  virtual QWidget * getCentralWidget () = 0;
  virtual QString getTabName () = 0;
  virtual void setFocus (bool focus) = 0;
};
#endif // MODE_H


text:
import { Fixture, SubcaseBatchState, TestParams } from '../common/framework/fixture.js';
import {
  assert,
  range,
  TypedArrayBufferView,
  TypedArrayBufferViewConstructor,
  unreachable,
} from '../common/util/util.js';

import {
  EncodableTextureFormat,
  SizedTextureFormat,
  kTextureFormatInfo,
  kQueryTypeInfo,
  resolvePerAspectFormat,
} from './capability_info.js';
import { makeBufferWithContents } from './util/buffer.js';
import {
  checkElementsEqual,
  checkElementsBetween,
  checkElementsFloat16Between,
} from './util/check_contents.js';
import { CommandBufferMaker, EncoderType } from './util/command_buffer_maker.js';
import { DevicePool, DeviceProvider, UncanonicalizedDeviceDescriptor } from './util/device_pool.js';
import { align, roundDown } from './util/math.js';
import { makeTextureWithContents } from './util/texture.js';
import {
  getTextureCopyLayout,
  getTextureSubCopyLayout,
  LayoutOptions as TextureLayoutOptions,
} from './util/texture/layout.js';
import { PerTexelComponent, kTexelRepresentationInfo } from './util/texture/texel_data.js';
import { TexelView } from './util/texture/texel_view.js';

const devicePool = new DevicePool();

// MAINTENANCE_TODO: When DevicePool becomes able to provide multiple devices at once, use the
// usual one instead of a new one.
const mismatchedDevicePool = new DevicePool();

const kResourceStateValues = ['valid', 'invalid', 'destroyed'] as const;
export type ResourceState = typeof kResourceStateValues[number];
export const kResourceStates: readonly ResourceState[] = kResourceStateValues;

/** Various "convenient" shorthands for GPUDeviceDescriptors for selectDevice functions. */
type DeviceSelectionDescriptor =
  | UncanonicalizedDeviceDescriptor
  | GPUFeatureName
  | undefined
  | Array<GPUFeatureName | undefined>;

export function initUncanonicalizedDeviceDescriptor(
  descriptor: DeviceSelectionDescriptor
): UncanonicalizedDeviceDescriptor | undefined {
  if (typeof descriptor === 'string') {
    return { requiredFeatures: [descriptor] };
  } else if (descriptor instanceof Array) {
    return {
      requiredFeatures: descriptor.filter(f => f !== undefined) as GPUFeatureName[],
    };
  } else {
    return descriptor;
  }
}

export class GPUTestSubcaseBatchState extends SubcaseBatchState {
  /** Provider for default device. */
  private provider: Promise<DeviceProvider> | undefined;
  /** Provider for mismatched device. */
  private mismatchedProvider: Promise<DeviceProvider> | undefined;

  async postInit(): Promise<void> {
    // Skip all subcases if there's no device.
    await this.acquireProvider();
  }

  async finalize(): Promise<void> {
    await super.finalize();

    // Ensure devicePool.release is called for both providers even if one rejects.
    await Promise.all([
      this.provider?.then(x => devicePool.release(x)),
      this.mismatchedProvider?.then(x => devicePool.release(x)),
    ]);
  }

  /** @internal MAINTENANCE_TODO: Make this not visible to test code? */
  acquireProvider(): Promise<DeviceProvider> {
    if (this.provider === undefined) {
      this.selectDeviceOrSkipTestCase(undefined);
    }
    assert(this.provider !== undefined);
    return this.provider;
  }

  /**
   * Some tests or cases need particular feature flags or limits to be enabled.
   * Call this function with a descriptor or feature name (or `undefined`) to select a
   * GPUDevice with matching capabilities. If this isn't called, a default device is provided.
   *
   * If the request isn't supported, throws a SkipTestCase exception to skip the entire test case.
   */
  selectDeviceOrSkipTestCase(descriptor: DeviceSelectionDescriptor): void {
    assert(this.provider === undefined, "Can't selectDeviceOrSkipTestCase() multiple times");
    this.provider = devicePool.acquire(initUncanonicalizedDeviceDescriptor(descriptor));
    // Suppress uncaught promise rejection (we'll catch it later).
    this.provider.catch(() => {});
  }

  /**
   * Convenience function for {@link selectDeviceOrSkipTestCase}.
   * Select a device with the features required by these texture format(s).
   * If the device creation fails, then skip the test case.
   */
  selectDeviceForTextureFormatOrSkipTestCase(
    formats: GPUTextureFormat | undefined | (GPUTextureFormat | undefined)[]
  ): void {
    if (!Array.isArray(formats)) {
      formats = [formats];
    }
    const features = new Set<GPUFeatureName | undefined>();
    for (const format of formats) {
      if (format !== undefined) {
        features.add(kTextureFormatInfo[format].feature);
      }
    }

    this.selectDeviceOrSkipTestCase(Array.from(features));
  }

  /**
   * Convenience function for {@link selectDeviceOrSkipTestCase}.
   * Select a device with the features required by these query type(s).
   * If the device creation fails, then skip the test case.
   */
  selectDeviceForQueryTypeOrSkipTestCase(types: GPUQueryType | GPUQueryType[]): void {
    if (!Array.isArray(types)) {
      types = [types];
    }
    const features = types.map(t => kQueryTypeInfo[t].feature);
    this.selectDeviceOrSkipTestCase(features);
  }

  /** @internal MAINTENANCE_TODO: Make this not visible to test code? */
  acquireMismatchedProvider(): Promise<DeviceProvider> | undefined {
    return this.mismatchedProvider;
  }

  /**
   * Some tests need a second device which is different from the first.
   * This requests a second device so it will be available during the test. If it is not called,
   * no second device will be available.
   *
   * If the request isn't supported, throws a SkipTestCase exception to skip the entire test case.
   */
  selectMismatchedDeviceOrSkipTestCase(descriptor: DeviceSelectionDescriptor): void {
    assert(
      this.mismatchedProvider === undefined,
      "Can't selectMismatchedDeviceOrSkipTestCase() multiple times"
    );

    this.mismatchedProvider = mismatchedDevicePool.acquire(
      initUncanonicalizedDeviceDescriptor(descriptor)
    );
    // Suppress uncaught promise rejection (we'll catch it later).
    this.mismatchedProvider.catch(() => {});
  }
}

/**
 * Base fixture for WebGPU tests.
 */
export class GPUTest extends Fixture<GPUTestSubcaseBatchState> {
  public static MakeSharedState(params: TestParams): GPUTestSubcaseBatchState {
    return new GPUTestSubcaseBatchState(params);
  }

  // Should never be undefined in a test. If it is, init() must not have run/finished.
  private provider: DeviceProvider | undefined;
  private mismatchedProvider: DeviceProvider | undefined;

  async init() {
    await super.init();

    this.provider = await this.sharedState.acquireProvider();
    this.mismatchedProvider = await this.sharedState.acquireMismatchedProvider();
  }

  /**
   * GPUDevice for the test to use.
   */
  get device(): GPUDevice {
    assert(this.provider !== undefined, 'internal error: GPUDevice missing?');
    return this.provider.device;
  }

  /**
   * GPUDevice for tests requiring a second device different from the default one,
   * e.g. for creating objects for by device_mismatch validation tests.
   */
  get mismatchedDevice(): GPUDevice {
    assert(
      this.mismatchedProvider !== undefined,
      'selectMismatchedDeviceOrSkipTestCase was not called in beforeAllSubcases'
    );
    return this.mismatchedProvider.device;
  }

  /** GPUQueue for the test to use. (Same as `t.device.queue`.) */
  get queue(): GPUQueue {
    return this.device.queue;
  }

  /** Snapshot a GPUBuffer's contents, returning a new GPUBuffer with the `MAP_READ` usage. */
  private createCopyForMapRead(src: GPUBuffer, srcOffset: number, size: number): GPUBuffer {
    assert(srcOffset % 4 === 0);
    assert(size % 4 === 0);

    const dst = this.device.createBuffer({
      size,
      usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
    });
    this.trackForCleanup(dst);

    const c = this.device.createCommandEncoder();
    c.copyBufferToBuffer(src, srcOffset, dst, 0, size);
    this.queue.submit([c.finish()]);

    return dst;
  }

  /**
   * Offset and size passed to createCopyForMapRead must be divisible by 4. For that
   * we might need to copy more bytes from the buffer than we want to map.
   * begin and end values represent the part of the copied buffer that stores the contents
   * we initially wanted to map.
   * The copy will not cause an OOB error because the buffer size must be 4-aligned.
   */
  private createAlignedCopyForMapRead(
    src: GPUBuffer,
    size: number,
    offset: number
  ): { mappable: GPUBuffer; subarrayByteStart: number } {
    const alignedOffset = roundDown(offset, 4);
    const subarrayByteStart = offset - alignedOffset;
    const alignedSize = align(size + subarrayByteStart, 4);
    const mappable = this.createCopyForMapRead(src, alignedOffset, alignedSize);
    return { mappable, subarrayByteStart };
  }

  /**
   * Snapshot the current contents of a range of a GPUBuffer, and return them as a TypedArray.
   * Also provides a cleanup() function to unmap and destroy the staging buffer.
   */
  async readGPUBufferRangeTyped<T extends TypedArrayBufferView>(
    src: GPUBuffer,
    {
      srcByteOffset = 0,
      method = 'copy',
      type,
      typedLength,
    }: {
      srcByteOffset?: number;
      method?: 'copy' | 'map';
      type: TypedArrayBufferViewConstructor<T>;
      typedLength: number;
    }
  ): Promise<{ data: T; cleanup(): void }> {
    assert(
      srcByteOffset % type.BYTES_PER_ELEMENT === 0,
      'srcByteOffset must be a multiple of BYTES_PER_ELEMENT'
    );

    const byteLength = typedLength * type.BYTES_PER_ELEMENT;
    let mappable: GPUBuffer;
    let mapOffset: number | undefined, mapSize: number | undefined, subarrayByteStart: number;
    if (method === 'copy') {
      ({ mappable, subarrayByteStart } = this.createAlignedCopyForMapRead(
        src,
        byteLength,
        srcByteOffset
      ));
    } else if (method === 'map') {
      mappable = src;
      mapOffset = roundDown(srcByteOffset, 8);
      mapSize = align(byteLength, 4);
      subarrayByteStart = srcByteOffset - mapOffset;
    } else {
      unreachable();
    }

    assert(subarrayByteStart % type.BYTES_PER_ELEMENT === 0);
    const subarrayStart = subarrayByteStart / type.BYTES_PER_ELEMENT;

    // 2. Map the staging buffer, and create the TypedArray from it.
    await mappable.mapAsync(GPUMapMode.READ, mapOffset, mapSize);
    const mapped = new type(mappable.getMappedRange(mapOffset, mapSize));
    const data = mapped.subarray(subarrayStart, typedLength) as T;

    return {
      data,
      cleanup() {
        mappable.unmap();
        mappable.destroy();
      },
    };
  }

  /**
   * Expect a GPUBuffer's contents to pass the provided check.
   *
   * A library of checks can be found in {@link webgpu/util/check_contents}.
   */
  expectGPUBufferValuesPassCheck<T extends TypedArrayBufferView>(
    src: GPUBuffer,
    check: (actual: T) => Error | undefined,
    {
      srcByteOffset = 0,
      type,
      typedLength,
      method = 'copy',
      mode = 'fail',
    }: {
      srcByteOffset?: number;
      type: TypedArrayBufferViewConstructor<T>;
      typedLength: number;
      method?: 'copy' | 'map';
      mode?: 'fail' | 'warn';
    }
  ) {
    const readbackPromise = this.readGPUBufferRangeTyped(src, {
      srcByteOffset,
      type,
      typedLength,
      method,
    });
    this.eventualAsyncExpectation(async niceStack => {
      const readback = await readbackPromise;
      this.expectOK(check(readback.data), { mode, niceStack });
      readback.cleanup();
    });
  }

  /**
   * Expect a GPUBuffer's contents to equal the values in the provided TypedArray.
   */
  expectGPUBufferValuesEqual(
    src: GPUBuffer,
    expected: TypedArrayBufferView,
    srcByteOffset: number = 0,
    { method = 'copy', mode = 'fail' }: { method?: 'copy' | 'map'; mode?: 'fail' | 'warn' } = {}
  ): void {
    this.expectGPUBufferValuesPassCheck(src, a => checkElementsEqual(a, expected), {
      srcByteOffset,
      type: expected.constructor as TypedArrayBufferViewConstructor,
      typedLength: expected.length,
      method,
      mode,
    });
  }

  /**
   * Expect a buffer to consist exclusively of rows of some repeated expected value. The size of
   * `expectedValue` must be 1, 2, or any multiple of 4 bytes. Rows in the buffer are expected to be
   * zero-padded out to `bytesPerRow`. `minBytesPerRow` is the number of bytes per row that contain
   * actual (non-padding) data and must be an exact multiple of the byte-length of `expectedValue`.
   */
  expectGPUBufferRepeatsSingleValue(
    buffer: GPUBuffer,
    {
      expectedValue,
      numRows,
      minBytesPerRow,
      bytesPerRow,
    }: {
      expectedValue: ArrayBuffer;
      numRows: number;
      minBytesPerRow: number;
      bytesPerRow: number;
    }
  ) {
    const valueSize = expectedValue.byteLength;
    assert(valueSize === 1 || valueSize === 2 || valueSize % 4 === 0);
    assert(minBytesPerRow % valueSize === 0);
    assert(bytesPerRow % 4 === 0);

    // If the buffer is small enough, just generate the full expected buffer contents and check
    // against them on the CPU.
    const kMaxBufferSizeToCheckOnCpu = 256 * 1024;
    const bufferSize = bytesPerRow * (numRows - 1) + minBytesPerRow;
    if (bufferSize <= kMaxBufferSizeToCheckOnCpu) {
      const valueBytes = Array.from(new Uint8Array(expectedValue));
      const rowValues = new Array(minBytesPerRow / valueSize).fill(valueBytes);
      const rowBytes = new Uint8Array([].concat(...rowValues));
      const expectedContents = new Uint8Array(bufferSize);
      range(numRows, row => expectedContents.set(rowBytes, row * bytesPerRow));
      this.expectGPUBufferValuesEqual(buffer, expectedContents);
      return;
    }

    // Copy into a buffer suitable for STORAGE usage.
    const storageBuffer = this.device.createBuffer({
      size: bufferSize,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
    });
    this.trackForCleanup(storageBuffer);

    // This buffer conveys the data we expect to see for a single value read. Since we read 32 bits at
    // a time, for values smaller than 32 bits we pad this expectation with repeated value data, or
    // with zeroes if the width of a row in the buffer is less than 4 bytes. For value sizes larger
    // than 32 bits, we assume they're a multiple of 32 bits and expect to read exact matches of
    // `expectedValue` as-is.
    const expectedDataSize = Math.max(4, valueSize);
    const expectedDataBuffer = this.device.createBuffer({
      size: expectedDataSize,
      usage: GPUBufferUsage.STORAGE,
      mappedAtCreation: true,
    });
    this.trackForCleanup(expectedDataBuffer);
    const expectedData = new Uint32Array(expectedDataBuffer.getMappedRange());
    if (valueSize === 1) {
      const value = new Uint8Array(expectedValue)[0];
      const values = new Array(Math.min(4, minBytesPerRow)).fill(value);
      const padding = new Array(Math.max(0, 4 - values.length)).fill(0);
      const expectedBytes = new Uint8Array(expectedData.buffer);
      expectedBytes.set([...values, ...padding]);
    } else if (valueSize === 2) {
      const value = new Uint16Array(expectedValue)[0];
      const expectedWords = new Uint16Array(expectedData.buffer);
      expectedWords.set([value, minBytesPerRow > 2 ? value : 0]);
    } else {
      expectedData.set(new Uint32Array(expectedValue));
    }
    expectedDataBuffer.unmap();

    // The output buffer has one 32-bit entry per buffer row. An entry's value will be 1 if every
    // read from the corresponding row matches the expected data derived above, or 0 otherwise.
    const resultBuffer = this.device.createBuffer({
      size: numRows * 4,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
    });
    this.trackForCleanup(resultBuffer);

    const readsPerRow = Math.ceil(minBytesPerRow / expectedDataSize);
    const reducer = `
    struct Buffer { data: array<u32>, };
    @group(0) @binding(0) var<storage, read> expected: Buffer;
    @group(0) @binding(1) var<storage, read> in: Buffer;
    @group(0) @binding(2) var<storage, read_write> out: Buffer;
    @compute @workgroup_size(1) fn reduce(
        @builtin(global_invocation_id) id: vec3<u32>) {
      let rowBaseIndex = id.x * ${bytesPerRow / 4}u;
      let readSize = ${expectedDataSize / 4}u;
      out.data[id.x] = 1u;
      for (var i: u32 = 0u; i < ${readsPerRow}u; i = i + 1u) {
        let elementBaseIndex = rowBaseIndex + i * readSize;
        for (var j: u32 = 0u; j < readSize; j = j + 1u) {
          if (in.data[elementBaseIndex + j] != expected.data[j]) {
            out.data[id.x] = 0u;
            return;
          }
        }
      }
    }
    `;

    const pipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: this.device.createShaderModule({ code: reducer }),
        entryPoint: 'reduce',
      },
    });

    const bindGroup = this.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: [
        { binding: 0, resource: { buffer: expectedDataBuffer } },
        { binding: 1, resource: { buffer: storageBuffer } },
        { binding: 2, resource: { buffer: resultBuffer } },
      ],
    });

    const commandEncoder = this.device.createCommandEncoder();
    commandEncoder.copyBufferToBuffer(buffer, 0, storageBuffer, 0, bufferSize);
    const pass = commandEncoder.beginComputePass();
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, bindGroup);
    pass.dispatchWorkgroups(numRows);
    pass.end();
    this.device.queue.submit([commandEncoder.finish()]);

    const expectedResults = new Array(numRows).fill(1);
    this.expectGPUBufferValuesEqual(resultBuffer, new Uint32Array(expectedResults));
  }

  // MAINTENANCE_TODO: add an expectContents for textures, which logs data: uris on failure

  /**
   * Expect a whole GPUTexture to have the single provided color.
   */
  expectSingleColor(
    src: GPUTexture,
    format: GPUTextureFormat,
    {
      size,
      exp,
      dimension = '2d',
      slice = 0,
      layout,
    }: {
      size: [number, number, number];
      exp: PerTexelComponent<number>;
      dimension?: GPUTextureDimension;
      slice?: number;
      layout?: TextureLayoutOptions;
    }
  ): void {
    format = resolvePerAspectFormat(format, layout?.aspect);
    const { byteLength, minBytesPerRow, bytesPerRow, rowsPerImage, mipSize } = getTextureCopyLayout(
      format,
      dimension,
      size,
      layout
    );

    const rep = kTexelRepresentationInfo[format as EncodableTextureFormat];
    const expectedTexelData = rep.pack(rep.encode(exp));

    const buffer = this.device.createBuffer({
      size: byteLength,
      usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
    });
    this.trackForCleanup(buffer);

    const commandEncoder = this.device.createCommandEncoder();
    commandEncoder.copyTextureToBuffer(
      {
        texture: src,
        mipLevel: layout?.mipLevel,
        origin: { x: 0, y: 0, z: slice },
        aspect: layout?.aspect,
      },
      { buffer, bytesPerRow, rowsPerImage },
      mipSize
    );
    this.queue.submit([commandEncoder.finish()]);

    this.expectGPUBufferRepeatsSingleValue(buffer, {
      expectedValue: expectedTexelData,
      numRows: rowsPerImage,
      minBytesPerRow,
      bytesPerRow,
    });
  }

  /** Return a GPUBuffer that data are going to be written into. */
  private readSinglePixelFrom2DTexture(
    src: GPUTexture,
    format: SizedTextureFormat,
    { x, y }: { x: number; y: number },
    { slice = 0, layout }: { slice?: number; layout?: TextureLayoutOptions }
  ): GPUBuffer {
    const { byteLength, bytesPerRow, rowsPerImage } = getTextureSubCopyLayout(
      format,
      [1, 1],
      layout
    );
    const buffer = this.device.createBuffer({
      size: byteLength,
      usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
    });
    this.trackForCleanup(buffer);

    const commandEncoder = this.device.createCommandEncoder();
    commandEncoder.copyTextureToBuffer(
      { texture: src, mipLevel: layout?.mipLevel, origin: { x, y, z: slice } },
      { buffer, bytesPerRow, rowsPerImage },
      [1, 1]
    );
    this.queue.submit([commandEncoder.finish()]);

    return buffer;
  }

  /**
   * Expect a single pixel of a 2D texture to have a particular byte representation.
   *
   * MAINTENANCE_TODO: Add check for values of depth/stencil, probably through sampling of shader
   * MAINTENANCE_TODO: Can refactor this and expectSingleColor to use a similar base expect
   */
  expectSinglePixelIn2DTexture(
    src: GPUTexture,
    format: SizedTextureFormat,
    { x, y }: { x: number; y: number },
    {
      exp,
      slice = 0,
      layout,
      generateWarningOnly = false,
    }: {
      exp: Uint8Array;
      slice?: number;
      layout?: TextureLayoutOptions;
      generateWarningOnly?: boolean;
    }
  ): void {
    const buffer = this.readSinglePixelFrom2DTexture(src, format, { x, y }, { slice, layout });
    this.expectGPUBufferValuesEqual(buffer, exp, 0, {
      mode: generateWarningOnly ? 'warn' : 'fail',
    });
  }

  /**
   * Take a single pixel of a 2D texture, interpret it using a TypedArray of the `expected` type,
   * and expect each value in that array to be between the corresponding "expected" values
   * (either `a[i] <= actual[i] <= b[i]` or `a[i] >= actual[i] => b[i]`).
   */
  expectSinglePixelBetweenTwoValuesIn2DTexture(
    src: GPUTexture,
    format: SizedTextureFormat,
    { x, y }: { x: number; y: number },
    {
      exp,
      slice = 0,
      layout,
      generateWarningOnly = false,
      checkElementsBetweenFn = (act, [a, b]) => checkElementsBetween(act, [i => a[i], i => b[i]]),
    }: {
      exp: [TypedArrayBufferView, TypedArrayBufferView];
      slice?: number;
      layout?: TextureLayoutOptions;
      generateWarningOnly?: boolean;
      checkElementsBetweenFn?: (
        actual: TypedArrayBufferView,
        expected: readonly [TypedArrayBufferView, TypedArrayBufferView]
      ) => Error | undefined;
    }
  ): void {
    assert(exp[0].constructor === exp[1].constructor);
    const constructor = exp[0].constructor as TypedArrayBufferViewConstructor;
    assert(exp[0].length === exp[1].length);
    const typedLength = exp[0].length;

    const buffer = this.readSinglePixelFrom2DTexture(src, format, { x, y }, { slice, layout });
    this.expectGPUBufferValuesPassCheck(buffer, a => checkElementsBetweenFn(a, exp), {
      type: constructor,
      typedLength,
      mode: generateWarningOnly ? 'warn' : 'fail',
    });
  }

  /**
   * Equivalent to {@link expectSinglePixelBetweenTwoValuesIn2DTexture} but uses a special check func
   * to interpret incoming values as float16
   */
  expectSinglePixelBetweenTwoValuesFloat16In2DTexture(
    src: GPUTexture,
    format: SizedTextureFormat,
    { x, y }: { x: number; y: number },
    {
      exp,
      slice = 0,
      layout,
      generateWarningOnly = false,
    }: {
      exp: [Uint16Array, Uint16Array];
      slice?: number;
      layout?: TextureLayoutOptions;
      generateWarningOnly?: boolean;
    }
  ): void {
    this.expectSinglePixelBetweenTwoValuesIn2DTexture(
      src,
      format,
      { x, y },
      {
        exp,
        slice,
        layout,
        generateWarningOnly,
        checkElementsBetweenFn: checkElementsFloat16Between,
      }
    );
  }

  /**
   * Expect the specified WebGPU error to be generated when running the provided function.
   */
  expectGPUError<R>(filter: GPUErrorFilter, fn: () => R, shouldError: boolean = true): R {
    // If no error is expected, we let the scope surrounding the test catch it.
    if (!shouldError) {
      return fn();
    }

    this.device.pushErrorScope(filter);
    const returnValue = fn();
    const promise = this.device.popErrorScope();

    this.eventualAsyncExpectation(async niceStack => {
      const error = await promise;

      let failed = false;
      switch (filter) {
        case 'out-of-memory':
          failed = !(error instanceof GPUOutOfMemoryError);
          break;
        case 'validation':
          failed = !(error instanceof GPUValidationError);
          break;
      }

      if (failed) {
        niceStack.message = `Expected ${filter} error`;
        this.rec.expectationFailed(niceStack);
      } else {
        niceStack.message = `Captured ${filter} error`;
        if (error instanceof GPUValidationError) {
          niceStack.message += ` - ${error.message}`;
        }
        this.rec.debug(niceStack);
      }
    });

    return returnValue;
  }

  /**
   * Expect a validation error inside the callback.
   *
   * Tests should always do just one WebGPU call in the callback, to make sure that's what's tested.
   */
  expectValidationError(fn: () => void, shouldError: boolean = true): void {
    // If no error is expected, we let the scope surrounding the test catch it.
    if (shouldError) {
      this.device.pushErrorScope('validation');
    }

    // Note: A return value is not allowed for the callback function. This is to avoid confusion
    // about what the actual behavior would be; either of the following could be reasonable:
    //   - Make expectValidationError async, and have it await on fn(). This causes an async split
    //     between pushErrorScope and popErrorScope, so if the caller doesn't `await` on
    //     expectValidationError (either accidentally or because it doesn't care to do so), then
    //     other test code will be (nondeterministically) caught by the error scope.
    //   - Make expectValidationError NOT await fn(), but just execute its first block (until the
    //     first await) and return the return value (a Promise). This would be confusing because it
    //     would look like the error scope includes the whole async function, but doesn't.
    // If we do decide we need to return a value, we should use the latter semantic.
    const returnValue = fn() as unknown;
    assert(
      returnValue === undefined,
      'expectValidationError callback should not return a value (or be async)'
    );

    if (shouldError) {
      const promise = this.device.popErrorScope();

      this.eventualAsyncExpectation(async niceStack => {
        const gpuValidationError = await promise;
        if (!gpuValidationError) {
          niceStack.message = 'Validation succeeded unexpectedly.';
          this.rec.validationFailed(niceStack);
        } else if (gpuValidationError instanceof GPUValidationError) {
          niceStack.message = `Validation failed, as expected - ${gpuValidationError.message}`;
          this.rec.debug(niceStack);
        }
      });
    }
  }

  /**
   * Expects that the device should be lost for a particular reason at the teardown of the test.
   */
  expectDeviceLost(reason: GPUDeviceLostReason): void {
    assert(this.provider !== undefined, 'internal error: GPUDevice missing?');
    this.provider.expectDeviceLost(reason);
  }

  /**
   * Create a GPUBuffer with the specified contents and usage.
   *
   * MAINTENANCE_TODO: Several call sites would be simplified if this took ArrayBuffer as well.
   */
  makeBufferWithContents(dataArray: TypedArrayBufferView, usage: GPUBufferUsageFlags): GPUBuffer {
    return this.trackForCleanup(makeBufferWithContents(this.device, dataArray, usage));
  }

  /**
   * Creates a texture with the contents of a TexelView.
   */
  makeTextureWithContents(
    texelView: TexelView,
    desc: Omit<GPUTextureDescriptor, 'format'>
  ): GPUTexture {
    return this.trackForCleanup(makeTextureWithContents(this.device, texelView, desc));
  }

  /**
   * Create a GPUTexture with multiple mip levels, each having the specified contents.
   */
  createTexture2DWithMipmaps(mipmapDataArray: TypedArrayBufferView[]): GPUTexture {
    const format = 'rgba8unorm';
    const mipLevelCount = mipmapDataArray.length;
    const textureSizeMipmap0 = 1 << (mipLevelCount - 1);
    const texture = this.device.createTexture({
      mipLevelCount,
      size: { width: textureSizeMipmap0, height: textureSizeMipmap0, depthOrArrayLayers: 1 },
      format,
      usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
    });
    this.trackForCleanup(texture);

    const textureEncoder = this.device.createCommandEncoder();
    for (let i = 0; i < mipLevelCount; i++) {
      const { byteLength, bytesPerRow, rowsPerImage, mipSize } = getTextureCopyLayout(
        format,
        '2d',
        [textureSizeMipmap0, textureSizeMipmap0, 1],
        { mipLevel: i }
      );

      const data: Uint8Array = new Uint8Array(byteLength);
      const mipLevelData = mipmapDataArray[i];
      assert(rowsPerImage === mipSize[0]); // format is rgba8unorm and block size should be 1
      for (let r = 0; r < rowsPerImage; r++) {
        const o = r * bytesPerRow;
        for (let c = o, end = o + mipSize[1] * 4; c < end; c += 4) {
          data[c] = mipLevelData[0];
          data[c + 1] = mipLevelData[1];
          data[c + 2] = mipLevelData[2];
          data[c + 3] = mipLevelData[3];
        }
      }
      const buffer = this.makeBufferWithContents(
        data,
        GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST
      );

      textureEncoder.copyBufferToTexture(
        { buffer, bytesPerRow, rowsPerImage },
        { texture, mipLevel: i, origin: [0, 0, 0] },
        mipSize
      );
    }
    this.device.queue.submit([textureEncoder.finish()]);

    return texture;
  }

  /**
   * Returns a GPUCommandEncoder, GPUComputePassEncoder, GPURenderPassEncoder, or
   * GPURenderBundleEncoder, and a `finish` method returning a GPUCommandBuffer.
   * Allows testing methods which have the same signature across multiple encoder interfaces.
   *
   * @example
   * ```
   * g.test('popDebugGroup')
   *   .params(u => u.combine('encoderType', kEncoderTypes))
   *   .fn(t => {
   *     const { encoder, finish } = t.createEncoder(t.params.encoderType);
   *     encoder.popDebugGroup();
   *   });
   *
   * g.test('writeTimestamp')
   *   .params(u => u.combine('encoderType', ['non-pass', 'compute pass', 'render pass'] as const)
   *   .fn(t => {
   *     const { encoder, finish } = t.createEncoder(t.params.encoderType);
   *     // Encoder type is inferred, so `writeTimestamp` can be used even though it doesn't exist
   *     // on GPURenderBundleEncoder.
   *     encoder.writeTimestamp(args);
   *   });
   * ```
   */
  createEncoder<T extends EncoderType>(
    encoderType: T,
    {
      attachmentInfo,
      occlusionQuerySet,
    }: {
      attachmentInfo?: GPURenderBundleEncoderDescriptor;
      occlusionQuerySet?: GPUQuerySet;
    } = {}
  ): CommandBufferMaker<T> {
    const fullAttachmentInfo = {
      // Defaults if not overridden:
      colorFormats: ['rgba8unorm'],
      sampleCount: 1,
      // Passed values take precedent.
      ...attachmentInfo,
    } as const;

    switch (encoderType) {
      case 'non-pass': {
        const encoder = this.device.createCommandEncoder();

        return new CommandBufferMaker(this, encoder, () => {
          return encoder.finish();
        });
      }
      case 'render bundle': {
        const device = this.device;
        const rbEncoder = device.createRenderBundleEncoder(fullAttachmentInfo);
        const pass = this.createEncoder('render pass', { attachmentInfo });

        return new CommandBufferMaker(this, rbEncoder, () => {
          pass.encoder.executeBundles([rbEncoder.finish()]);
          return pass.finish();
        });
      }
      case 'compute pass': {
        const commandEncoder = this.device.createCommandEncoder();
        const encoder = commandEncoder.beginComputePass();

        return new CommandBufferMaker(this, encoder, () => {
          encoder.end();
          return commandEncoder.finish();
        });
      }
      case 'render pass': {
        const makeAttachmentView = (format: GPUTextureFormat) =>
          this.trackForCleanup(
            this.device.createTexture({
              size: [16, 16, 1],
              format,
              usage: GPUTextureUsage.RENDER_ATTACHMENT,
              sampleCount: fullAttachmentInfo.sampleCount,
            })
          ).createView();

        let depthStencilAttachment: GPURenderPassDepthStencilAttachment | undefined = undefined;
        if (fullAttachmentInfo.depthStencilFormat !== undefined) {
          depthStencilAttachment = {
            view: makeAttachmentView(fullAttachmentInfo.depthStencilFormat),
            depthReadOnly: fullAttachmentInfo.depthReadOnly,
            stencilReadOnly: fullAttachmentInfo.stencilReadOnly,
          };
          if (
            kTextureFormatInfo[fullAttachmentInfo.depthStencilFormat].depth &&
            !fullAttachmentInfo.depthReadOnly
          ) {
            depthStencilAttachment.depthClearValue = 0;
            depthStencilAttachment.depthLoadOp = 'clear';
            depthStencilAttachment.depthStoreOp = 'discard';
          }
          if (
            kTextureFormatInfo[fullAttachmentInfo.depthStencilFormat].stencil &&
            !fullAttachmentInfo.stencilReadOnly
          ) {
            depthStencilAttachment.stencilClearValue = 1;
            depthStencilAttachment.stencilLoadOp = 'clear';
            depthStencilAttachment.stencilStoreOp = 'discard';
          }
        }
        const passDesc: GPURenderPassDescriptor = {
          colorAttachments: Array.from(fullAttachmentInfo.colorFormats, format =>
            format
              ? {
                  view: makeAttachmentView(format),
                  clearValue: [0, 0, 0, 0],
                  loadOp: 'clear',
                  storeOp: 'store',
                }
              : null
          ),
          depthStencilAttachment,
          occlusionQuerySet,
        };

        const commandEncoder = this.device.createCommandEncoder();
        const encoder = commandEncoder.beginRenderPass(passDesc);
        return new CommandBufferMaker(this, encoder, () => {
          encoder.end();
          return commandEncoder.finish();
        });
      }
    }
    unreachable();
  }
}


text:
SYNONYM

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

#### Published in
Beitr. Kenntn. Pilze Mitteleur. 7: 77 (1991)

#### Original name
Boletus ferrugineus Schaeff., 1762

### Remarks
null


text:
using System;

namespace Shuttle.EMailSender.Messages
{
    public class EMailSentEvent
    {
        public Guid EMailId { get; set; }
    }
}


text:
package com.fjoglar.etsitnoticias.data.repository.datasource.local;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;

import com.fjoglar.etsitnoticias.BuildConfig;

/**
 * Define table and columns names for the database.
 */
public class NewsContract {

    public static final String CONTENT_AUTHORITY = BuildConfig.APPLICATION_ID;
    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

    public static final String PATH_NEWS = "news";
    public static final String PATH_BOOKMARKS = "bookmarks";

    // Class that defines the table contents.
    public static final class NewsEntry implements BaseColumns {

        public static final Uri CONTENT_URI =
                BASE_CONTENT_URI.buildUpon().appendPath(PATH_NEWS).build();

        public static final String CONTENT_TYPE =
                ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY
                        + "/" + PATH_NEWS;
        public static final String CONTENT_ITEM_TYPE =
                ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY
                        + "/" + PATH_NEWS;

        // Table name.
        public static final String TABLE_NAME = "news";

        public static final String COLUMN_TITLE = "title";
        public static final String COLUMN_DESCRIPTION = "description";
        public static final String COLUMN_LINK = "link";
        public static final String COLUMN_CATEGORY = "category";
        // Publication date in milliseconds.
        public static final String COLUMN_PUB_DATE = "pub_date";
        public static final String COLUMN_ATTACHMENTS = "attachments";
        public static final String COLUMN_IS_BOOKMARKED = "is_bookmarked";

        public static Uri buildNewsWithDate(long date) {
            return ContentUris.withAppendedId(CONTENT_URI, date);
        }
    }

    // Class that defines the table contents.
    public static final class BookmarksEntry implements BaseColumns {

        public static final Uri CONTENT_URI =
                BASE_CONTENT_URI.buildUpon().appendPath(PATH_BOOKMARKS).build();

        public static final String CONTENT_TYPE =
                ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY
                        + "/" + PATH_BOOKMARKS;
        public static final String CONTENT_ITEM_TYPE =
                ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY
                        + "/" + PATH_BOOKMARKS;

        // Table name.
        public static final String TABLE_NAME = "bookmarks";

        public static final String COLUMN_TITLE = "title";
        public static final String COLUMN_DESCRIPTION = "description";
        public static final String COLUMN_LINK = "link";
        public static final String COLUMN_CATEGORY = "category";
        // Publication date in milliseconds.
        public static final String COLUMN_PUB_DATE = "pub_date";
        public static final String COLUMN_ATTACHMENTS = "attachments";
        public static final String COLUMN_IS_BOOKMARKED = "is_bookmarked";

        public static Uri buildBookmarksWithDate(long date) {
            return ContentUris.withAppendedId(CONTENT_URI, date);
        }
    }
}


text:
package org.uberfire.ext.widgets.core.client.wizards;

/**
 * An event representing the selection of a page within a Wizard
 */
public class WizardPageSelectedEvent {

    private final WizardPage selectedPage;

    public WizardPageSelectedEvent( final WizardPage selectedPage ) {
        this.selectedPage = selectedPage;
    }

    public WizardPage getSelectedPage() {
        return selectedPage;
    }

}


text:
<?php

namespace content;

class Content extends \common\base\BaseModule
{
    public $controllerNamespace = 'content\controllers';

    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }
}


text:
@charset "UTF-8";

/* import print base styles | Basisformatierung für Drucklayout einbinden */
@import url(../core/print_base.css);

/* #col1 - x
** #col2 - x
** #col3 - 0
*/
@media print
{
  #col1, #col1_content {float:none; width: 100%; margin: 0; padding: 0; border: 0}
  #col1_content {page-break-after:always}

  #col2, #col2_content {float:none; width: 100%; margin: 0; padding: 0; border: 0}
  #col2_content {page-break-after:always}

  #col3 {display:none}

  /* Optional Column Labels | Optionale Spaltenauszeichnung
  #col1_content:before {content:" [ left | middle | right column ]"}
  #col2_content:before {content:" [ left | middle | right column ]"}
  */
}


text:
extern "C" {
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <Allocates.h>
#include <core/Store.h>
#include <dataTypes/Value.h>
#include <structures/WasmGlobal.h>
#include <instance/GlobalInst.h>
}
#undef _Bool

SKYPAT_F(allocate_global, valid)
{
    // Prepare
    Store store = new_Store();

    WasmGlobal* global = (WasmGlobal*) malloc(sizeof(WasmGlobal));
    global->mut = 1;
    global->valType = Value_i32;
    global->init.parent.entryType = Entry_Value;
    global->init.type = Value_i32;
    global->init.value.i32 = 38;

    // Test
    uint32_t address = allocate_Global(global, store);
    GlobalInst* globalInst = vector_at(GlobalInst*, store->globals, address);
    EXPECT_EQ(globalInst->mut, 1);
    EXPECT_EQ(globalInst->value.parent.entryType, Entry_Value);
    EXPECT_EQ(globalInst->value.type, Value_i32);
    EXPECT_EQ(globalInst->value.value.i32, 38);

    // Clean
    free_Store(store);
    free(global);
}


text:
interface Elm {
    Shanghai: ElmModule<ShanghaiPorts>;
}

interface ShanghaiPorts {
    coordinates: PortToElm<Array<number>>;
    incomingShip: PortToElm<Ship>;
    outgoingShip: PortToElm<string>;
    totalCapacity: PortFromElm<number>;
}

interface Ship {
    name: string;
    capacity: number;
}

// initialize the Shanghai component which keeps track of
// shipping data in and out of the Port of Shanghai.
var shanghai = Elm.worker(Elm.Shanghai, {
    coordinates: [0, 0],
    incomingShip: { name: "", capacity: 0 },
    outgoingShip: ""
});

function logger(x: any) { console.log(x) }
shanghai.ports.totalCapacity.subscribe(logger);
// send some ships to the port of Shanghai
shanghai.ports.incomingShip.send({
    name: "Mary Mærsk",
    capacity: 18270
});
shanghai.ports.incomingShip.send({
    name: "Emma Mærsk",
    capacity: 15500
});
// have those ships leave the port of Shanghai
shanghai.ports.outgoingShip.send("Mary Mærsk");
shanghai.ports.outgoingShip.send("Emma Mærsk");