text:
namespace v8 {
namespace internal {

void Snapshot::ReserveSpaceForLinkedInSnapshot(Deserializer* deserializer) {
  deserializer->set_reservation(NEW_SPACE, new_space_used_);
  deserializer->set_reservation(OLD_POINTER_SPACE, pointer_space_used_);
  deserializer->set_reservation(OLD_DATA_SPACE, data_space_used_);
  deserializer->set_reservation(CODE_SPACE, code_space_used_);
  deserializer->set_reservation(MAP_SPACE, map_space_used_);
  deserializer->set_reservation(CELL_SPACE, cell_space_used_);
  deserializer->set_reservation(PROPERTY_CELL_SPACE,
                                property_cell_space_used_);
}

bool Snapshot::Initialize() {
  if (size_ > 0) {
    base::ElapsedTimer timer;
    if (FLAG_profile_deserialization) {
      timer.Start();
    }
    SnapshotByteSource source(raw_data_, raw_size_);
    Deserializer deserializer(&source);
    ReserveSpaceForLinkedInSnapshot(&deserializer);
    bool success = V8::Initialize(&deserializer);
    if (FLAG_profile_deserialization) {
      double ms = timer.Elapsed().InMillisecondsF();
      PrintF("[Snapshot loading and deserialization took %0.3f ms]\n", ms);
    }
    return success;
  }
  return false;
}

bool Snapshot::HaveASnapshotToStartFrom() {
  return size_ != 0;
}

Handle<Context> Snapshot::NewContextFromSnapshot(Isolate* isolate) {
  if (context_size_ == 0) {
    return Handle<Context>();
  }
  SnapshotByteSource source(context_raw_data_,
                            context_raw_size_);
  Deserializer deserializer(&source);
  Object* root;
  deserializer.set_reservation(NEW_SPACE, context_new_space_used_);
  deserializer.set_reservation(OLD_POINTER_SPACE, context_pointer_space_used_);
  deserializer.set_reservation(OLD_DATA_SPACE, context_data_space_used_);
  deserializer.set_reservation(CODE_SPACE, context_code_space_used_);
  deserializer.set_reservation(MAP_SPACE, context_map_space_used_);
  deserializer.set_reservation(CELL_SPACE, context_cell_space_used_);
  deserializer.set_reservation(PROPERTY_CELL_SPACE,
                               context_property_cell_space_used_);
  deserializer.DeserializePartial(isolate, &root);
  CHECK(root->IsContext());
  return Handle<Context>(Context::cast(root));
}

#ifdef V8_USE_EXTERNAL_STARTUP_DATA
// Dummy implementations of Set*FromFile(..) APIs.
//
// These are meant for use with snapshot-external.cc. Should this file
// be compiled with those options we just supply these dummy implementations
// below. This happens when compiling the mksnapshot utility.
void SetNativesFromFile(StartupData* data) { CHECK(false); }
void SetSnapshotFromFile(StartupData* data) { CHECK(false); }
#endif  // V8_USE_EXTERNAL_STARTUP_DATA

} }  // namespace v8::internal

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SeStep\Migrations\DI;

use Nette;
use Nette\InvalidArgumentException;
use Nette\UnexpectedValueException;
use SeStep\Migrations\Base\BaseMigration;

class MigrationsExtension extends Nette\DI\CompilerExtension
{
    public $defaults = array(
        'command' => 'app:utils:migrate',
        'list' => array(), // of migration classes or arrays with specific options
    );

    public function loadConfiguration()
    {
        $config = $this->validateConfig($this->defaults);

        $list = $this->verifyMigrationsDefinitions($config['list']);

        $container = $this->getContainerBuilder();

        $container->addDefinition($this->prefix('junction'))
            ->setClass('SeStep\Migrations\Migrations')
            ->setArguments(['list' => $list]);

        $container->addDefinition($this->prefix('migrateCommand'))
            ->setClass('SeStep\Migrations\MigrateCommand')
            ->setArguments(['name' => $config['command']])
            ->addTag('kdyby.console.command');
    }

    /**
     * @param string[]|mixed[] $list List of FQN indexed by keys
     * @return mixed[]
     */
    private function verifyMigrationsDefinitions($list)
    {
        $result = [];
        foreach ($list as $key => $item) {
            if (is_string($item)) {
                $item = ['class' => $item];
            }
            if (!is_array($item) || !isset($item['class'])) {
                throw new InvalidArgumentException('Migration definition has to be a FQN string or an array with a ' .
                    '\'class\' offset');
            }
            if (!is_a($item['class'], BaseMigration::class, true)) {
                throw new UnexpectedValueException('Migration class definition must be a descendant of '
                    . BaseMigration::class . ", $item[class] given");
            }
            $result[$key] = $item;
        }

        return $result;
    }

}


text:
/*
Modele e implemente em C (ficheiros .h e .c) uma estrutura de dados que represente uma versão simples do conceito
"gato". Um gato tem como características o nome ( _name), a idade ( _age), o peso ( _weight), o volume do
ronronar ( _purrLevel) e o grau de suavidade do pêlo ( _fluffiness). Implemente a função newCat que reserva
memória suficiente para representar um gato e permite inicializar os seus campos (através dos argumentos da
função). Por simplicidade, assuma que o campo _name tem comprimento fixo máximo de 16 caracteres (incluindo o
terminador). Implemente também a função destroyCat, que liberta os recursos associados ao gato.

a. Implemente a função de comparação - equalsCat -, por forma a considerar que dois gatos são iguais se as suas
características forem iguais.
b. Implemente funções de acesso às variáveis de um gato: getCatName, getCatAge, getCatWeight, getCatPurrLevel,
getCatFluffiness (dado um gato, retornam um dos seus campos).
c. Implemente a função printCat que, quando aplicada a um gato, apresenta os seus dados (use printf para apresentar
cada campo do gato).
d. Implemente um programa - main - que ilustre a utilização das funções anteriores.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Cat.h"

struct cat{
	char _name[16];
	int _age;
	int _weight;
	int _purrLevel;
	int _fluffiness;
};

Cat* newCat(char* name, int age, int weight, int purrLevel, int fluffiness){
	Cat* cat;

	// Allocate memory for the "Cat" structure
	cat = (Cat*)malloc(sizeof(Cat));

	if (cat != NULL){
		strcpy(cat->_name, name);
		cat->_age = age;
		cat->_weight = weight;
		cat->_purrLevel = purrLevel;
		cat->_fluffiness = fluffiness;
	}

	return cat;
}

void destroyCat(Cat* cat){
	if (cat != NULL){
		free(cat);
	}
}

int equalsCat(Cat* c1, Cat* c2){
	if (c1 != NULL && c2 != NULL)
	{
		return (
			getFluffiness(c1) == getFluffiness(c2) &&
			getAge(c1) == getAge(c2) &&
			getPurrLevel(c1) == getPurrLevel(c2)
			&& getWeight(c1) == getWeight(c2)
			&& !strcmp(c1->_name, c2->_name)
			);
	}
	return -1; // One of the addresses is NULL (Error)
}

char* getName(Cat* cat){
	return cat->_name;
}

int getAge(Cat* cat){
	return cat->_age;
}

int getWeight(Cat* cat){
	return cat->_weight;
}

int getPurrLevel(Cat* cat){
	return cat->_purrLevel;
}

int getFluffiness(Cat* cat){
	return cat->_fluffiness;
}

void printCat(Cat* cat){
	printf("N: %s \nA: %d \nW: %d \nPL: %d \nF: %d \n", getName(cat), getAge(cat), getWeight(cat), getPurrLevel(cat), getFluffiness(cat));
}


text:
layout: post
title: Many Loves of Peter Pan
date: 2012-08-18
---
Belle grabs from behind, guides him. Ballroom is spinning. Peter Pan,
      intoxicated, lets himself be directed. Quickly as that he has a new love and Belle like a face
      in a lamp is knowing but not willing to accept the truth that she is competing for his
      affections and losing.    Pan can't keep this up for long. With Jasmine
      now the vortex through which his love is received, his ability to stay neutral is increasingly
      diminished. He sits on a couch in a movie theater behind an even more cartoonish man who is
      talking about something that isn't very funny. We're in some strange comic book. Belle, a
      beastly akaname, climbs onto the arm of the couch next to Pan as the flickering lights of the
      film flash against their bodies.    "Hehe. That's ok. No. I don't think
      so."    The arm of the couch is now moist with bath water.


text:
from console import console
from roomter import roomter
from sub_process import sub_process
from tools import tools
from strip_ogg import strip_ogg
from switch_stream_Worker import switch_stream_Worker

__version__ = '0.1'

class test_tool(console,roomter,sub_process,tools,strip_ogg,switch_stream_Worker):
	"""audio自动化测试库"""
	ROBOT_LIBRARY_SCOPE = 'GLOBAL'


text:
package com.esri.gdb

import java.io.{DataInput, File}
import java.nio.{ByteBuffer, ByteOrder}

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FSDataInputStream, Path}
import org.apache.spark.Logging

object GDBIndex {
  def apply(path: String, name: String, conf: Configuration = new Configuration()) = {
    val filename = StringBuilder.newBuilder.append(path).append(File.separator).append(name).append(".gdbtablx").toString()
    val hdfsPath = new Path(filename)
    val dataInput = hdfsPath.getFileSystem(conf).open(hdfsPath)

    val bytes = new Array[Byte](16)
    dataInput.readFully(bytes)
    val byteBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)

    val signature = byteBuffer.getInt
    val n1024Blocks = byteBuffer.getInt
    val numRows = byteBuffer.getInt
    val indexSize = byteBuffer.getInt

    new GDBIndex(dataInput, numRows, indexSize)
  }
}

private[gdb] class GDBIndex(dataInput: FSDataInputStream,
                            val numRows: Int,
                            indexSize: Int
                           ) extends Logging with AutoCloseable with Serializable {

  def readSeekForRowNum(rowNum: Int) = {
    val bytes = new Array[Byte](indexSize)
    dataInput.seek(16 + rowNum * indexSize)
    dataInput.readFully(bytes)
    ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt
  }

  def iterator(startAtRow: Int = 0, numRowsToRead: Int = -1) = {
    dataInput.seek(16 + startAtRow * indexSize)
    val maxRows = if (numRowsToRead == -1) numRows else numRowsToRead
    // log.info(s"iterator::startAtRow=$startAtRow maxRows=$maxRows")
    new GDBIndexIterator(dataInput, startAtRow, maxRows, indexSize).withFilter(_.isSeekable)
  }

  def close() {
    dataInput.close()
  }
}

private[gdb] class GDBIndexIterator(dataInput: DataInput,
                                    startID: Int,
                                    maxRows: Int,
                                    indexSize: Int
                                   ) extends Iterator[IndexInfo] with Logging with Serializable {

  private val indexInfo = IndexInfo(0, 0)
  private val bytes = new Array[Byte](indexSize)
  private val byteBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)

  private var objectID = startID
  private var nextRow = 0

  def hasNext() = nextRow < maxRows

  def next() = {
    // log.info(s"next::nextRow=$nextRow maxRows=$maxRows")
    nextRow += 1

    objectID += 1
    indexInfo.objectID = objectID

    byteBuffer.clear
    dataInput.readFully(bytes)
    indexInfo.seek = byteBuffer.getInt

    indexInfo
  }
}


text:
import unittest
from decimal import Decimal
import datetime
from ctypes import *
from ctypes.wintypes import BOOL
from comtypes.test.find_memleak import find_memleak
from comtypes import BSTR, IUnknown
from comtypes.test import is_resource_enabled
import array

from comtypes.automation import VARIANT, IDispatch, VT_ARRAY, VT_VARIANT, \
     VT_I4, VT_R4, VT_R8, VT_BSTR, VARIANT_BOOL, VT_DATE, VT_CY
from comtypes.automation import _midlSAFEARRAY

from comtypes._safearray import SafeArrayGetVartype

class VariantTestCase(unittest.TestCase):
    def test_VARIANT_array(self):
        v = VARIANT()
        v.value = ((1, 2, 3), ("foo", "bar", None))
        self.failUnlessEqual(v.vt, VT_ARRAY | VT_VARIANT)
        self.failUnlessEqual(v.value, ((1, 2, 3), ("foo", "bar", None)))

        def func():
            v = VARIANT((1, 2, 3), ("foo", "bar", None))

        bytes = find_memleak(func)
        self.failIf(bytes, "Leaks %d bytes" % bytes)

    def test_object(self):
        self.assertRaises(TypeError, lambda: VARIANT(object()))

    def test_double_array(self):
        a = array.array("d", (3.14, 2.78))
        v = VARIANT(a)
        self.failUnlessEqual(v.vt, VT_ARRAY | VT_R8)
        self.failUnlessEqual(tuple(a.tolist()), v.value)

        def func():
            v = VARIANT(array.array("d", (3.14, 2.78)))

        bytes = find_memleak(func)
        self.failIf(bytes, "Leaks %d bytes" % bytes)

    def test_float_array(self):
        a = array.array("f", (3.14, 2.78))
        v = VARIANT(a)
        self.failUnlessEqual(v.vt, VT_ARRAY | VT_R4)
        self.failUnlessEqual(tuple(a.tolist()), v.value)

    def test_2dim_array(self):
        data = ((1, 2, 3, 4),
                (5, 6, 7, 8),
                (9, 10, 11, 12))
        v = VARIANT(data)
        self.failUnlessEqual(v.value, data)

    def test_datetime(self):
        now = datetime.datetime.now()

        v = VARIANT()
        v.value = now
        self.failUnlessEqual(v.value, now)
        self.failUnlessEqual(v.vt, VT_DATE)

    def test_decimal(self):
        pi = Decimal("3.13")

        v = VARIANT()
        v.value = pi
        self.failUnlessEqual(v.vt, VT_CY)
        self.failUnlessEqual(v.value, pi)

    def test_UDT(self):
        from comtypes.gen.TestComServerLib import MYCOLOR
        v = VARIANT(MYCOLOR(red=1.0, green=2.0, blue=3.0))
        value = v.value
        self.failUnlessEqual((1.0, 2.0, 3.0),
                             (value.red, value.green, value.blue))

        def func():
            v = VARIANT(MYCOLOR(red=1.0, green=2.0, blue=3.0))
            return v.value

        bytes = find_memleak(func)
        self.failIf(bytes, "Leaks %d bytes" % bytes)

class SafeArrayTestCase(unittest.TestCase):

    def test_equality(self):
        a = _midlSAFEARRAY(c_long)
        b = _midlSAFEARRAY(c_long)
        self.failUnless(a is b)

        c = _midlSAFEARRAY(BSTR)
        d = _midlSAFEARRAY(BSTR)
        self.failUnless(c is d)

        self.failIfEqual(a, c)

        # XXX remove:
        self.failUnlessEqual((a._itemtype_, a._vartype_),
                             (c_long, VT_I4))
        self.failUnlessEqual((c._itemtype_, c._vartype_),
                             (BSTR, VT_BSTR))

    def test_VT_BSTR(self):
        t = _midlSAFEARRAY(BSTR)

        sa = t.from_param(["a" ,"b", "c"])
        self.failUnlessEqual(sa[0], ("a", "b", "c"))
        self.failUnlessEqual(SafeArrayGetVartype(sa), VT_BSTR)

    def test_VT_BSTR_leaks(self):
        sb = _midlSAFEARRAY(BSTR)
        def doit():
            sb.from_param(["foo", "bar"])

        bytes = find_memleak(doit)
        self.failIf(bytes, "Leaks %d bytes" % bytes)

    def test_VT_I4_leaks(self):
        sa = _midlSAFEARRAY(c_long)
        def doit():
            sa.from_param([1, 2, 3, 4, 5, 6])

        bytes = find_memleak(doit)
        self.failIf(bytes, "Leaks %d bytes" % bytes)

    def test_VT_I4(self):
        t = _midlSAFEARRAY(c_long)

        sa = t.from_param([11, 22, 33])

        self.failUnlessEqual(sa[0], (11, 22, 33))

        self.failUnlessEqual(SafeArrayGetVartype(sa), VT_I4)

        # TypeError: len() of unsized object
        self.assertRaises(TypeError, lambda: t.from_param(object()))

    def test_array(self):
        t = _midlSAFEARRAY(c_double)
        pat = pointer(t())

        try:
            import numpy
        except ImportError:
            pass # numpy not available
        else:
            pat[0] = numpy.zeros(32, dtype=numpy.float)
            self.failUnlessEqual(tuple(pat[0][0]),
                                 (0.0,) * 32)

            data = ((1.0, 2.0, 3.0),
                    (4.0, 5.0, 6.0),
                    (7.0, 8.0, 9.0))
            a = numpy.array(data,
                            dtype=numpy.double)
            pat[0] = a
            self.failUnlessEqual(pat[0][0],
                                 data)

            data = ((1.0, 2.0), (3.0, 4.0), (5.0, 6.0))
            a = numpy.array(data,
                            dtype=numpy.double,
                            order="F")
            pat[0] = a
            self.failUnlessEqual(pat[0][0],
                                 data)

    def test_VT_VARIANT(self):
        t = _midlSAFEARRAY(VARIANT)

        now = datetime.datetime.now()
        sa = t.from_param([11, "22", None, True, now, Decimal("3.14")])
        self.failUnlessEqual(sa[0], (11, "22", None, True, now, Decimal("3.14")))

        self.failUnlessEqual(SafeArrayGetVartype(sa), VT_VARIANT)

    def test_VT_BOOL(self):
        t = _midlSAFEARRAY(VARIANT_BOOL)

        sa = t.from_param([True, False, True, False])
        self.failUnlessEqual(sa[0], (True, False, True, False))

    def test_VT_UNKNOWN_1(self):
        a = _midlSAFEARRAY(POINTER(IUnknown))
        t = _midlSAFEARRAY(POINTER(IUnknown))
        self.failUnless(a is t)

        def com_refcnt(o):
            "Return the COM refcount of an interface pointer"
            import gc; gc.collect(); gc.collect()
            o.AddRef()
            return o.Release()

        from comtypes.typeinfo import CreateTypeLib, ICreateTypeLib
        punk = CreateTypeLib("spam").QueryInterface(IUnknown) # will never be saved to disk

        # initial refcount
        initial = com_refcnt(punk)

        # This should increase the refcount by 1
        sa = t.from_param([punk])
        self.failUnlessEqual(initial + 1, com_refcnt(punk))

        # Unpacking the array must not change the refcount, and must
        # return an equal object.
        self.failUnlessEqual((punk,), sa[0])
        self.failUnlessEqual(initial + 1, com_refcnt(punk))

        del sa
        self.failUnlessEqual(initial, com_refcnt(punk))

        sa = t.from_param([None])
        self.failUnlessEqual((POINTER(IUnknown)(),), sa[0])

    def test_VT_UNKNOWN_multi(self):
        a = _midlSAFEARRAY(POINTER(IUnknown))
        t = _midlSAFEARRAY(POINTER(IUnknown))
        self.failUnless(a is t)

        def com_refcnt(o):
            "Return the COM refcount of an interface pointer"
            import gc; gc.collect(); gc.collect()
            o.AddRef()
            return o.Release()

        from comtypes.typeinfo import CreateTypeLib, ICreateTypeLib
        punk = CreateTypeLib("spam").QueryInterface(IUnknown) # will never be saved to disk

        # initial refcount
        initial = com_refcnt(punk)

        # This should increase the refcount by 4
        sa = t.from_param((punk,) * 4)
        self.failUnlessEqual(initial + 4, com_refcnt(punk))

        # Unpacking the array must not change the refcount, and must
        # return an equal object.
        self.failUnlessEqual((punk,)*4, sa[0])
        self.failUnlessEqual(initial + 4, com_refcnt(punk))

        del sa
        self.failUnlessEqual(initial, com_refcnt(punk))

        # This should increase the refcount by 2
        sa = t.from_param((punk, None, punk, None))
        self.failUnlessEqual(initial + 2, com_refcnt(punk))

        null = POINTER(IUnknown)()
        self.failUnlessEqual((punk, null, punk, null), sa[0])

        del sa
        self.failUnlessEqual(initial, com_refcnt(punk))

        # repeat same test, with 2 different com pointers

        plib = CreateTypeLib("foo")
        a, b = com_refcnt(plib), com_refcnt(punk)
        sa = t.from_param([plib, punk, plib])

####        self.failUnlessEqual((plib, punk, plib), sa[0])
        self.failUnlessEqual((a+2, b+1), (com_refcnt(plib), com_refcnt(punk)))

        del sa
        self.failUnlessEqual((a, b), (com_refcnt(plib), com_refcnt(punk)))

    def test_UDT(self):
        from comtypes.gen.TestComServerLib import MYCOLOR

        t = _midlSAFEARRAY(MYCOLOR)
        self.failUnless(t is _midlSAFEARRAY(MYCOLOR))

        sa = t.from_param([MYCOLOR(0, 0, 0), MYCOLOR(1, 2, 3)])

        self.failUnlessEqual([(x.red, x.green, x.blue) for x in sa[0]],
                             [(0.0, 0.0, 0.0), (1.0, 2.0, 3.0)])

        def doit():
            t.from_param([MYCOLOR(0, 0, 0), MYCOLOR(1, 2, 3)])
        bytes = find_memleak(doit)
        self.failIf(bytes, "Leaks %d bytes" % bytes)

if is_resource_enabled("pythoncom"):
    try:
        import pythoncom
    except ImportError:
        # pywin32 not installed...
        pass
    else:
        # pywin32 is available.  The pythoncom dll contains two handy
        # exported functions that allow to create a VARIANT from a Python
        # object, also a function that unpacks a VARIANT into a Python
        # object.
        #
        # This allows us to create und unpack SAFEARRAY instances
        # contained in VARIANTs, and check for consistency with the
        # comtypes code.

        _dll = PyDLL(pythoncom.__file__)

        # c:/sf/pywin32/com/win32com/src/oleargs.cpp 213
        # PyObject *PyCom_PyObjectFromVariant(const VARIANT *var)
        unpack = _dll.PyCom_PyObjectFromVariant
        unpack.restype = py_object
        unpack.argtypes = POINTER(VARIANT),

        # c:/sf/pywin32/com/win32com/src/oleargs.cpp 54
        # BOOL PyCom_VariantFromPyObject(PyObject *obj, VARIANT *var)
        _pack = _dll.PyCom_VariantFromPyObject
        _pack.argtypes = py_object, POINTER(VARIANT)
        _pack.restype = BOOL
        def pack(obj):
            var = VARIANT()
            result = _pack(obj, byref(var))
            return var

        class PyWinTest(unittest.TestCase):
            def test_1dim(self):
                data = (1, 2, 3)
                variant = pack(data)
                self.failUnlessEqual(variant.value, data)
                self.failUnlessEqual(unpack(variant), data)

            def test_2dim(self):
                data = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
                variant = pack(data)
                self.failUnlessEqual(variant.value, data)
                self.failUnlessEqual(unpack(variant), data)

            def test_3dim(self):
                data = ( ( (1, 2), (3, 4), (5, 6) ),
                         ( (7, 8), (9, 10), (11, 12) ) )
                variant = pack(data)
                self.failUnlessEqual(variant.value, data)
                self.failUnlessEqual(unpack(variant), data)

            def test_4dim(self):
                data = ( ( ( ( 1,  2), ( 3,  4) ),
                           ( ( 5,  6), ( 7,  8) ) ),
                         ( ( ( 9, 10), (11, 12) ),
                           ( (13, 14), (15, 16) ) ) )
                variant = pack(data)
                self.failUnlessEqual(variant.value, data)
                self.failUnlessEqual(unpack(variant), data)

if __name__ == "__main__":
    unittest.main()


text:
using UnityEngine;
using System.Collections;

public class Screenshot : MonoBehaviour {
	void Update() {
		if(Input.GetKeyDown(KeyCode.F9))
		   {
			ScreenCapture.CaptureScreenshot(Time.realtimeSinceStartup + "_Screenshot.png");
		}
	}
}


text:
package org.hibernate.test.type.descriptor.java;

import static org.junit.Assert.assertEquals;

import java.util.Locale;

import org.hibernate.internal.util.StringHelper;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.type.descriptor.java.LocaleTypeDescriptor;
import org.junit.Test;

/**
 * Tests of the {@link LocaleTypeDescriptor} class.
 *
 * @author Christian Beikov
 * @author Steve Ebersole
 */
public class LocaleTypeDescriptorTest extends BaseUnitTestCase {

	@Test
	public void testConversionFromString() {
		assertEquals( toLocale( "de", null, null ), LocaleTypeDescriptor.INSTANCE.fromString( "de" ) );
		assertEquals( toLocale( "de", "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE" ) );
		assertEquals( toLocale( null, "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE" ) );
		assertEquals( toLocale( null, null, "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "__ch123" ) );
		assertEquals( toLocale( null, "DE", "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE_ch123" ) );
		assertEquals( toLocale( "de", null, "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "de__ch123" ) );
		assertEquals( toLocale( "de", "DE", "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE_ch123" ) );
	}

	public Locale toLocale(String lang, String region, String variant) {
		final Locale.Builder builder = new Locale.Builder();
		if ( StringHelper.isNotEmpty( lang ) ) {
			builder.setLanguage( lang );
		}
		if ( StringHelper.isNotEmpty( region ) ) {
			builder.setRegion( region );
		}
		if ( StringHelper.isNotEmpty( variant ) ) {
			builder.setVariant( variant );
		}
		return builder.build();
	}
}


text:
from __future__ import absolute_import, unicode_literals

from collections import OrderedDict

from decorator import decorator

import groove._constants as _constants
from groove.audio_format import AudioFormat
from groove.groove import GrooveClass
from groove._groove import ffi, lib

__all__ = ['File']

@decorator
def _require_open(method, *args, **kwargs):
    if args[0]._obj is None:
        raise ValueError('File is not open')
    return method(*args, **kwargs)

class File(GrooveClass):
    """Groove File

    Args:
        filename (str)  Name of the file to open
    """
    _ffitype = 'struct GrooveFile *'
    tag_match_case = _constants.GROOVE_TAG_MATCH_CASE
    tag_dont_overwrite = _constants.GROOVE_TAG_MATCH_CASE
    tag_append = _constants.GROOVE_TAG_MATCH_CASE

    @property
    def filename(self):
        return self._filename

    @classmethod
    def _from_obj(cls, obj):
        instance, created = super(File, cls)._from_obj(obj)
        if created:
            instance._filename = ffi.string(instance._obj.filename).decode()
        return instance, created

    def __init__(self, filename):
        self._obj = None
        self._filename = filename

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.close()

    def __eq__(self, rhs):
        if not isinstance(rhs, File):
            return False
        return self.filename == rhs.filename

    def open(self):
        """Open the file

        In general this should not be used, use the context manager approach
        when possible
        """
        if self._obj is not None:
            raise ValueError('File is already open')

        self._obj = lib.groove_file_open(self._filename.encode())
        if self._obj == ffi.NULL:
            # TODO: get error from AV_LOG
            self._obj = None
            raise ValueError('I/O error opening file')

    def close(self):
        """Close the file

        In general this should not be used, use the context manager approach
        when possible
        """
        lib.groove_file_close(self._obj or ffi.NULL)
        self._obj = None

    @_require_open
    def save(self):
        """Save changes made to the file"""
        status = lib.groove_file_save(self._obj)
        if status < 0:
            # TODO: Read error msg from AV_LOG
            raise ValueError('Unknown error')

    @_require_open
    def dirty(self):
        """True if unsaved changed have been made to the file"""
        return bool(self._obj.dirty)

    @_require_open
    def get_tags(self, flags=0):
        """Get the tags for an open file

        Args:
            flags (int)  Bitmask of tag flags

        Returns:
            A dictionary of `name: value` pairs. Both `name` and `value` will
            be type `bytes`.
        """
        # Have to make a GrooveTag** so cffi doesn't try to sizeof GrooveTag
        gtag_ptr = ffi.new('struct GrooveTag **')
        gtag = gtag_ptr[0]
        tags = OrderedDict()
        while True:
            gtag = lib.groove_file_metadata_get(self._obj, b'', gtag, flags)
            if gtag == ffi.NULL:
                break

            key = ffi.string(lib.groove_tag_key(gtag))
            value = ffi.string(lib.groove_tag_value(gtag))
            tags[key] = value

        return tags

    @_require_open
    def set_tags(self, tagdict, flags=0):
        """Shortcut to set each flag in tagdict

        This will overwrite existing tags, but will not delete existing tags
        that are not listed in tagdict. To delete a tag, set its value to
        `None`
        """
        for k, v in tagdict.items():
            self.set_tag(k, v, flags)

    @_require_open
    def set_tag(self, key, value, flags=0):
        """Set tag `key` to `value`

        If `value` is `None`, the tag will be deleted. `key` and `value` must
        be type `bytes`.
        """
        if value is None:
            value = ffi.NULL

        status = lib.groove_file_metadata_set(self._obj, key, value, flags)
        return status

    @_require_open
    def short_names(self):
        """A list of short names for the format"""
        names = ffi.string(lib.groove_file_short_names(self._obj)).decode()
        return names.split(',')

    @_require_open
    def duration(self):
        """Get the main audio stream duration in seconds

        Note that this relies on a combination of format headers and
        heuristics. It can be inaccurate. The most accurate way to learn
        the duration of a file is to use GrooveLoudnessDetector.
        """
        return lib.groove_file_duration(self._obj)

    @_require_open
    def audio_format(self):
        audio_format = AudioFormat()
        lib.groove_file_audio_format(self._obj, audio_format._obj)
        return audio_format


text:
export { default } from './Menu';
export * from './Menu';
export { default as MenuList } from './MenuList';
export * from './MenuList';
export { default as MenuItem } from './MenuItem';
export * from './MenuItem';


text:
<?php
namespace wpfactory;

/**
 * Класс для работы с видами
 * Class View
 */
class View
{
    /**
     * @var string Путь к папке с видами по-умолчанию
     */
    public static $defaultViewDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'common' . DIRECTORY_SEPARATOR . 'views';

    /**
     */
    public function __construct()
    {
    }

    /**
     * Отображает вид
     * @param $viewName string вида (файла) БЕЗ .php!
     * @param array $data данные дял вида (ассоциативный массив, но в виде будут достыпны как переменные)
     * @param string $viewDir путь к папке с видами
     * @return mixed
     * @throws \Exception
     */
    public static function render($viewName, $data = array(), $viewDir = null)
    {
        if ($viewDir === null) $viewDir = self::$defaultViewDir;
        $filePath = $viewDir . '/' . $viewName . '.php';
        if ($viewName && file_exists($filePath)) {
            extract($data);
            ob_start();
            require $filePath;
            return ob_get_clean();
        } else {
            throw new \Exception("View $viewName not found!");
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" type="text/css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="./resources/prism/prism.css" type="text/css">
    <link rel="stylesheet" href="../css/ol.css" type="text/css">
    <link rel="stylesheet" href="./resources/layout.css" type="text/css">

    <title>Navigation Controls</title>

           OpenLayers Examples

Docs

Examples

API

Code

Navigation Controls

Shows how to add navigation controls.

This example shows how to use the beforeRender function on the Map to run one or more animations.

The following navigation controls are added to the map:

ol.control.Zoom (added by default)

ol.control.ZoomToExtent

Related API documentation:

ol.Map
,
ol.View
,
ol.control
,
ol.control.ZoomToExtent
,
ol.layer.Tile
,
ol.source.OSM

           Copy
           Edit

        <form method="POST" id="jsfiddle-form" target="_blank" action="http://jsfiddle.net/api/post/library/pure/">
          <textarea class="hidden" name="js">var map = new ol.Map({
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }).extend([
    new ol.control.ZoomToExtent({
      extent: [
        813079.7791264898, 5929220.284081122,
        848966.9639063801, 5936863.986909639
      ]
    })
  ]),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});
</textarea>
          <textarea class="hidden" name="css"></textarea>
          <textarea class="hidden" name="html"><div id="map" class="map"></div>
</textarea>
          <input type="hidden" name="wrap" value="l">
          <input type="hidden" name="resources" value="http://openlayers.org/en/v3.15.1/css/ol.css,http://openlayers.org/en/v3.15.1/build/ol.js">
        </form>

<!DOCTYPE html>
<html>
  <head>
    <title>Navigation Controls</title>
    <link rel="stylesheet" href="http://openlayers.org/en/v3.15.1/css/ol.css" type="text/css">
    <script src="http://openlayers.org/en/v3.15.1/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
      var map = new ol.Map({
        controls: ol.control.defaults({
          attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
            collapsible: false
          })
        }).extend([
          new ol.control.ZoomToExtent({
            extent: [
              813079.7791264898, 5929220.284081122,
              848966.9639063801, 5936863.986909639
            ]
          })
        ]),
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        target: 'map',
        view: new ol.View({
          center: [0, 0],
          zoom: 2
        })
      });
    </script>
  </body>
</html>


text:
<?php
/**
 * Author: Pavel Naumenko
 */

namespace frontend\widgets\authBlock;

/**
 * Class Widget
 *
 * @package frontend\widgets\authBlock
 */
class Widget extends \yii\base\Widget
{
    /**
     * @return string
     */
    public function run()
    {
        $view = \Yii::$app->user->isGuest ? 'guest' : 'authorized';

        return $this->render($view);
    }
}


text:
package edu.teco.dnd.module.messages.values;

import java.io.Serializable;

import edu.teco.dnd.blocks.FunctionBlockID;
import edu.teco.dnd.module.ApplicationID;
import edu.teco.dnd.module.UserSuppliedCodeException;
import edu.teco.dnd.module.UsercodeWrapper;
import edu.teco.dnd.network.messages.ApplicationSpecificMessage;

/**
 * Message containing a value send by the output of one functionBlock to the input of another.
 *
 * @author Marvin Marx
 *
 */
public class ValueMessage extends ApplicationSpecificMessage {

	public static final String MESSAGE_TYPE = "value";
	/**
	 * ID of the block this is to be send to.
	 */
	public final FunctionBlockID blockID;
	/**
	 * Name of the input this is to be send to.
	 */
	public final String input;
	/**
	 * The actual value.
	 */
	public final Serializable value;

	/**
	 *
	 * @param applicationID
	 *            ID of the application this is part of
	 * @param functionBlock
	 *            ID of the block this is to be send to.
	 * @param input
	 *            Name of the input this is to be send to.
	 * @param value
	 *            The actual value.
	 */
	public ValueMessage(ApplicationID applicationID, FunctionBlockID functionBlock, String input, Serializable value) {
		super(applicationID);
		this.blockID = functionBlock;
		this.input = input;
		this.value = value;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((blockID == null) ? 0 : blockID.hashCode());
		result = prime * result + ((input == null) ? 0 : input.hashCode());
		try {
			result = prime * result + ((value == null) ? 0 : UsercodeWrapper.getHashCode(value));
		} catch (UserSuppliedCodeException e) {
			e.printStackTrace();
			result = prime * result + 0;
		}
		return result;
	}

	/**
	 * ATTENTION: may falsely return false, because the Serializable value does not guarantee comparability!
	 *
	 * @param obj
	 *            the usual.
	 * @return the usual.
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		ValueMessage other = (ValueMessage) obj;
		if (blockID == null) {
			if (other.blockID != null) {
				return false;
			}
		} else if (!blockID.equals(other.blockID)) {
			return false;
		}
		if (input == null) {
			if (other.input != null) {
				return false;
			}
		} else if (!input.equals(other.input)) {
			return false;
		}
		if (value == null) {
			if (other.value != null) {
				return false;
			}
		} else {
			try {
				if (!UsercodeWrapper.getEquals(value, other.value)) {
					return false;
				}
			} catch (UserSuppliedCodeException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		try {
			return "ValueMessage [blockId=" + blockID + ", input=" + input + ", value="
					+ UsercodeWrapper.getToString(value) + ", getApplicationID()=" + getApplicationID()
					+ ", getUUID()=" + getUUID() + "]";
		} catch (UserSuppliedCodeException e) {
			e.printStackTrace();
			return "ValueMessage [blockId=" + blockID + ", input=" + input + ", value=" + "ERROR"
					+ ", getApplicationID()=" + getApplicationID() + ", getUUID()=" + getUUID() + "]";
		}
	}

}


text:
package sai.bytecode.instruction

import sai.bytecode.Method
import vm.Frame

class EntryPoint(method: Method) extends Instruction(null, null, method) {

  override def id: String = buildId("entry")

  override def prev: Instruction = null

  override def next: Instruction = method.firstInstruction

  override def successors: List[Instruction] = List(next)

  override def lineNumber: Int = method.firstInstruction.lineNumber - 1

  override def interpret(frame: Frame): List[Frame] = frame :: Nil

  override def compare(that: Instruction): Int = -1

  override def toString = s"$id entry point"

}


text:
File Uploader
=============

Mono file uploader module.

## Configuration

The most important parameters are set in the module upload operation `params` array.

 - `uploadDir`: path to the directory where the file will be uploaded (**required**)
 - `dsUpload`: datasource (**required**)
 - `dsTemporarUpload`: temporar upload datasource (**required** if `temporarUpload: true` in uploader template configuration)
 - `emitArgument`: sets the parameter that will be emited by module in `fileUploaded` event. It can take the following values: `id`, `path`, `object` or an object: `{"type": "custom", "value": "docKey"}` (`upload` operation)
 - `uploadFileEvent`: name of custom handler that gets called before the uploaded object gets inserted in the db (`upload` operation)
 - `customUpload`: name of custom handler that gets called in order to construct a custom upload path for the uploaded file (`upload` operation)
 - `customPathHandler`: name of custom handler that gets called in order to construct a custom path to a file that needs to be downloaded (`download` operation)

The file-uploader module can also receive an optional template object with a template configuration (see `setTemplate` event bellow). In this case for each `setTemplate` call, the module will render all configured `uploaders` (see template configuration bellow) for the given template in the specified `container` based on user permissions.

## Template configuration

The most important parameters are set in the `uploader` object found in the template `options` configuration

 - `uploaders`: object containing all distinct uploader configurations (a template can have multiple uploaders with diffrent configurations and permissions (upload, download, remove) all renderd by the same module instance (**required**)
    * `[uploaderName]` the name of the uploader instance (**required**)
        * `container` the selector used to find the container where the uploader will be rendered
        * `uploadDir` path to the directory where the file will be uploaded (this path will be appended to the `uploadDir` value found in the module `params` array)
        * `customUpload` name of custom handler that gets called in order to construct a custom upload path for the uploaded file (`upload` operation)
        * `uploadFileEvent` name of custom handler that gets called before the uploaded object gets inserted in the db (`upload` operation)
        * `temporarUpload` document will be uploaded to a temporar collection (true/false)
        * `access` permissions string for the module operations (upload, download, remove), can be set dynamically for each user in the `crud_access.js` file ("u" - if user has uplaod permission, "d" - download permission, "r" - remove permission)
        * `customPathHandler` name of custom handler that gets called in order to construct a custom path to a file that needs to be downloaded (`download` operation)
        * `customPermissions` name of custom handler that returns custom permissions for the upload operations
 - `html` the path to the html files/file for the upload controls
 - `controls` selector configurations for the upload controls (`select`, `upload`, `fileName`)
 - `waitForEvent` the uploader will listen for a `enableRendering` event before rendering the configured uploaders

### Example of configuration

```JSON
"uploader": {
    "module": "github/jillix/file-uploader/[VERSION]",
    "config": {
        "html": "/path/to/html/file.html",
        "options": {
            "acceptTypes": ["txt", "and", "other", "file", "extensions"]
        },
        "binds": [BIND_OBJECTS],
        "listen": {EVENT_OBJECTS}
    },
    "roles": [MONO_ROLES],
    "operations": {
        "upload": {
            "roles": [MONO_ROLES],
            "params": [
                {
                    "dsUpload": "temporarDS",
                    "emitArgument": "path",
                    "acceptTypes": ["txt", "and", "other", "file", "extensions"],
                    "uploadDir": "path/to/upload/dir",
                    "uploadFileEvent": "uploadedFileToImport",
                    "customUpload": "getUploadCustomPath"
                }
            ]
        },
        "download": {
            "roles": [MONO_ROLES],
            "params": [
                {
                    "dsUpload": "temporarDS",
                    "uploadDir": "path/to/upload/dir",
                    "customPathHandler": "getDocCustomPath"
                }
            ]
        },
        "remove": {
            "roles": [MONO_ROLES],
            "params": [
                {
                    "dsUpload": "temporarDS",
                    "uploadDir": "path/to/upload/dir",
                    "removeFileEvent": "exampleHandler"
                }
            ]
        },
        "getDocuments": {
            "roles": [MONO_ROLES],
            "params": [
                {
                    "dsUpload": "temporarDS"
                }
            ]
        },
        "getUploadPermissions": {
            "roles": [MONO_ROLES],
            "params": [{}]
        }
    }
},
```

Where `temporarDS` is defined into `datasources` key from application descriptor:

```JSON
{
  ...
  "datasources": {
    "temporarDS": {
      "type": "mongo",
      "db": "databaseName",
      "collection": "temp"
    }
  },
  ...
}
```

### Example of template configuration
```Javascript
uploader: {
    uploaders: {
        [UPLOADER_NAME]: {
            container: [CSS_SELECTOR],
            uploadDir: "path/to/upload/dir",
            customUpload: "handlerName",
            uploadFileEvent: "handlerName",
            temporarUpload: true, // default false
            access: 'urd',
            customPermissions: "handlerName",
            customPathHandler: "handlerName"
        }
    },
    html: "path/to/htmlFile.html", // can be i18n object
    controls: {
        select: ".btn-upload-select",
        upload: ".btn-upload-start",
        fileName: ".file-name"
    },
    waitForEvent: true // default false
}
```
## Events

The module emits the following events:

        Event name
        Description
        Parameters

fileUploaded

            It is emited when the file is uploaded
            uploaded file id, path or the entire object. This can be set in the module upload operation parameters.

uploadFailed

            It is emited when the upload process encountered an error and failed
            The error encountered. This parameter can be missing.

itemRemoved

            It is emited when the file is successfully removed
            none

uploadersRendered

            It is emited when the template configured uploaders finish rendering
            none

The module listens for the following events:

        Event name
        Description
        Parameters

setTemplate

            Sets the template and renders uploaders based on the configuration found inside the template
            The full template object or the template `_id` as string.

enableRendering

            Starts the uploaders rendering if the `waitForEvent` is true
            none

setData

            Data sent will be appended to the upload form
            `data` object

reset

            For template uploaders only. Resets the uploader controls
            none

rebuildUi

            For template uploaders only. The uploader will ask again for the upload permissions and rebuild the uploaders based on the permissions that might have changed
            none

removeItem

            Removes the specified item from the DB and FS
            An object containing the `itemId` and `uploader` (the name of the uploader instance configured in the `uploaders` field) if the document was uploaded using a template uploader

getDocuments

            For template uploaders only. Returns the documents for a specified `uploader` and `template` based on the user permissions. Also returns `removeForbidden: true` if the user cannot remove the requested documents
            An object containing `uploader` name and `template` object or id as string

## Change Log

### v0.5.0
- Added "template uploaders" functionality

### v0.4.0
- transferred the module to the new jxMono organization
- updated Bind to `v0.4.0`, Events to `v0.4.0`

### v0.3.9
- Clear the existing hidden inputs when `setData` is called

### v0.3.8
- `removeItem` client function can receive object as parameter

### v0.3.7
- Added `removeFileEvent` remove operation event

### v0.3.6
- Updated to Bind `v0.3.2`

### v0.3.5
- catching server side errors during upload
- added `uploadFile` event
- fixed IE upload problem (IFRAME does not understand application/json content type)

### v0.3.3
- piping downloaded files

### v0.3.2
- checking if file exists for download

### v0.3.1
- Updated to Bind `v0.3.1`

### v0.3.0
- Updated deps

### v0.2.1
- Added custom handler support for the file path in the download operation
- Removed the `Content-Disposition` `attachment` directive for the download operation
- Removed the `text/csv` `Content-Type` from the download operation

### v0.1.8
- Moved the `fileUploaded` event emit higher in the code

### v0.1.7
- Check the file size when uploading a file

### v0.1.6
- Update to Events v0.1.11

### v0.1.5
- `acceptTypes` options (both client and server) if not present, allows any file type uploads
- add new features and fixed here
- Update to Events v0.1.10
- Update to Bind v0.2.2

### v0.1.4
- Update to Events v0.1.8

### v0.1.3
- `acceptTypes` configuration and param fields
- Update to Bind v0.2.1

### v0.1.2
- Update to Events v0.1.7

### v0.1.1
- Don't emit `fileUploaded` if no file was selected in the file input

### v0.1.0
- initial version


text:
```c
From patchwork Thu Dec  3 12:18:36 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Yifei Jiang <jiangyifei@huawei.com>
X-Patchwork-Id: 11948603
Return-Path: <kvm-owner@kernel.org>
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
	aws-us-west-2-korg-lkml-1.web.codeaurora.org
X-Spam-Level:
X-Spam-Status: No, score=-11.8 required=3.0 tests=BAYES_00,
	HEADER_FROM_DIFFERENT_DOMAINS,INCLUDES_PATCH,MAILING_LIST_MULTI,SPF_HELO_NONE,
	SPF_PASS,USER_AGENT_GIT autolearn=ham autolearn_force=no version=3.4.0
Received: from mail.kernel.org (mail.kernel.org [198.145.29.99])
	by smtp.lore.kernel.org (Postfix) with ESMTP id 6333AC64E8A
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 12:22:18 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [23.128.96.18])
	by mail.kernel.org (Postfix) with ESMTP id 0F9CE22241
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 12:22:17 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1730452AbgLCMVy (ORCPT <rfc822;kvm@archiver.kernel.org>);
        Thu, 3 Dec 2020 07:21:54 -0500
Received: from szxga05-in.huawei.com ([45.249.212.191]:9099 "EHLO
        szxga05-in.huawei.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org
        with ESMTP id S1726157AbgLCMVy (ORCPT <rfc822;kvm@vger.kernel.org>);
        Thu, 3 Dec 2020 07:21:54 -0500
Received: from DGGEMS406-HUB.china.huawei.com (unknown [172.30.72.60])
        by szxga05-in.huawei.com (SkyGuard) with ESMTP id 4Cmw0N6bBrzLyy0;
        Thu,  3 Dec 2020 20:20:36 +0800 (CST)
Received: from huawei.com (10.174.186.236) by DGGEMS406-HUB.china.huawei.com
 (10.3.19.206) with Microsoft SMTP Server id 14.3.487.0; Thu, 3 Dec 2020
 20:21:02 +0800
From: Yifei Jiang <jiangyifei@huawei.com>
To: <anup.patel@wdc.com>, <atish.patra@wdc.com>,
        <paul.walmsley@sifive.com>, <palmer@dabbelt.com>,
        <aou@eecs.berkeley.edu>, <pbonzini@redhat.com>
CC: <kvm-riscv@lists.infradead.org>, <kvm@vger.kernel.org>,
        <linux-riscv@lists.infradead.org>, <linux-kernel@vger.kernel.org>,
        <victor.zhangxiaofeng@huawei.com>, <wu.wubin@huawei.com>,
        <zhang.zhanghailiang@huawei.com>, <dengkai1@huawei.com>,
        <yinyipeng1@huawei.com>, Yifei Jiang <jiangyifei@huawei.com>
Subject: [PATCH RFC 0/3] Implement guest time scaling in RISC-V KVM
Date: Thu, 3 Dec 2020 20:18:36 +0800
Message-ID: <20201203121839.308-1-jiangyifei@huawei.com>
X-Mailer: git-send-email 2.26.2.windows.1
MIME-Version: 1.0
X-Originating-IP: [10.174.186.236]
X-CFilter-Loop: Reflected
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

This series implements guest time scaling based on RDTIME instruction
emulation so that we can allow migrating Guest/VM across Hosts with
different time frequency.

Why not through para-virt. From arm's experience[1], para-virt implementation
doesn't really solve the problem for the following two main reasons:
- RDTIME not only be used in linux, but also in firmware and userspace.
- It is difficult to be compatible with nested virtualization.

[1] https://lore.kernel.org/patchwork/cover/1288153/

Yifei Jiang (3):
  RISC-V: KVM: Change the method of calculating cycles to nanoseconds
  RISC-V: KVM: Support dynamic time frequency from userspace
  RISC-V: KVM: Implement guest time scaling

 arch/riscv/include/asm/csr.h            |  3 ++
 arch/riscv/include/asm/kvm_vcpu_timer.h | 13 +++++--
 arch/riscv/kvm/vcpu_exit.c              | 35 +++++++++++++++++
 arch/riscv/kvm/vcpu_timer.c             | 51 ++++++++++++++++++++++---
 4 files changed, 93 insertions(+), 9 deletions(-)
```
#### [PATCH RFC v4 00/15] Add riscv kvm accel support
##### From: Yifei Jiang <jiangyifei@huawei.com>

```c
From patchwork Thu Dec  3 12:46:48 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Yifei Jiang <jiangyifei@huawei.com>
X-Patchwork-Id: 11948657
Return-Path: <kvm-owner@kernel.org>
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
	aws-us-west-2-korg-lkml-1.web.codeaurora.org
X-Spam-Level:
X-Spam-Status: No, score=-16.7 required=3.0 tests=BAYES_00,
	HEADER_FROM_DIFFERENT_DOMAINS,INCLUDES_PATCH,MAILING_LIST_MULTI,
	MENTIONS_GIT_HOSTING,SPF_HELO_NONE,SPF_PASS,URIBL_BLOCKED,USER_AGENT_GIT
	autolearn=ham autolearn_force=no version=3.4.0
Received: from mail.kernel.org (mail.kernel.org [198.145.29.99])
	by smtp.lore.kernel.org (Postfix) with ESMTP id 974ADC83014
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 12:48:25 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [23.128.96.18])
	by mail.kernel.org (Postfix) with ESMTP id 5443F20709
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 12:48:25 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1730407AbgLCMsI (ORCPT <rfc822;kvm@archiver.kernel.org>);
        Thu, 3 Dec 2020 07:48:08 -0500
Received: from szxga04-in.huawei.com ([45.249.212.190]:8626 "EHLO
        szxga04-in.huawei.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org
        with ESMTP id S1730384AbgLCMsH (ORCPT <rfc822;kvm@vger.kernel.org>);
        Thu, 3 Dec 2020 07:48:07 -0500
Received: from DGGEMS403-HUB.china.huawei.com (unknown [172.30.72.60])
        by szxga04-in.huawei.com (SkyGuard) with ESMTP id 4CmwZk4sJMz15Wyc;
        Thu,  3 Dec 2020 20:46:54 +0800 (CST)
Received: from huawei.com (10.174.186.236) by DGGEMS403-HUB.china.huawei.com
 (10.3.19.203) with Microsoft SMTP Server id 14.3.487.0; Thu, 3 Dec 2020
 20:47:12 +0800
From: Yifei Jiang <jiangyifei@huawei.com>
To: <qemu-devel@nongnu.org>, <qemu-riscv@nongnu.org>
CC: <kvm-riscv@lists.infradead.org>, <kvm@vger.kernel.org>,
        <libvir-list@redhat.com>, <anup.patel@wdc.com>,
        <palmer@dabbelt.com>, <Alistair.Francis@wdc.com>,
        <sagark@eecs.berkeley.edu>, <kbastian@mail.uni-paderborn.de>,
        <victor.zhangxiaofeng@huawei.com>, <wu.wubin@huawei.com>,
        <zhang.zhanghailiang@huawei.com>, <dengkai1@huawei.com>,
        <yinyipeng1@huawei.com>, Yifei Jiang <jiangyifei@huawei.com>
Subject: [PATCH RFC v4 00/15] Add riscv kvm accel support
Date: Thu, 3 Dec 2020 20:46:48 +0800
Message-ID: <20201203124703.168-1-jiangyifei@huawei.com>
X-Mailer: git-send-email 2.26.2.windows.1
MIME-Version: 1.0
X-Originating-IP: [10.174.186.236]
X-CFilter-Loop: Reflected
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

This series adds both riscv32 and riscv64 kvm support, and implements
migration based on riscv. It is based on temporarily unaccepted kvm:
https://github.com/kvm-riscv/linux (lastest version v15).

This series depends on above pending changes which haven't yet been
accepted, so this QEMU patch series is treated as RFC patches until
that dependency has been dealt with.

Compared to RFC v3, the time scaling is supported in this series. The
new feature also requires the following patches:
[1] Bugfix in kvm v15
https://lkml.org/lkml/2020/11/30/245
[2] kvm patches:
[PATCH RFC 0/3] Implement guest time scaling in RISC-V KVM

Several steps to use this:
1. Build emulation
$ ./configure --target-list=riscv64-softmmu
$ make -j$(nproc)

2. Build kernel
https://github.com/kvm-riscv/linux

3. Build QEMU VM
Cross built in riscv toolchain.
$ PKG_CONFIG_LIBDIR=<toolchain pkgconfig path>
$ export PKG_CONFIG_SYSROOT_DIR=<toolchain sysroot path>
$ ./configure --target-list=riscv64-softmmu --enable-kvm \
--cross-prefix=riscv64-linux-gnu- --disable-libiscsi --disable-glusterfs \
--disable-libusb --disable-usb-redir --audio-drv-list= --disable-opengl \
--disable-libxml2
$ make -j$(nproc)

4. Start emulation
$ ./qemu-system-riscv64 -M virt -m 4096M -cpu rv64,x-h=true -nographic \
        -name guest=riscv-hyp,debug-threads=on \
        -smp 4 \
        -bios ./fw_jump.bin \
        -kernel ./Image \
        -drive file=./hyp.img,format=raw,id=hd0 \
        -device virtio-blk-device,drive=hd0 \
        -append "root=/dev/vda rw console=ttyS0 earlycon=sbi"

5. Start kvm-acceled QEMU VM in emulation
$ ./qemu-system-riscv64 -M virt,accel=kvm -m 1024M -cpu host -nographic \
        -name guest=riscv-guset \
        -smp 2 \
        -bios none \
        -kernel ./Image \
        -drive file=./guest.img,format=raw,id=hd0 \
        -device virtio-blk-device,drive=hd0 \
        -append "root=/dev/vda rw console=ttyS0 earlycon=sbi"

Changes since RFC v3
- Rebase on QEMU v5.2.0-rc2 and kvm-riscv linux v15.
- Add time scaling support(New patches 13, 14 and 15).
- Fix the bug that guest vm can't reboot.

Changes since RFC v2
- Fix checkpatch error at target/riscv/sbi_ecall_interface.h.
- Add riscv migration support.

Changes since RFC v1
- Add separate SBI ecall interface header.
- Add riscv32 kvm accel support.

Yifei Jiang (15):
  linux-header: Update linux/kvm.h
  target/riscv: Add target/riscv/kvm.c to place the public kvm interface
  target/riscv: Implement function kvm_arch_init_vcpu
  target/riscv: Implement kvm_arch_get_registers
  target/riscv: Implement kvm_arch_put_registers
  target/riscv: Support start kernel directly by KVM
  hw/riscv: PLIC update external interrupt by KVM when kvm enabled
  target/riscv: Handle KVM_EXIT_RISCV_SBI exit
  target/riscv: Add host cpu type
  target/riscv: Add kvm_riscv_get/put_regs_timer
  target/riscv: Implement virtual time adjusting with vm state changing
  target/riscv: Support virtual time context synchronization
  target/riscv: Introduce dynamic time frequency for virt machine
  target/riscv: Synchronize vcpu's frequency with KVM
  target/riscv: Add time frequency migration support

 hw/intc/sifive_plic.c              |  31 +-
 hw/riscv/virt.c                    |  26 +-
 linux-headers/linux/kvm.h          |   8 +
 meson.build                        |   2 +
 target/riscv/cpu.c                 |  13 +
 target/riscv/cpu.h                 |  12 +
 target/riscv/kvm.c                 | 617 +++++++++++++++++++++++++++++
 target/riscv/kvm_riscv.h           |  25 ++
 target/riscv/machine.c             |  23 ++
 target/riscv/meson.build           |   1 +
 target/riscv/sbi_ecall_interface.h |  72 ++++
 11 files changed, 817 insertions(+), 13 deletions(-)
 create mode 100644 target/riscv/kvm.c
 create mode 100644 target/riscv/kvm_riscv.h
 create mode 100644 target/riscv/sbi_ecall_interface.h
```
#### [PATCH 0/1] Fix for a recent regression in kvm/queue (guest using
##### From: Maxim Levitsky <mlevitsk@redhat.com>

```c
From patchwork Thu Dec  3 14:33:18 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Maxim Levitsky <mlevitsk@redhat.com>
X-Patchwork-Id: 11948963
Return-Path: <kvm-owner@kernel.org>
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
	aws-us-west-2-korg-lkml-1.web.codeaurora.org
X-Spam-Level:
X-Spam-Status: No, score=-12.2 required=3.0 tests=BAYES_00,DKIMWL_WL_HIGH,
	DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS,
	INCLUDES_PATCH,MAILING_LIST_MULTI,SPF_HELO_NONE,SPF_PASS
	autolearn=unavailable autolearn_force=no version=3.4.0
Received: from mail.kernel.org (mail.kernel.org [198.145.29.99])
	by smtp.lore.kernel.org (Postfix) with ESMTP id 820D5C4361A
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 14:51:34 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [23.128.96.18])
	by mail.kernel.org (Postfix) with ESMTP id D6AE622293
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 14:35:20 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S2436525AbgLCOez (ORCPT <rfc822;kvm@archiver.kernel.org>);
        Thu, 3 Dec 2020 09:34:55 -0500
Received: from us-smtp-delivery-124.mimecast.com ([216.205.24.124]:57266 "EHLO
        us-smtp-delivery-124.mimecast.com" rhost-flags-OK-OK-OK-OK)
        by vger.kernel.org with ESMTP id S1728159AbgLCOez (ORCPT
        <rfc822;kvm@vger.kernel.org>); Thu, 3 Dec 2020 09:34:55 -0500
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com;
        s=mimecast20190719; t=1607006009;
        h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
         to:to:cc:cc:mime-version:mime-version:
         content-transfer-encoding:content-transfer-encoding;
        bh=6smsIvjf77OYufhjM+C0nrIBQuuSFafCoX7/LBefMiM=;
        b=gULYPi1uPCVBZnRipEt/DTz9hk356RosnjManBt2OlMXsHldmMwq6DCD2X2zoqHWupMyjO
        B5urZ28cLHZJHSgH5T6NofDAjDgHCcoaOg+ZBRfL0d12VcD92CQTcIR2LKYwDeHmPKXvxc
        Hy5lNo30+fJ4i2F6LGIN2wMMf3d6Pkw=
Received: from mimecast-mx01.redhat.com (mimecast-mx01.redhat.com
 [209.132.183.4]) (Using TLS) by relay.mimecast.com with ESMTP id
 us-mta-365-AOBA8ru4POGmZP_E6v16cw-1; Thu, 03 Dec 2020 09:33:27 -0500
X-MC-Unique: AOBA8ru4POGmZP_E6v16cw-1
Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.phx2.redhat.com
 [10.5.11.11])
        (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits))
        (No client certificate requested)
        by mimecast-mx01.redhat.com (Postfix) with ESMTPS id 716B315822E;
        Thu,  3 Dec 2020 14:33:25 +0000 (UTC)
Received: from localhost.localdomain (unknown [10.35.206.228])
        by smtp.corp.redhat.com (Postfix) with ESMTP id E723A18A60;
        Thu,  3 Dec 2020 14:33:20 +0000 (UTC)
From: Maxim Levitsky <mlevitsk@redhat.com>
To: kvm@vger.kernel.org
Cc: Sean Christopherson <sean.j.christopherson@intel.com>,
        Joerg Roedel <joro@8bytes.org>, Ingo Molnar <mingo@redhat.com>,
        x86@kernel.org (maintainer:X86 ARCHITECTURE (32-BIT AND 64-BIT)),
        "H. Peter Anvin" <hpa@zytor.com>,
        Vitaly Kuznetsov <vkuznets@redhat.com>,
        Paolo Bonzini <pbonzini@redhat.com>,
        Borislav Petkov <bp@alien8.de>,
        Jim Mattson <jmattson@google.com>,
        Wanpeng Li <wanpengli@tencent.com>,
        linux-kernel@vger.kernel.org, Thomas Gleixner <tglx@linutronix.de>,
        Maxim Levitsky <mlevitsk@redhat.com>
Subject: [PATCH 0/1] Fix for a recent regression in kvm/queue (guest using
 100% cpu time)
Date: Thu,  3 Dec 2020 16:33:18 +0200
Message-Id: <20201203143319.159394-1-mlevitsk@redhat.com>
MIME-Version: 1.0
X-Scanned-By: MIMEDefang 2.79 on 10.5.11.11
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

I did a quick bisect yesterday after noticing that my VMs started
to take 100% cpu time.

Looks like we don't ignore SIPIs that are received while the CPU isn't
waiting for them, and that makes KVM think that CPU always has
pending events which makes it never enter an idle state.

Best regards,
	Maxim Levitsky

Maxim Levitsky (1):
  KVM: x86: ignore SIPIs that are received while not in wait-for-sipi
    state

 arch/x86/kvm/lapic.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
```
#### [PATCH v2 0/3] RFC: Precise TSC migration
##### From: Maxim Levitsky <mlevitsk@redhat.com>

```c
From patchwork Thu Dec  3 17:11:15 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Maxim Levitsky <mlevitsk@redhat.com>
X-Patchwork-Id: 11949163
Return-Path: <kvm-owner@kernel.org>
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
	aws-us-west-2-korg-lkml-1.web.codeaurora.org
X-Spam-Level:
X-Spam-Status: No, score=-12.2 required=3.0 tests=BAYES_00,DKIMWL_WL_HIGH,
	DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS,
	INCLUDES_PATCH,MAILING_LIST_MULTI,SPF_HELO_NONE,SPF_PASS,URIBL_BLOCKED
	autolearn=unavailable autolearn_force=no version=3.4.0
Received: from mail.kernel.org (mail.kernel.org [198.145.29.99])
	by smtp.lore.kernel.org (Postfix) with ESMTP id D9508C0018C
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 17:13:28 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [23.128.96.18])
	by mail.kernel.org (Postfix) with ESMTP id 53F9E207AE
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 17:13:28 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1728633AbgLCRN0 (ORCPT <rfc822;kvm@archiver.kernel.org>);
        Thu, 3 Dec 2020 12:13:26 -0500
Received: from us-smtp-delivery-124.mimecast.com ([63.128.21.124]:53421 "EHLO
        us-smtp-delivery-124.mimecast.com" rhost-flags-OK-OK-OK-OK)
        by vger.kernel.org with ESMTP id S2501942AbgLCRNY (ORCPT
        <rfc822;kvm@vger.kernel.org>); Thu, 3 Dec 2020 12:13:24 -0500
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com;
        s=mimecast20190719; t=1607015518;
        h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
         to:to:cc:cc:mime-version:mime-version:
         content-transfer-encoding:content-transfer-encoding;
        bh=zaqAemO/Fsujg9r8lt/SFqF1ctdGuOQUqsO5lgI9LxY=;
        b=eapRq1a/cEDgA0rlGekknwtGedJqPGEcwuF08WAje/e7/Q0c3mCr2p3nHuSAtCYk7tch61
        vhOX38J70DdI2K/Wv6dDcdeCyaAqbTKitwotK8HCJQAhKsnLYRIYwpARxIw9e4JZ7ETzDm
        LvrKY4WFdLnX03Mxtp+LYPVjFFyfvtg=
Received: from mimecast-mx01.redhat.com (mimecast-mx01.redhat.com
 [209.132.183.4]) (Using TLS) by relay.mimecast.com with ESMTP id
 us-mta-474-6I46_4btNSS0GSJXwwek_Q-1; Thu, 03 Dec 2020 12:11:55 -0500
X-MC-Unique: 6I46_4btNSS0GSJXwwek_Q-1
Received: from smtp.corp.redhat.com (int-mx03.intmail.prod.int.phx2.redhat.com
 [10.5.11.13])
        (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits))
        (No client certificate requested)
        by mimecast-mx01.redhat.com (Postfix) with ESMTPS id 51CEC180A089;
        Thu,  3 Dec 2020 17:11:27 +0000 (UTC)
Received: from localhost.localdomain (unknown [10.35.206.228])
        by smtp.corp.redhat.com (Postfix) with ESMTP id 2475A6F963;
        Thu,  3 Dec 2020 17:11:19 +0000 (UTC)
From: Maxim Levitsky <mlevitsk@redhat.com>
To: kvm@vger.kernel.org
Cc: "H. Peter Anvin" <hpa@zytor.com>,
        Paolo Bonzini <pbonzini@redhat.com>,
        Jonathan Corbet <corbet@lwn.net>,
        Jim Mattson <jmattson@google.com>,
        Wanpeng Li <wanpengli@tencent.com>,
        linux-kselftest@vger.kernel.org (open list:KERNEL SELFTEST FRAMEWORK),
        Vitaly Kuznetsov <vkuznets@redhat.com>,
        Marcelo Tosatti <mtosatti@redhat.com>,
        Thomas Gleixner <tglx@linutronix.de>,
        Sean Christopherson <sean.j.christopherson@intel.com>,
        linux-kernel@vger.kernel.org (open list),
        Ingo Molnar <mingo@redhat.com>,
        x86@kernel.org (maintainer:X86 ARCHITECTURE (32-BIT AND 64-BIT)),
        Joerg Roedel <joro@8bytes.org>, Borislav Petkov <bp@alien8.de>,
        Shuah Khan <shuah@kernel.org>,
        Maxim Levitsky <mlevitsk@redhat.com>,
        Andrew Jones <drjones@redhat.com>,
        Oliver Upton <oupton@google.com>,
        linux-doc@vger.kernel.org (open list:DOCUMENTATION)
Subject: [PATCH v2 0/3] RFC: Precise TSC migration
Date: Thu,  3 Dec 2020 19:11:15 +0200
Message-Id: <20201203171118.372391-1-mlevitsk@redhat.com>
MIME-Version: 1.0
X-Scanned-By: MIMEDefang 2.79 on 10.5.11.13
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

Hi!

This is the second version of the work to make TSC migration more accurate,
as was defined by Paulo at:
https://www.spinics.net/lists/kvm/msg225525.html

I omitted most of the semi-offtopic points I raised related to TSC
in the previous RFC where we can continue the discussion.

I do want to raise another thing that I almost forgot.

On AMD systems, the Linux kernel will mark the guest tsc as
unstable unless invtsc is set which is set on recent AMD
hardware.

Take a look at 'unsynchronized_tsc()' to verify this.

This is another thing that IMHO should be fixed at least when
running under KVM.

Note that I forgot to mention that
X86_FEATURE_TSC_RELIABLE also short-circuits this code,
thus giving another reason to enable it under KVM.

Changes from V1:

- added KVM_TSC_STATE_TIMESTAMP_VALID instead of testing ns == 0
- allow diff < 0, because it is still better that capping it to 0
- updated tsc_msr_test unit test to cover this feature
- refactoring

Patches to enable this feature in qemu are in the process of
being sent to qemu-devel mailing list.

Best regards,
    Maxim Levitsky

Maxim Levitsky (3):
  KVM: x86: implement KVM_{GET|SET}_TSC_STATE
  KVM: x86: introduce KVM_X86_QUIRK_TSC_HOST_ACCESS
  kvm/selftests: update tsc_msrs_test to cover
    KVM_X86_QUIRK_TSC_HOST_ACCESS

 Documentation/virt/kvm/api.rst                | 65 +++++++++++++
 arch/x86/include/uapi/asm/kvm.h               |  1 +
 arch/x86/kvm/x86.c                            | 92 ++++++++++++++++++-
 include/uapi/linux/kvm.h                      | 15 +++
 .../selftests/kvm/x86_64/tsc_msrs_test.c      | 79 ++++++++++++++--
 5 files changed, 237 insertions(+), 15 deletions(-)
```
#### [PATCH v2 0/2] RFC: Precise TSC migration
##### From: Maxim Levitsky <mlevitsk@redhat.com>

```c
From patchwork Thu Dec  3 17:15:44 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Maxim Levitsky <mlevitsk@redhat.com>
X-Patchwork-Id: 11949183
Return-Path: <kvm-owner@kernel.org>
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
	aws-us-west-2-korg-lkml-1.web.codeaurora.org
X-Spam-Level:
X-Spam-Status: No, score=-12.2 required=3.0 tests=BAYES_00,DKIMWL_WL_HIGH,
	DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS,
	INCLUDES_PATCH,MAILING_LIST_MULTI,SPF_HELO_NONE,SPF_PASS autolearn=ham
	autolearn_force=no version=3.4.0
Received: from mail.kernel.org (mail.kernel.org [198.145.29.99])
	by smtp.lore.kernel.org (Postfix) with ESMTP id C12A5C433FE
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 17:17:42 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [23.128.96.18])
	by mail.kernel.org (Postfix) with ESMTP id 608AE207AF
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 17:17:42 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1731535AbgLCRR0 (ORCPT <rfc822;kvm@archiver.kernel.org>);
        Thu, 3 Dec 2020 12:17:26 -0500
Received: from us-smtp-delivery-124.mimecast.com ([63.128.21.124]:44840 "EHLO
        us-smtp-delivery-124.mimecast.com" rhost-flags-OK-OK-OK-OK)
        by vger.kernel.org with ESMTP id S1726840AbgLCRRY (ORCPT
        <rfc822;kvm@vger.kernel.org>); Thu, 3 Dec 2020 12:17:24 -0500
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com;
        s=mimecast20190719; t=1607015757;
        h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
         to:to:cc:cc:mime-version:mime-version:
         content-transfer-encoding:content-transfer-encoding;
        bh=cR3WCJq9d7LvMDlf7M0tIlYK9KyXcPJkybrgmwJqmcM=;
        b=ESZ2rLiE7RBB4RMYrrPjdRZy1yD4vyl3qnN/WfyYBFRJ0y8te99/ePSTu8VH3XYvZ64OSS
        H9hC6NjNDO/wjyuhMAH4/XAyAxrmaBfuhs5b2CWRGLKoQQArL4xdw+QoS5ccwM8XYVx2Fk
        8QbOpC6Xy9Xcan/GcHWhOVIZ3ugztV4=
Received: from mimecast-mx01.redhat.com (mimecast-mx01.redhat.com
 [209.132.183.4]) (Using TLS) by relay.mimecast.com with ESMTP id
 us-mta-490-tW323KgXM-6_kPnBfxoCwQ-1; Thu, 03 Dec 2020 12:15:56 -0500
X-MC-Unique: tW323KgXM-6_kPnBfxoCwQ-1
Received: from smtp.corp.redhat.com (int-mx05.intmail.prod.int.phx2.redhat.com
 [10.5.11.15])
        (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits))
        (No client certificate requested)
        by mimecast-mx01.redhat.com (Postfix) with ESMTPS id 979AB858180;
        Thu,  3 Dec 2020 17:15:54 +0000 (UTC)
Received: from localhost.localdomain (unknown [10.35.206.228])
        by smtp.corp.redhat.com (Postfix) with ESMTP id 084AC5D6AC;
        Thu,  3 Dec 2020 17:15:47 +0000 (UTC)
From: Maxim Levitsky <mlevitsk@redhat.com>
To: qemu-devel@nongnu.org
Cc: Paolo Bonzini <pbonzini@redhat.com>,
        "Michael S. Tsirkin" <mst@redhat.com>,
        Marcelo Tosatti <mtosatti@redhat.com>,
        Eduardo Habkost <ehabkost@redhat.com>, kvm@vger.kernel.org,
        Richard Henderson <richard.henderson@linaro.org>,
        Cornelia Huck <cohuck@redhat.com>,
        Maxim Levitsky <mlevitsk@redhat.com>
Subject: [PATCH v2 0/2] RFC: Precise TSC migration
Date: Thu,  3 Dec 2020 19:15:44 +0200
Message-Id: <20201203171546.372686-1-mlevitsk@redhat.com>
MIME-Version: 1.0
X-Scanned-By: MIMEDefang 2.79 on 10.5.11.15
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

Note that to use this feature you need the kernel patches which are
posted to LKML and kvm@vger.kernel.org

The feature is disabled by default, and can be enabled with
-accel kvm,x-precise-tsc=on.

I changed the TSC and TSC adjust read/write code to go though a special
function kvm_get_tsc/kvm_set_tsc regardless of enablement of this feature.

The side effect of this is that now we upload to the kernel the TSC_ADJUST
msr only on KVM_PUT_RESET_STATE reset level.
This shouldn't matter as I don't think that qemu changes this msr on its own.

For migration I added a new state field 'cpu/tsc_ns_timestamp',
where I save the TSC nanosecond timestamp, which is the only
new thing that was added to the migration state.

First patch in this series is temporary and it just updates the kernel
headers to make qemu compile.

When the feature is merged to the kernel, a kernel header sync will bring
the same changes to the qemu, making this patch unnecessary.

V2:

- switched to -accel for enablement
- sync with updated kernel patches
- minor cleanups, renames, etc

Best regards,
    Maxim Levitsky

Maxim Levitsky (2):
  Update the kernel headers for 5.10-rc5 + TSC
  Implement support for precise TSC migration

 accel/kvm/kvm-all.c                         |  28 ++++
 include/standard-headers/asm-x86/kvm_para.h |   1 +
 include/sysemu/kvm.h                        |   1 +
 linux-headers/asm-x86/kvm.h                 |   2 +
 linux-headers/linux/kvm.h                   |  71 +++++++++-
 target/i386/cpu.h                           |   1 +
 target/i386/kvm.c                           | 140 ++++++++++++++++----
 target/i386/machine.c                       |  19 +++
 8 files changed, 234 insertions(+), 29 deletions(-)
```
#### [PATCH v3 0/2] Connect request callback to mdev and vfio-ccw
##### From: Eric Farman <farman@linux.ibm.com>

```c
From patchwork Thu Dec  3 21:35:10 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Eric Farman <farman@linux.ibm.com>
X-Patchwork-Id: 11949675
Return-Path: <kvm-owner@kernel.org>
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
	aws-us-west-2-korg-lkml-1.web.codeaurora.org
X-Spam-Level:
X-Spam-Status: No, score=-11.8 required=3.0 tests=BAYES_00,DKIM_SIGNED,
	DKIM_VALID,HEADER_FROM_DIFFERENT_DOMAINS,INCLUDES_PATCH,MAILING_LIST_MULTI,
	SPF_HELO_NONE,SPF_PASS,USER_AGENT_GIT autolearn=ham autolearn_force=no
	version=3.4.0
Received: from mail.kernel.org (mail.kernel.org [198.145.29.99])
	by smtp.lore.kernel.org (Postfix) with ESMTP id 957D3C4361B
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 21:36:07 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [23.128.96.18])
	by mail.kernel.org (Postfix) with ESMTP id 4D09E22473
	for <kvm@archiver.kernel.org>; Thu,  3 Dec 2020 21:36:07 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1728923AbgLCVgG (ORCPT <rfc822;kvm@archiver.kernel.org>);
        Thu, 3 Dec 2020 16:36:06 -0500
Received: from mx0b-001b2d01.pphosted.com ([148.163.158.5]:62368 "EHLO
        mx0a-001b2d01.pphosted.com" rhost-flags-OK-OK-OK-FAIL)
        by vger.kernel.org with ESMTP id S1728252AbgLCVgF (ORCPT
        <rfc822;kvm@vger.kernel.org>); Thu, 3 Dec 2020 16:36:05 -0500
Received: from pps.filterd (m0098414.ppops.net [127.0.0.1])
        by mx0b-001b2d01.pphosted.com (8.16.0.42/8.16.0.42) with SMTP id
 0B3LYXo3027151;
        Thu, 3 Dec 2020 16:35:21 -0500
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=ibm.com;
 h=from : to : cc : subject
 : date : message-id; s=pp1;
 bh=202NPPv11LZXskIKT2kUmTrWRL/sWF+vMp8dh5k9rv0=;
 b=Bd8H4QiwsZlIGgF+2kDRPYFgpigqbB/0dK2kL41Xqo0c+/AIkzORBPjxi2iTn43RE0MC
 Q0IF81AYEdunv3i3MaepVWAu0VOCrA2G7/jXk4ODWI2Cboq5zNTOcauDm7qtAVyr3CPw
 fEJQeYpBuEV0T7b/nzKtqQ0ZHHPWLo8XGXJNS/QUqTJRj61hC3kOdLVaNi+Whu6QEKvW
 FE2w11BNI1kfUAbQVLzJ9hKF8xT9ItVF9FV/CD71AUBtWcygowyCrtUK6IBvNDeE+4+D
 DtqAikB6qRhp9tmtQp2BGuGgJtlFbf8PYDvD+NCwpmAMoz4ddQUuB5PVqluOmVqjmKX9 0g==
Received: from pps.reinject (localhost [127.0.0.1])
        by mx0b-001b2d01.pphosted.com with ESMTP id 35775csgqa-1
        (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256
 verify=NOT);
        Thu, 03 Dec 2020 16:35:20 -0500
Received: from m0098414.ppops.net (m0098414.ppops.net [127.0.0.1])
        by pps.reinject (8.16.0.36/8.16.0.36) with SMTP id 0B3LYcMA027701;
        Thu, 3 Dec 2020 16:35:20 -0500
Received: from ppma03ams.nl.ibm.com (62.31.33a9.ip4.static.sl-reverse.com
 [169.51.49.98])
        by mx0b-001b2d01.pphosted.com with ESMTP id 35775csgpm-1
        (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256
 verify=NOT);
        Thu, 03 Dec 2020 16:35:20 -0500
Received: from pps.filterd (ppma03ams.nl.ibm.com [127.0.0.1])
        by ppma03ams.nl.ibm.com (8.16.0.42/8.16.0.42) with SMTP id
 0B3LW8aq021225;
        Thu, 3 Dec 2020 21:35:18 GMT
Received: from b06cxnps4075.portsmouth.uk.ibm.com
 (d06relay12.portsmouth.uk.ibm.com [9.149.109.197])
        by ppma03ams.nl.ibm.com with ESMTP id 3573v9r67q-1
        (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256
 verify=NOT);
        Thu, 03 Dec 2020 21:35:18 +0000
Received: from d06av26.portsmouth.uk.ibm.com (d06av26.portsmouth.uk.ibm.com
 [9.149.105.62])
        by b06cxnps4075.portsmouth.uk.ibm.com (8.14.9/8.14.9/NCO v10.0) with
 ESMTP id 0B3LZFed1835584
        (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-GCM-SHA384 bits=256
 verify=OK);
        Thu, 3 Dec 2020 21:35:15 GMT
Received: from d06av26.portsmouth.uk.ibm.com (unknown [127.0.0.1])
        by IMSVA (Postfix) with ESMTP id B3B0AAE053;
        Thu,  3 Dec 2020 21:35:15 +0000 (GMT)
Received: from d06av26.portsmouth.uk.ibm.com (unknown [127.0.0.1])
        by IMSVA (Postfix) with ESMTP id 9E892AE045;
        Thu,  3 Dec 2020 21:35:15 +0000 (GMT)
Received: from tuxmaker.boeblingen.de.ibm.com (unknown [9.152.85.9])
        by d06av26.portsmouth.uk.ibm.com (Postfix) with ESMTPS;
        Thu,  3 Dec 2020 21:35:15 +0000 (GMT)
Received: by tuxmaker.boeblingen.de.ibm.com (Postfix, from userid 4958)
        id 14A8DE01E6; Thu,  3 Dec 2020 22:35:15 +0100 (CET)
From: Eric Farman <farman@linux.ibm.com>
To: Alex Williamson <alex.williamson@redhat.com>,
        Cornelia Huck <cohuck@redhat.com>
Cc: Kirti Wankhede <kwankhede@nvidia.com>,
        Halil Pasic <pasic@linux.ibm.com>,
        Matthew Rosato <mjrosato@linux.ibm.com>,
        linux-s390@vger.kernel.org, kvm@vger.kernel.org,
        Eric Farman <farman@linux.ibm.com>
Subject: [PATCH v3 0/2] Connect request callback to mdev and vfio-ccw
Date: Thu,  3 Dec 2020 22:35:10 +0100
Message-Id: <20201203213512.49357-1-farman@linux.ibm.com>
X-Mailer: git-send-email 2.17.1
X-TM-AS-GCONF: 00
X-Proofpoint-Virus-Version: vendor=fsecure engine=2.50.10434:6.0.312,18.0.737
 definitions=2020-12-03_12:2020-12-03,2020-12-03 signatures=0
X-Proofpoint-Spam-Details: rule=outbound_notspam policy=outbound score=0
 bulkscore=0
 priorityscore=1501 spamscore=0 mlxscore=0 malwarescore=0 adultscore=0
 phishscore=0 lowpriorityscore=0 impostorscore=0 suspectscore=0
 clxscore=1015 mlxlogscore=817 classifier=spam adjust=0 reason=mlx
 scancount=1 engine=8.12.0-2009150000 definitions=main-2012030122
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

Alex,

As promised, here is a v3 with a message indicating a request is blocked
until a user releases the device in question and a corresponding tweak to
the commit message describing this change (and Conny's r-b). The remainder
of the patches are otherwise identical.

v2      : https://lore.kernel.org/kvm/20201120180740.87837-1-farman@linux.ibm.com/
v1(RFC) : https://lore.kernel.org/kvm/20201117032139.50988-1-farman@linux.ibm.com/

Eric Farman (2):
  vfio-mdev: Wire in a request handler for mdev parent
  vfio-ccw: Wire in the request callback

 drivers/s390/cio/vfio_ccw_ops.c     | 26 ++++++++++++++++++++++++++
 drivers/s390/cio/vfio_ccw_private.h |  4 ++++
 drivers/vfio/mdev/mdev_core.c       |  4 ++++
 drivers/vfio/mdev/vfio_mdev.c       | 13 +++++++++++++
 include/linux/mdev.h                |  4 ++++
 include/uapi/linux/vfio.h           |  1 +
 6 files changed, 52 insertions(+)
```


text: Rechtschreibvorschläge für $var['word']


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:background="@color/material_blue_grey_800"
        app:tabIndicatorColor="@color/orange"
        app:tabSelectedTextColor="@color/orange"
        app:tabTextColor="@color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</LinearLayout>


text:
package artifacts

import (
	"testing"

	"google.golang.org/grpc/codes"

	"go.chromium.org/luci/server/span"

	"go.chromium.org/luci/resultdb/internal/invocations"
	"go.chromium.org/luci/resultdb/internal/testutil"
	"go.chromium.org/luci/resultdb/internal/testutil/insert"
	"go.chromium.org/luci/resultdb/pbutil"
	pb "go.chromium.org/luci/resultdb/proto/v1"

	. "github.com/smartystreets/goconvey/convey"
	. "go.chromium.org/luci/common/testing/assertions"
)

func TestQuery(t *testing.T) {
	Convey(`Query`, t, func() {
		ctx := testutil.SpannerTestContext(t)

		testutil.MustApply(ctx, insert.Invocation("inv1", pb.Invocation_ACTIVE, nil))
		q := &Query{
			InvocationIDs:       invocations.NewIDSet("inv1"),
			PageSize:            100,
			TestResultPredicate: &pb.TestResultPredicate{},
			WithRBECASHash:      false,
		}

		mustFetch := func(q *Query) (arts []*pb.Artifact, token string) {
			ctx, cancel := span.ReadOnlyTransaction(ctx)
			defer cancel()
			arts, tok, err := q.FetchProtos(ctx)
			So(err, ShouldBeNil)
			return arts, tok
		}

		mustFetchNames := func(q *Query) []string {
			arts, _ := mustFetch(q)
			names := make([]string, len(arts))
			for i, a := range arts {
				names[i] = a.Name
			}
			return names
		}

		Convey(`Populates fields correctly`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", map[string]interface{}{
					"ContentType": "text/plain",
					"Size":        64,
				}),
			)
			actual, _ := mustFetch(q)
			So(actual, ShouldHaveLength, 1)
			So(actual[0].ContentType, ShouldEqual, "text/plain")
			So(actual[0].SizeBytes, ShouldEqual, 64)
		})

		Convey(`Reads both invocation and test result artifacts`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv1", "tr/t t/r", "a", nil),
			)
			actual := mustFetchNames(q)
			So(actual, ShouldResemble, []string{
				"invocations/inv1/artifacts/a",
				"invocations/inv1/tests/t%20t/results/r/artifacts/a",
			})
		})

		Convey(`Does not fetch artifacts of other invocations`, func() {
			testutil.MustApply(ctx,
				insert.Invocation("inv0", pb.Invocation_ACTIVE, nil),
				insert.Invocation("inv2", pb.Invocation_ACTIVE, nil),
				insert.Artifact("inv0", "", "a", nil),
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv2", "", "a", nil),
			)
			actual := mustFetchNames(q)
			So(actual, ShouldResemble, []string{"invocations/inv1/artifacts/a"})
		})

		Convey(`Test ID regexp`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv1", "tr/t00/r", "a", nil),
				insert.Artifact("inv1", "tr/t10/r", "a", nil),
				insert.Artifact("inv1", "tr/t11/r", "a", nil),
				insert.Artifact("inv1", "tr/t20/r", "a", nil),
			)
			q.TestResultPredicate.TestIdRegexp = "t1."
			actual := mustFetchNames(q)
			So(actual, ShouldResemble, []string{
				"invocations/inv1/artifacts/a",
				"invocations/inv1/tests/t10/results/r/artifacts/a",
				"invocations/inv1/tests/t11/results/r/artifacts/a",
			})
		})

		Convey(`Follow edges`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a0", nil),
				insert.Artifact("inv1", "", "a1", nil),
				insert.Artifact("inv1", "tr/t/r", "a0", nil),
				insert.Artifact("inv1", "tr/t/r", "a1", nil),
			)

			Convey(`Unspecified`, func() {
				actual := mustFetchNames(q)
				So(actual, ShouldResemble, []string{
					"invocations/inv1/artifacts/a0",
					"invocations/inv1/artifacts/a1",
					"invocations/inv1/tests/t/results/r/artifacts/a0",
					"invocations/inv1/tests/t/results/r/artifacts/a1",
				})
			})

			Convey(`Only invocations`, func() {
				q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{
					IncludedInvocations: true,
				}
				actual := mustFetchNames(q)
				So(actual, ShouldResemble, []string{
					"invocations/inv1/artifacts/a0",
					"invocations/inv1/artifacts/a1",
				})

				Convey(`Test result predicate is ignored`, func() {
					q.TestResultPredicate.TestIdRegexp = "t."
					actual := mustFetchNames(q)
					So(actual, ShouldResemble, []string{
						"invocations/inv1/artifacts/a0",
						"invocations/inv1/artifacts/a1",
					})
				})
			})

			Convey(`Only test results`, func() {
				q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{
					TestResults: true,
				}
				actual := mustFetchNames(q)
				So(actual, ShouldResemble, []string{
					"invocations/inv1/tests/t/results/r/artifacts/a0",
					"invocations/inv1/tests/t/results/r/artifacts/a1",
				})
			})

			Convey(`Both`, func() {
				q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{
					IncludedInvocations: true,
					TestResults:         true,
				}
				actual := mustFetchNames(q)
				So(actual, ShouldResemble, []string{
					"invocations/inv1/artifacts/a0",
					"invocations/inv1/artifacts/a1",
					"invocations/inv1/tests/t/results/r/artifacts/a0",
					"invocations/inv1/tests/t/results/r/artifacts/a1",
				})
			})
		})

		Convey(`Artifacts of interesting test results`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv1", "tr/t0/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/1", "a", nil),
				insert.Artifact("inv1", "tr/t1/1", "b", nil),
				insert.Artifact("inv1", "tr/t2/0", "a", nil),
			)
			testutil.MustApply(ctx, testutil.CombineMutations(
				insert.TestResults("inv1", "t0", nil, pb.TestStatus_PASS),
				insert.TestResults("inv1", "t1", nil, pb.TestStatus_PASS, pb.TestStatus_FAIL),
				insert.TestResults("inv1", "t2", nil, pb.TestStatus_FAIL),
			)...)

			q.TestResultPredicate.Expectancy = pb.TestResultPredicate_VARIANTS_WITH_UNEXPECTED_RESULTS
			actual := mustFetchNames(q)
			So(actual, ShouldResemble, []string{
				"invocations/inv1/artifacts/a",
				"invocations/inv1/tests/t1/results/0/artifacts/a",
				"invocations/inv1/tests/t1/results/1/artifacts/a",
				"invocations/inv1/tests/t1/results/1/artifacts/b",
				"invocations/inv1/tests/t2/results/0/artifacts/a",
			})

			Convey(`Without invocation artifacts`, func() {
				q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{TestResults: true}
				actual := mustFetchNames(q)
				So(actual, ShouldNotContain, "invocations/inv1/artifacts/a")
			})
		})

		Convey(`Artifacts of unexpected test results`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv1", "tr/t0/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/1", "a", nil),
				insert.Artifact("inv1", "tr/t1/1", "b", nil),
				insert.Artifact("inv1", "tr/t2/0", "a", nil),
			)
			testutil.MustApply(ctx, testutil.CombineMutations(
				insert.TestResults("inv1", "t0", nil, pb.TestStatus_PASS),
				insert.TestResults("inv1", "t1", nil, pb.TestStatus_PASS, pb.TestStatus_FAIL),
				insert.TestResults("inv1", "t2", nil, pb.TestStatus_FAIL),
			)...)

			q.TestResultPredicate.Expectancy = pb.TestResultPredicate_VARIANTS_WITH_ONLY_UNEXPECTED_RESULTS
			actual := mustFetchNames(q)
			So(actual, ShouldResemble, []string{
				"invocations/inv1/artifacts/a",
				"invocations/inv1/tests/t2/results/0/artifacts/a",
			})

		})

		Convey(`Variant equals`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv1", "tr/t0/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/0", "b", nil),
				insert.Artifact("inv1", "tr/t2/0", "a", nil),
			)
			v1 := pbutil.Variant("k", "1")
			v2 := pbutil.Variant("k", "2")
			testutil.MustApply(ctx, testutil.CombineMutations(
				insert.TestResults("inv1", "t0", v1, pb.TestStatus_PASS),
				insert.TestResults("inv1", "t1", v2, pb.TestStatus_PASS),
				insert.TestResults("inv1", "t2", v1, pb.TestStatus_PASS),
			)...)

			q.TestResultPredicate.Variant = &pb.VariantPredicate{
				Predicate: &pb.VariantPredicate_Equals{Equals: v2},
			}
			So(mustFetchNames(q), ShouldResemble, []string{
				"invocations/inv1/artifacts/a",
				"invocations/inv1/tests/t1/results/0/artifacts/a",
				"invocations/inv1/tests/t1/results/0/artifacts/b",
			})

			Convey(`Without invocation artifacts`, func() {
				q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{TestResults: true}
				actual := mustFetchNames(q)
				So(actual, ShouldNotContain, "invocations/inv1/artifacts/a")
			})
		})

		Convey(`Variant contains`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a", nil),
				insert.Artifact("inv1", "tr/t0/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/0", "a", nil),
				insert.Artifact("inv1", "tr/t1/0", "b", nil),
				insert.Artifact("inv1", "tr/t2/0", "a", nil),
			)
			v00 := pbutil.Variant("k0", "0")
			v01 := pbutil.Variant("k0", "0", "k1", "1")
			v10 := pbutil.Variant("k0", "1")
			testutil.MustApply(ctx, testutil.CombineMutations(
				insert.TestResults("inv1", "t0", v00, pb.TestStatus_PASS),
				insert.TestResults("inv1", "t1", v01, pb.TestStatus_PASS),
				insert.TestResults("inv1", "t2", v10, pb.TestStatus_PASS),
			)...)

			Convey(`Empty`, func() {
				q.TestResultPredicate.Variant = &pb.VariantPredicate{
					Predicate: &pb.VariantPredicate_Contains{Contains: pbutil.Variant()},
				}
				So(mustFetchNames(q), ShouldResemble, []string{
					"invocations/inv1/artifacts/a",
					"invocations/inv1/tests/t0/results/0/artifacts/a",
					"invocations/inv1/tests/t1/results/0/artifacts/a",
					"invocations/inv1/tests/t1/results/0/artifacts/b",
					"invocations/inv1/tests/t2/results/0/artifacts/a",
				})

				Convey(`Without invocation artifacts`, func() {
					q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{TestResults: true}
					actual := mustFetchNames(q)
					So(actual, ShouldNotContain, "invocations/inv1/artifacts/a")
				})
			})

			Convey(`Non-empty`, func() {
				q.TestResultPredicate.Variant = &pb.VariantPredicate{
					Predicate: &pb.VariantPredicate_Contains{Contains: v00},
				}
				So(mustFetchNames(q), ShouldResemble, []string{
					"invocations/inv1/artifacts/a",
					"invocations/inv1/tests/t0/results/0/artifacts/a",
					"invocations/inv1/tests/t1/results/0/artifacts/a",
					"invocations/inv1/tests/t1/results/0/artifacts/b",
				})

				Convey(`Without invocation artifacts`, func() {
					q.FollowEdges = &pb.ArtifactPredicate_EdgeTypeSet{TestResults: true}
					actual := mustFetchNames(q)
					So(actual, ShouldNotContain, "invocations/inv1/artifacts/a")
				})
			})
		})

		Convey(`Paging`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "", "a0", nil),
				insert.Artifact("inv1", "", "a1", nil),
				insert.Artifact("inv1", "", "a2", nil),
				insert.Artifact("inv1", "", "a3", nil),
				insert.Artifact("inv1", "", "a4", nil),
			)

			mustReadPage := func(pageToken string, pageSize int, expectedArtifactIDs ...string) string {
				q2 := *q
				q2.PageToken = pageToken
				q2.PageSize = pageSize
				arts, token := mustFetch(&q2)

				actualArtifactIDs := make([]string, len(arts))
				for i, a := range arts {
					actualArtifactIDs[i] = a.ArtifactId
				}
				So(actualArtifactIDs, ShouldResemble, expectedArtifactIDs)
				return token
			}

			Convey(`All results`, func() {
				token := mustReadPage("", 10, "a0", "a1", "a2", "a3", "a4")
				So(token, ShouldEqual, "")
			})

			Convey(`With pagination`, func() {
				token := mustReadPage("", 1, "a0")
				So(token, ShouldNotEqual, "")

				token = mustReadPage(token, 2, "a1", "a2")
				So(token, ShouldNotEqual, "")

				token = mustReadPage(token, 3, "a3", "a4")
				So(token, ShouldEqual, "")
			})

			Convey(`Bad token`, func() {
				q.PageToken = "CgVoZWxsbw=="
				_, _, err := q.FetchProtos(span.Single(ctx))
				So(err, ShouldHaveAppStatus, codes.InvalidArgument, "invalid page_token")
			})
		})

		Convey(`ContentTypes`, func() {
			Convey(`Works`, func() {
				testutil.MustApply(ctx,
					insert.Artifact("inv1", "", "a0", map[string]interface{}{"ContentType": "text/plain; encoding=utf-8"}),
					insert.Artifact("inv1", "tr/t/r", "a0", map[string]interface{}{"ContentType": "text/plain"}),
					insert.Artifact("inv1", "tr/t/r", "a1", nil),
					insert.Artifact("inv1", "tr/t/r", "a3", map[string]interface{}{"ContentType": "image/jpg"}),
				)
				q.ContentTypeRegexp = "text/.+"

				actual := mustFetchNames(q)
				So(actual, ShouldResemble, []string{
					"invocations/inv1/artifacts/a0",
					"invocations/inv1/tests/t/results/r/artifacts/a0",
				})
			})

			Convey(`Filter generated conditionally`, func() {
				q.ContentTypeRegexp = ""
				st, err := q.genStmt(ctx)
				So(err, ShouldBeNil)
				So(st.SQL, ShouldNotContainSubstring, "@contentTypeRegexp")
			})
		})

		Convey(`ArtifactIds`, func() {
			Convey(`Works`, func() {
				testutil.MustApply(ctx,
					insert.Artifact("inv1", "", "a0", nil),
					insert.Artifact("inv1", "tr/t/r", "a0", nil),
					insert.Artifact("inv1", "tr/t/r", "a1", nil),
					insert.Artifact("inv1", "tr/t/r", "a3", nil),
				)
				q.ArtifactIDRegexp = "a0"

				actual := mustFetchNames(q)
				So(actual, ShouldResemble, []string{
					"invocations/inv1/artifacts/a0",
					"invocations/inv1/tests/t/results/r/artifacts/a0",
				})
			})

			Convey(`Filter generated conditionally`, func() {
				q.ArtifactIDRegexp = ""
				st, err := q.genStmt(ctx)
				So(err, ShouldBeNil)
				So(st.SQL, ShouldNotContainSubstring, "@artifactIdRegexp")
			})
		})

		Convey(`WithRBECASHash`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "tr/t/r", "a", map[string]interface{}{
					"ContentType": "text/plain",
					"Size":        64,
					"RBECASHash":  "deadbeef",
				}),
			)

			q.WithRBECASHash = true
			q.PageSize = 0
			ctx, cancel := span.ReadOnlyTransaction(ctx)
			defer cancel()
			var actual []*Artifact
			err := q.Run(ctx, func(a *Artifact) error {
				actual = append(actual, a)
				return nil
			})
			So(err, ShouldBeNil)
			So(actual, ShouldHaveLength, 1)
			So(actual[0].RBECASHash, ShouldEqual, "deadbeef")
		})

		Convey(`WithGcsURI`, func() {
			testutil.MustApply(ctx,
				insert.Artifact("inv1", "tr/t/r", "a", map[string]interface{}{
					"ContentType": "text/plain",
					"Size":        64,
					"GcsURI":      "gs://bucket/beyondbeef",
				}),
			)

			q.WithGcsURI = true
			q.PageSize = 0
			ctx, cancel := span.ReadOnlyTransaction(ctx)
			defer cancel()
			var actual []*Artifact
			err := q.Run(ctx, func(a *Artifact) error {
				actual = append(actual, a)
				return nil
			})
			So(err, ShouldBeNil)
			So(actual, ShouldHaveLength, 1)
			So(actual[0].GcsUri, ShouldEqual, "gs://bucket/beyondbeef")
		})
	})
}


text:
.class public interface abstract Lorg/apache/http/cookie/ClientCookie;
.super Ljava/lang/Object;
.source "ClientCookie.java"

# interfaces
.implements Lorg/apache/http/cookie/Cookie;

# static fields
.field public static final COMMENTURL_ATTR:Ljava/lang/String; = "commenturl"
    .annotation build Lorg/apache/http/annotation/Obsolete;
    .end annotation
.end field

.field public static final COMMENT_ATTR:Ljava/lang/String; = "comment"
    .annotation build Lorg/apache/http/annotation/Obsolete;
    .end annotation
.end field

.field public static final DISCARD_ATTR:Ljava/lang/String; = "discard"
    .annotation build Lorg/apache/http/annotation/Obsolete;
    .end annotation
.end field

.field public static final DOMAIN_ATTR:Ljava/lang/String; = "domain"

.field public static final EXPIRES_ATTR:Ljava/lang/String; = "expires"

.field public static final MAX_AGE_ATTR:Ljava/lang/String; = "max-age"

.field public static final PATH_ATTR:Ljava/lang/String; = "path"

.field public static final PORT_ATTR:Ljava/lang/String; = "port"
    .annotation build Lorg/apache/http/annotation/Obsolete;
    .end annotation
.end field

.field public static final SECURE_ATTR:Ljava/lang/String; = "secure"

.field public static final VERSION_ATTR:Ljava/lang/String; = "version"
    .annotation build Lorg/apache/http/annotation/Obsolete;
    .end annotation
.end field

# virtual methods
.method public abstract containsAttribute(Ljava/lang/String;)Z
.end method

.method public abstract getAttribute(Ljava/lang/String;)Ljava/lang/String;
.end method


text:
import pytest
from django.contrib.contenttypes.models import ContentType

from ..models import Format

@pytest.fixture
def video_format(local_video):
    return Format.objects.create(
        object_id=local_video.pk,
        content_type=ContentType.objects.get_for_model(local_video),
        field_name='file',
        format='mp4_hd',
        progress=100,
    )

@pytest.mark.django_db
def test_related_manager(local_video):
    assert hasattr(local_video.format_set, 'complete')
    assert hasattr(local_video.format_set, 'in_progress')

@pytest.mark.django_db
def test_in_progress(video_format):
    video_format.progress = 30
    video_format.save()

    assert Format.objects.complete().count() == 0
    assert Format.objects.in_progress().count() == 1
    assert Format.objects.in_progress()[0].progress < 100

@pytest.mark.django_db
def test_complete(video_format):
    assert Format.objects.in_progress().count() == 0
    assert Format.objects.complete().count() == 1
    assert Format.objects.complete()[0].progress == 100


text:
Ports can be specified in an image's manifest. This allows for easy mapping of
ports inside the image to ports on the host, when the app is run in a separate
network namespace, among other uses.

## Subcommands

* `acbuild port add NAME PROTOCOL PORT`

  Updates the image to contain a port with the given name, protocol, and port.
  The protocol is either `udp` or `tcp`. If the port already exists, its values
  will be changed.

* `acbuild port remove NAME/PORT`

  Removes the port with the given name or number from the image.

## Flags

`acbuild port add` supports the following flags when in appc build mode:

- `--count`: when specified, represents a range of ports as opposed to a single
  one. The range starts at the port being added, and has a size of the given
  number.
- `--socket-activated`: when set, the application expects to be socket
  activated on the given ports.

## Examples:

```bash
acbuild port add http tcp 80

acbuild port add dns udp 53

acbuild port remove tftp
```