file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
nat_test.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package big
import (
"io"
"runtime"
"strings"
"testing"
)
var cmpTests = []struct {
x, y nat
r int
}{
{nil, nil, 0},
{nil, nat(nil), 0},
{nat(nil), nil, 0},
{nat(nil), nat(nil), 0},
{nat{0}, nat{0}, 0},
{nat{0}, nat{1}, -1},
{nat{1}, nat{0}, 1},
{nat{1}, nat{1}, 0},
{nat{0, _M}, nat{1}, 1},
{nat{1}, nat{0, _M}, -1},
{nat{1, _M}, nat{0, _M}, 1},
{nat{0, _M}, nat{1, _M}, -1},
{nat{16, 571956, 8794, 68}, nat{837, 9146, 1, 754489}, -1},
{nat{34986, 41, 105, 1957}, nat{56, 7458, 104, 1957}, 1},
}
func TestCmp(t *testing.T) {
for i, a := range cmpTests {
r := a.x.cmp(a.y)
if r != a.r {
t.Errorf("#%d got r = %v; want %v", i, r, a.r)
}
}
}
type funNN func(z, x, y nat) nat
type argNN struct {
z, x, y nat
}
var sumNN = []argNN{
{},
{nat{1}, nil, nat{1}},
{nat{1111111110}, nat{123456789}, nat{987654321}},
{nat{0, 0, 0, 1}, nil, nat{0, 0, 0, 1}},
{nat{0, 0, 0, 1111111110}, nat{0, 0, 0, 123456789}, nat{0, 0, 0, 987654321}},
{nat{0, 0, 0, 1}, nat{0, 0, _M}, nat{0, 0, 1}},
}
var prodNN = []argNN{
{},
{nil, nil, nil},
{nil, nat{991}, nil},
{nat{991}, nat{991}, nat{1}},
{nat{991 * 991}, nat{991}, nat{991}},
{nat{0, 0, 991 * 991}, nat{0, 991}, nat{0, 991}},
{nat{1 * 991, 2 * 991, 3 * 991, 4 * 991}, nat{1, 2, 3, 4}, nat{991}},
{nat{4, 11, 20, 30, 20, 11, 4}, nat{1, 2, 3, 4}, nat{4, 3, 2, 1}},
// 3^100 * 3^28 = 3^128
{
natFromString("11790184577738583171520872861412518665678211592275841109096961"),
natFromString("515377520732011331036461129765621272702107522001"),
natFromString("22876792454961"),
},
// z = 111....1 (70000 digits)
// x = 10^(99*700) + ... + 10^1400 + 10^700 + 1
// y = 111....1 (700 digits, larger than Karatsuba threshold on 32-bit and 64-bit)
{
natFromString(strings.Repeat("1", 70000)),
natFromString("1" + strings.Repeat(strings.Repeat("0", 699)+"1", 99)),
natFromString(strings.Repeat("1", 700)),
},
// z = 111....1 (20000 digits)
// x = 10^10000 + 1
// y = 111....1 (10000 digits)
{
natFromString(strings.Repeat("1", 20000)),
natFromString("1" + strings.Repeat("0", 9999) + "1"),
natFromString(strings.Repeat("1", 10000)),
},
}
func natFromString(s string) nat {
x, _, err := nat(nil).scan(strings.NewReader(s), 0)
if err != nil {
panic(err)
}
return x
}
func TestSet(t *testing.T) {
for _, a := range sumNN {
z := nat(nil).set(a.z)
if z.cmp(a.z) != 0 {
t.Errorf("got z = %v; want %v", z, a.z)
}
}
}
func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
z := f(nil, a.x, a.y)
if z.cmp(a.z) != 0 {
t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, z, a.z)
}
}
func TestFunNN(t *testing.T) {
for _, a := range sumNN {
arg := a
testFunNN(t, "add", nat.add, arg)
arg = argNN{a.z, a.y, a.x}
testFunNN(t, "add symmetric", nat.add, arg)
arg = argNN{a.x, a.z, a.y}
testFunNN(t, "sub", nat.sub, arg)
arg = argNN{a.y, a.z, a.x}
testFunNN(t, "sub symmetric", nat.sub, arg)
}
for _, a := range prodNN {
arg := a
testFunNN(t, "mul", nat.mul, arg)
arg = argNN{a.z, a.y, a.x}
testFunNN(t, "mul symmetric", nat.mul, arg)
}
}
var mulRangesN = []struct {
a, b uint64
prod string
}{
{0, 0, "0"},
{1, 1, "1"},
{1, 2, "2"},
{1, 3, "6"},
{10, 10, "10"},
{0, 100, "0"},
{0, 1e9, "0"},
{1, 0, "1"}, // empty range
{100, 1, "1"}, // empty range
{1, 10, "3628800"}, // 10!
{1, 20, "2432902008176640000"}, // 20!
{1, 100,
"933262154439441526816992388562667004907159682643816214685929" +
"638952175999932299156089414639761565182862536979208272237582" +
"51185210916864000000000000000000000000", // 100!
},
}
func TestMulRangeN(t *testing.T) {
for i, r := range mulRangesN {
prod := nat(nil).mulRange(r.a, r.b).decimalString()
if prod != r.prod {
t.Errorf("#%d: got %s; want %s", i, prod, r.prod)
}
}
}
// allocBytes returns the number of bytes allocated by invoking f.
func allocBytes(f func()) uint64 {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
t := stats.TotalAlloc
f()
runtime.ReadMemStats(&stats)
return stats.TotalAlloc - t
}
// TestMulUnbalanced tests that multiplying numbers of different lengths
// does not cause deep recursion and in turn allocate too much memory.
// Test case for issue 3807.
func TestMulUnbalanced(t *testing.T) {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
x := rndNat(50000)
y := rndNat(40)
allocSize := allocBytes(func() {
nat(nil).mul(x, y)
})
inputSize := uint64(len(x)+len(y)) * _S
if ratio := allocSize / uint64(inputSize); ratio > 10 {
t.Errorf("multiplication uses too much memory (%d > %d times the size of inputs)", allocSize, ratio)
}
}
func rndNat(n int) nat {
return nat(rndV(n)).norm()
}
func BenchmarkMul(b *testing.B) {
mulx := rndNat(1e4)
muly := rndNat(1e4)
b.ResetTimer()
for i := 0; i < b.N; i++ {
var z nat
z.mul(mulx, muly)
}
}
func toString(x nat, charset string) string {
base := len(charset)
// special cases
switch {
case base < 2:
panic("illegal base")
case len(x) == 0:
return string(charset[0])
}
// allocate buffer for conversion
i := x.bitLen()/log2(Word(base)) + 1 // +1: round up
s := make([]byte, i)
// don't destroy x
q := nat(nil).set(x)
// convert
for len(q) > 0 {
i--
var r Word
q, r = q.divW(q, Word(base))
s[i] = charset[r]
}
return string(s[i:])
}
var strTests = []struct {
x nat // nat value to be converted
c string // conversion charset
s string // expected result
}{
{nil, "01", "0"},
{nat{1}, "01", "1"},
{nat{0xc5}, "01", "11000101"},
{nat{03271}, lowercaseDigits[0:8], "3271"},
{nat{10}, lowercaseDigits[0:10], "10"},
{nat{1234567890}, uppercaseDigits[0:10], "1234567890"},
{nat{0xdeadbeef}, lowercaseDigits[0:16], "deadbeef"},
{nat{0xdeadbeef}, uppercaseDigits[0:16], "DEADBEEF"},
{nat{0x229be7}, lowercaseDigits[0:17], "1a2b3c"},
{nat{0x309663e6}, uppercaseDigits[0:32], "O9COV6"},
}
func TestString(t *testing.T) {
for _, a := range strTests {
s := a.x.string(a.c)
if s != a.s {
t.Errorf("string%+v\n\tgot s = %s; want %s", a, s, a.s)
}
x, b, err := nat(nil).scan(strings.NewReader(a.s), len(a.c))
if x.cmp(a.x) != 0 {
t.Errorf("scan%+v\n\tgot z = %v; want %v", a, x, a.x)
}
if b != len(a.c) {
t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, len(a.c))
}
if err != nil {
t.Errorf("scan%+v\n\tgot error = %s", a, err)
}
}
}
var natScanTests = []struct {
s string // string to be scanned
base int // input base
x nat // expected nat
b int // expected base
ok bool // expected success
next rune // next character (or 0, if at EOF)
}{
// error: illegal base
{base: -1},
{base: 1},
{base: 37},
// error: no mantissa
{},
{s: "?"},
{base: 10},
{base: 36},
{s: "?", base: 10},
{s: "0x"},
{s: "345", base: 2},
// no errors
{"0", 0, nil, 10, true, 0},
{"0", 10, nil, 10, true, 0},
{"0", 36, nil, 36, true, 0},
{"1", 0, nat{1}, 10, true, 0},
{"1", 10, nat{1}, 10, true, 0},
{"0 ", 0, nil, 10, true, ' '},
{"08", 0, nil, 10, true, '8'},
{"018", 0, nat{1}, 8, true, '8'},
{"0b1", 0, nat{1}, 2, true, 0},
{"0b11000101", 0, nat{0xc5}, 2, true, 0},
{"03271", 0, nat{03271}, 8, true, 0},
{"10ab", 0, nat{10}, 10, true, 'a'},
{"1234567890", 0, nat{1234567890}, 10, true, 0},
{"xyz", 36, nat{(33*36+34)*36 + 35}, 36, true, 0},
{"xyz?", 36, nat{(33*36+34)*36 + 35}, 36, true, '?'},
{"0x", 16, nil, 16, true, 'x'},
{"0xdeadbeef", 0, nat{0xdeadbeef}, 16, true, 0},
{"0XDEADBEEF", 0, nat{0xdeadbeef}, 16, true, 0},
}
func TestScanBase(t *testing.T) {
for _, a := range natScanTests {
r := strings.NewReader(a.s)
x, b, err := nat(nil).scan(r, a.base)
if err == nil && !a.ok {
t.Errorf("scan%+v\n\texpected error", a)
}
if err != nil {
if a.ok {
t.Errorf("scan%+v\n\tgot error = %s", a, err)
}
continue
}
if x.cmp(a.x) != 0 {
t.Errorf("scan%+v\n\tgot z = %v; want %v", a, x, a.x)
}
if b != a.b {
t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base)
}
next, _, err := r.ReadRune()
if err == io.EOF {
next = 0
err = nil
}
if err == nil && next != a.next {
t.Errorf("scan%+v\n\tgot next = %q; want %q", a, next, a.next)
}
}
}
var pi = "3" +
"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651" +
"32823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461" +
"28475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920" +
"96282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179" +
"31051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798" +
"60943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901" +
"22495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837" +
"29780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083" +
"81420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909" +
"21642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151" +
"55748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035" +
"63707660104710181942955596198946767837449448255379774726847104047534646208046684259069491293313677028989152104" +
"75216205696602405803815019351125338243003558764024749647326391419927260426992279678235478163600934172164121992" +
"45863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818" +
"34797753566369807426542527862551818417574672890977772793800081647060016145249192173217214772350141441973568548" +
"16136115735255213347574184946843852332390739414333454776241686251898356948556209921922218427255025425688767179" +
"04946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886" +
"26945604241965285022210661186306744278622039194945047123713786960956364371917287467764657573962413890865832645" +
"99581339047802759009946576407895126946839835259570982582262052248940772671947826848260147699090264013639443745" +
"53050682034962524517493996514314298091906592509372216964615157098583874105978859597729754989301617539284681382" +
"68683868942774155991855925245953959431049972524680845987273644695848653836736222626099124608051243884390451244" +
"13654976278079771569143599770012961608944169486855584840635342207222582848864815845602850601684273945226746767" +
"88952521385225499546667278239864565961163548862305774564980355936345681743241125150760694794510965960940252288" +
"79710893145669136867228748940560101503308617928680920874760917824938589009714909675985261365549781893129784821" +
"68299894872265880485756401427047755513237964145152374623436454285844479526586782105114135473573952311342716610" +
"21359695362314429524849371871101457654035902799344037420073105785390621983874478084784896833214457138687519435" +
"06430218453191048481005370614680674919278191197939952061419663428754440643745123718192179998391015919561814675" +
"14269123974894090718649423196156794520809514655022523160388193014209376213785595663893778708303906979207734672" +
"21825625996615014215030680384477345492026054146659252014974428507325186660021324340881907104863317346496514539" +
"05796268561005508106658796998163574736384052571459102897064140110971206280439039759515677157700420337869936007" +
"23055876317635942187312514712053292819182618612586732157919841484882916447060957527069572209175671167229109816" +
"90915280173506712748583222871835209353965725121083579151369882091444210067510334671103141267111369908658516398" +
"31501970165151168517143765761835155650884909989859982387345528331635507647918535893226185489632132933089857064" +
"20467525907091548141654985946163718027098199430992448895757128289059232332609729971208443357326548938239119325" +
"97463667305836041428138830320382490375898524374417029132765618093773444030707469211201913020330380197621101100" +
"44929321516084244485963766983895228684783123552658213144957685726243344189303968642624341077322697802807318915" +
"44110104468232527162010526522721116603966655730925471105578537634668206531098965269186205647693125705863566201" +
"85581007293606598764861179104533488503461136576867532494416680396265797877185560845529654126654085306143444318" +
"58676975145661406800700237877659134401712749470420562230538994561314071127000407854733269939081454664645880797" +
"27082668306343285878569830523580893306575740679545716377525420211495576158140025012622859413021647155097925923" +
"09907965473761255176567513575178296664547791745011299614890304639947132962107340437518957359614589019389713111" +
"79042978285647503203198691514028708085990480109412147221317947647772622414254854540332157185306142288137585043" +
"06332175182979866223717215916077166925474873898665494945011465406284336639379003976926567214638530673609657120" +
"91807638327166416274888800786925602902284721040317211860820419000422966171196377921337575114959501566049631862" +
"94726547364252308177036751590673502350728354056704038674351362222477158915049530984448933309634087807693259939" +
"78054193414473774418426312986080998886874132604721569516239658645730216315981931951673538129741677294786724229" +
"24654366800980676928238280689964004824354037014163149658979409243237896907069779422362508221688957383798623001" +
"59377647165122893578601588161755782973523344604281512627203734314653197777416031990665541876397929334419521541" +
"34189948544473456738316249934191318148092777710386387734317720754565453220777092120190516609628049092636019759" +
"88281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267" +
"94561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337"
// Test case for BenchmarkScanPi.
func TestScanPi(t *testing.T) {
var x nat
z, _, err := x.scan(strings.NewReader(pi), 10)
if err != nil {
t.Errorf("scanning pi: %s", err)
}
if s := z.decimalString(); s != pi {
t.Errorf("scanning pi: got %s", s)
}
}
func TestScanPiParallel(t *testing.T) {
const n = 2
c := make(chan int)
for i := 0; i < n; i++ {
go func() {
TestScanPi(t)
c <- 0
}()
}
for i := 0; i < n; i++ {
<-c
}
}
func BenchmarkScanPi(b *testing.B) {
for i := 0; i < b.N; i++ {
var x nat
x.scan(strings.NewReader(pi), 10)
}
}
func BenchmarkStringPiParallel(b *testing.B) {
var x nat
x, _, _ = x.scan(strings.NewReader(pi), 0)
if x.decimalString() != pi {
panic("benchmark incorrect: conversion failed")
}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
x.decimalString()
}
})
}
func BenchmarkScan10Base2(b *testing.B) { ScanHelper(b, 2, 10, 10) }
func BenchmarkScan100Base2(b *testing.B) { ScanHelper(b, 2, 10, 100) }
func BenchmarkScan1000Base2(b *testing.B) { ScanHelper(b, 2, 10, 1000) }
func BenchmarkScan10000Base2(b *testing.B) { ScanHelper(b, 2, 10, 10000) }
func BenchmarkScan100000Base2(b *testing.B) { ScanHelper(b, 2, 10, 100000) }
func BenchmarkScan10Base8(b *testing.B) { ScanHelper(b, 8, 10, 10) }
func BenchmarkScan100Base8(b *testing.B) { ScanHelper(b, 8, 10, 100) }
func BenchmarkScan1000Base8(b *testing.B) { ScanHelper(b, 8, 10, 1000) }
func BenchmarkScan10000Base8(b *testing.B) { ScanHelper(b, 8, 10, 10000) }
func BenchmarkScan100000Base8(b *testing.B) { ScanHelper(b, 8, 10, 100000) }
func BenchmarkScan10Base10(b *testing.B) { ScanHelper(b, 10, 10, 10) }
func BenchmarkScan100Base10(b *testing.B) { ScanHelper(b, 10, 10, 100) }
func BenchmarkScan1000Base10(b *testing.B) { ScanHelper(b, 10, 10, 1000) }
func BenchmarkScan10000Base10(b *testing.B) { ScanHelper(b, 10, 10, 10000) }
func BenchmarkScan100000Base10(b *testing.B) { ScanHelper(b, 10, 10, 100000) }
func BenchmarkScan10Base16(b *testing.B) { ScanHelper(b, 16, 10, 10) }
func BenchmarkScan100Base16(b *testing.B) { ScanHelper(b, 16, 10, 100) }
func BenchmarkScan1000Base16(b *testing.B) { ScanHelper(b, 16, 10, 1000) }
func BenchmarkScan10000Base16(b *testing.B) { ScanHelper(b, 16, 10, 10000) }
func BenchmarkScan100000Base16(b *testing.B) { ScanHelper(b, 16, 10, 100000) }
func ScanHelper(b *testing.B, base int, x, y Word) {
b.StopTimer()
var z nat
z = z.expWW(x, y)
var s string
s = z.string(lowercaseDigits[0:base])
if t := toString(z, lowercaseDigits[0:base]); t != s {
b.Fatalf("scanning: got %s; want %s", s, t)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
z.scan(strings.NewReader(s), base)
}
}
func BenchmarkString10Base2(b *testing.B) { StringHelper(b, 2, 10, 10) }
func BenchmarkString100Base2(b *testing.B) { StringHelper(b, 2, 10, 100) }
func BenchmarkString1000Base2(b *testing.B) { StringHelper(b, 2, 10, 1000) }
func BenchmarkString10000Base2(b *testing.B) { StringHelper(b, 2, 10, 10000) }
func BenchmarkString100000Base2(b *testing.B) { StringHelper(b, 2, 10, 100000) }
func BenchmarkString10Base8(b *testing.B) { StringHelper(b, 8, 10, 10) }
func BenchmarkString100Base8(b *testing.B) { StringHelper(b, 8, 10, 100) }
func BenchmarkString1000Base8(b *testing.B) { StringHelper(b, 8, 10, 1000) }
func BenchmarkString10000Base8(b *testing.B) { StringHelper(b, 8, 10, 10000) }
func BenchmarkString100000Base8(b *testing.B) { StringHelper(b, 8, 10, 100000) }
func BenchmarkString10Base10(b *testing.B) { StringHelper(b, 10, 10, 10) }
func BenchmarkString100Base10(b *testing.B) { StringHelper(b, 10, 10, 100) }
func BenchmarkString1000Base10(b *testing.B) { StringHelper(b, 10, 10, 1000) }
func BenchmarkString10000Base10(b *testing.B) { StringHelper(b, 10, 10, 10000) }
func BenchmarkString100000Base10(b *testing.B) { StringHelper(b, 10, 10, 100000) }
func BenchmarkString10Base16(b *testing.B) { StringHelper(b, 16, 10, 10) }
func BenchmarkString100Base16(b *testing.B) { StringHelper(b, 16, 10, 100) }
func BenchmarkString1000Base16(b *testing.B) { StringHelper(b, 16, 10, 1000) }
func BenchmarkString10000Base16(b *testing.B) { StringHelper(b, 16, 10, 10000) }
func BenchmarkString100000Base16(b *testing.B) { StringHelper(b, 16, 10, 100000) }
func StringHelper(b *testing.B, base int, x, y Word) {
b.StopTimer()
var z nat
z = z.expWW(x, y)
z.string(lowercaseDigits[0:base]) // warm divisor cache
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = z.string(lowercaseDigits[0:base])
}
}
func BenchmarkLeafSize0(b *testing.B) { LeafSizeHelper(b, 10, 0) } // test without splitting
func BenchmarkLeafSize1(b *testing.B) { LeafSizeHelper(b, 10, 1) }
func BenchmarkLeafSize2(b *testing.B) { LeafSizeHelper(b, 10, 2) }
func BenchmarkLeafSize3(b *testing.B) { LeafSizeHelper(b, 10, 3) }
func BenchmarkLeafSize4(b *testing.B) { LeafSizeHelper(b, 10, 4) }
func BenchmarkLeafSize5(b *testing.B) { LeafSizeHelper(b, 10, 5) }
func BenchmarkLeafSize6(b *testing.B) { LeafSizeHelper(b, 10, 6) }
func BenchmarkLeafSize7(b *testing.B) { LeafSizeHelper(b, 10, 7) }
func BenchmarkLeafSize8(b *testing.B) { LeafSizeHelper(b, 10, 8) }
func BenchmarkLeafSize9(b *testing.B) { LeafSizeHelper(b, 10, 9) }
func BenchmarkLeafSize10(b *testing.B) { LeafSizeHelper(b, 10, 10) }
func BenchmarkLeafSize11(b *testing.B) { LeafSizeHelper(b, 10, 11) }
func BenchmarkLeafSize12(b *testing.B) { LeafSizeHelper(b, 10, 12) }
func BenchmarkLeafSize13(b *testing.B) { LeafSizeHelper(b, 10, 13) }
func BenchmarkLeafSize14(b *testing.B) { LeafSizeHelper(b, 10, 14) }
func BenchmarkLeafSize15(b *testing.B) { LeafSizeHelper(b, 10, 15) }
func BenchmarkLeafSize16(b *testing.B) { LeafSizeHelper(b, 10, 16) }
func BenchmarkLeafSize32(b *testing.B) { LeafSizeHelper(b, 10, 32) } // try some large lengths
func BenchmarkLeafSize64(b *testing.B) { LeafSizeHelper(b, 10, 64) }
func LeafSizeHelper(b *testing.B, base Word, size int) {
b.StopTimer()
originalLeafSize := leafSize
resetTable(cacheBase10.table[:])
leafSize = size
b.StartTimer()
for d := 1; d <= 10000; d *= 10 {
b.StopTimer()
var z nat
z = z.expWW(base, Word(d)) // build target number
_ = z.string(lowercaseDigits[0:base]) // warm divisor cache
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = z.string(lowercaseDigits[0:base])
}
}
b.StopTimer()
resetTable(cacheBase10.table[:])
leafSize = originalLeafSize
b.StartTimer()
}
func resetTable(table []divisor) {
if table != nil && table[0].bbb != nil {
for i := 0; i < len(table); i++ {
table[i].bbb = nil
table[i].nbits = 0
table[i].ndigits = 0
}
}
}
func TestStringPowers(t *testing.T) {
var b, p Word
for b = 2; b <= 16; b++ {
for p = 0; p <= 512; p++ {
x := nat(nil).expWW(b, p)
xs := x.string(lowercaseDigits[0:b])
xs2 := toString(x, lowercaseDigits[0:b])
if xs != xs2 {
t.Errorf("failed at %d ** %d in base %d: %s != %s", b, p, b, xs, xs2)
}
}
if b >= 3 && testing.Short() {
break
}
}
}
func TestLeadingZeros(t *testing.T) {
var x Word = _B >> 1
for i := 0; i <= _W; i++ {
if int(leadingZeros(x)) != i {
t.Errorf("failed at %x: got %d want %d", x, leadingZeros(x), i)
}
x >>= 1
}
}
type shiftTest struct {
in nat
shift uint
out nat
}
var leftShiftTests = []shiftTest{
{nil, 0, nil},
{nil, 1, nil},
{natOne, 0, natOne},
{natOne, 1, natTwo},
{nat{1 << (_W - 1)}, 1, nat{0}},
{nat{1 << (_W - 1), 0}, 1, nat{0, 1}},
}
func TestShiftLeft(t *testing.T) {
for i, test := range leftShiftTests {
var z nat
z = z.shl(test.in, test.shift)
for j, d := range test.out {
if j >= len(z) || z[j] != d {
t.Errorf("#%d: got: %v want: %v", i, z, test.out)
break
}
}
}
}
var rightShiftTests = []shiftTest{
{nil, 0, nil},
{nil, 1, nil},
{natOne, 0, natOne},
{natOne, 1, nil},
{natTwo, 1, natOne},
{nat{0, 1}, 1, nat{1 << (_W - 1)}},
{nat{2, 1, 1}, 1, nat{1<<(_W-1) + 1, 1 << (_W - 1)}},
}
func TestShiftRight(t *testing.T) {
for i, test := range rightShiftTests {
var z nat
z = z.shr(test.in, test.shift)
for j, d := range test.out {
if j >= len(z) || z[j] != d {
t.Errorf("#%d: got: %v want: %v", i, z, test.out)
break
}
}
}
}
type modWTest struct {
in string
dividend string
out string
}
var modWTests32 = []modWTest{
{"23492635982634928349238759823742", "252341", "220170"},
}
var modWTests64 = []modWTest{
{"6527895462947293856291561095690465243862946", "524326975699234", "375066989628668"},
}
func runModWTests(t *testing.T, tests []modWTest) {
for i, test := range tests {
in, _ := new(Int).SetString(test.in, 10)
d, _ := new(Int).SetString(test.dividend, 10)
out, _ := new(Int).SetString(test.out, 10)
r := in.abs.modW(d.abs[0])
if r != out.abs[0] {
t.Errorf("#%d failed: got %d want %s", i, r, out)
}
}
}
func TestModW(t *testing.T) {
if _W >= 32 {
runModWTests(t, modWTests32)
}
if _W >= 64 {
runModWTests(t, modWTests64)
}
}
func TestTrailingZeroBits(t *testing.T) {
x := Word(1)
for i := uint(0); i <= _W; i++ {
n := trailingZeroBits(x)
if n != i%_W {
t.Errorf("got trailingZeroBits(%#x) = %d; want %d", x, n, i%_W)
}
x <<= 1
}
y := nat(nil).set(natOne)
for i := uint(0); i <= 3*_W; i++ {
n := y.trailingZeroBits()
if n != i {
t.Errorf("got 0x%s.trailingZeroBits() = %d; want %d", y.string(lowercaseDigits[0:16]), n, i)
}
y = y.shl(y, 1)
}
}
var expNNTests = []struct {
x, y, m string
out string
}{
{"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
{"0x8000000000000000", "2", "6719", "4944"},
{"0x8000000000000000", "3", "6719", "5447"},
{"0x8000000000000000", "1000", "6719", "1603"},
{"0x8000000000000000", "1000000", "6719", "3199"},
{
"2938462938472983472983659726349017249287491026512746239764525612965293865296239471239874193284792387498274256129746192347",
"298472983472983471903246121093472394872319615612417471234712061",
"29834729834729834729347290846729561262544958723956495615629569234729836259263598127342374289365912465901365498236492183464",
"23537740700184054162508175125554701713153216681790245129157191391322321508055833908509185839069455749219131480588829346291",
},
}
func TestExpNN(t *testing.T) {
for i, test := range expNNTests {
x, _, _ := nat(nil).scan(strings.NewReader(test.x), 0)
y, _, _ := nat(nil).scan(strings.NewReader(test.y), 0)
out, _, _ := nat(nil).scan(strings.NewReader(test.out), 0)
var m nat
if len(test.m) > 0 {
m, _, _ = nat(nil).scan(strings.NewReader(test.m), 0)
}
z := nat(nil).expNN(x, y, m)
if z.cmp(out) != 0 {
t.Errorf("#%d got %v want %v", i, z, out)
}
}
}
func | (b *testing.B, x, y Word) {
var z nat
for i := 0; i < b.N; i++ {
z.expWW(x, y)
}
}
func BenchmarkExp3Power0x10(b *testing.B) { ExpHelper(b, 3, 0x10) }
func BenchmarkExp3Power0x40(b *testing.B) { ExpHelper(b, 3, 0x40) }
func BenchmarkExp3Power0x100(b *testing.B) { ExpHelper(b, 3, 0x100) }
func BenchmarkExp3Power0x400(b *testing.B) { ExpHelper(b, 3, 0x400) }
func BenchmarkExp3Power0x1000(b *testing.B) { ExpHelper(b, 3, 0x1000) }
func BenchmarkExp3Power0x4000(b *testing.B) { ExpHelper(b, 3, 0x4000) }
func BenchmarkExp3Power0x10000(b *testing.B) { ExpHelper(b, 3, 0x10000) }
func BenchmarkExp3Power0x40000(b *testing.B) { ExpHelper(b, 3, 0x40000) }
func BenchmarkExp3Power0x100000(b *testing.B) { ExpHelper(b, 3, 0x100000) }
func BenchmarkExp3Power0x400000(b *testing.B) { ExpHelper(b, 3, 0x400000) }
| ExpHelper |
version.go | package version
import "fmt"
const (
majorVersion uint32 = 2
minorVersion uint32 = 0
patchVersion uint32 = 4
)
var (
gitCommit string
ver *version
)
type version struct {
majorVersion uint32
minorVersion uint32
patchVersion uint32
versionString string
}
// Format version to "<majorVersion>.<minorVersion>.<patchVersion>[+<gitCommit>]",
// like "1.0.0", or "1.0.0+1a2b3c4d".
func (v version) String() string {
if v.versionString != "" {
return v.versionString
}
v.versionString = fmt.Sprintf("%d.%d.%d", v.majorVersion, v.minorVersion, v.patchVersion)
if gitCommit != "" && len(gitCommit) >= 8 |
return v.versionString
}
func GetVersion() string {
return ver.String()
}
func init() {
ver = &version{
majorVersion: majorVersion,
minorVersion: minorVersion,
patchVersion: patchVersion,
}
}
| {
v.versionString += "+" + gitCommit[:8]
} |
dagre-d3-tests.ts | /// <reference path="dagre-d3.d.ts"/>
namespace DagreD3Tests {
var gDagre = new dagreD3.graphlib.Graph();
var graph = gDagre.graph();
// has graph methods from dagre.d.ts
graph.setNode("a", {});
var num: number = 251 + graph.height + graph.width;
var predecessors: { [vertex:string]: string[] } = {};
var successors: { [vertex:string]: string[] } = {}; |
predecessors["a"] = graph.predecessors("a");
successors["a"] = graph.successors("a");
var render = new dagreD3.render();
var svg = d3.select("svg");
render(svg, graph);
} | |
sm3.js | (function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
var K = [];
// ROTATE: function(a, n) { return a << n | (a >>> (32 - n)) }
// for ( var i = 0; 16 > i; i++) T_00_63[i] = ROTATE(0x79CC4519, i);
// for ( var i = 16; 64 > i; i++) T_00_63[i] = ROTATE(0x7A879D8A, i);
var T_00_63 = [
//ROTATE(0x79CC4519, [0..15])
2043430169, -208106958, -416213915, -832427829,
-1664855657, 965255983, 1930511966, -433943364,
-867886727, -1735773453, 823420391, 1646840782,
-1001285732, -2002571463, 289824371, 579648742,
//ROTATE(0x7A879D8A, [16..63])
-1651869049, 991229199, 1982458398, -330050500,
-660100999, -1320201997, 1654563303, -985840690,
-1971681379, 351604539, 703209078, 1406418156,
-1482130984, 1330705329, -1633556638, 1027854021,
2055708042, -183551212, -367102423, -734204845,
-1468409689, 1358147919, -1578671458, 1137624381,
-2019718534, 255530229, 511060458, 1022120916,
2044241832, -206483632, -412967263, -825934525,
-1651869049, 991229199, 1982458398, -330050500,
-660100999, -1320201997, 1654563303, -985840690,
-1971681379, 351604539, 703209078, 1406418156,
-1482130984, 1330705329, -1633556638, 1027854021];
/**
* SM3 hash algorithm.
*/
var SM3 = C_algo.SM3 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
1937774191, 1226093241,
388252375, -628488704,
-1452330820, 372324522,
-477237683, -1325724082
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var H0 = [];
for (var i = 0; i < H.length; i++) {
H0.push(H[i]);
}
for (var i = 0; 16 > i; i++) {
W[i] = M[offset + i] | 0;
}
// Computation
var P1;
for (var i = 16; 68 > i; i++) {
// ROTATE: function(a, n) { return a << n | (a >>> (32 - n)) }
// P1: function(a) { return a ^ ROTATE(a, 15) ^ ROTATE(a, 23) }
// W[i] = P1(W[i - 16] ^ W[i - 9] ^ (W[i - 3] << 15 | (W[i - 3] >>> 17))) ^ (W[i - 13] << 7 | (W[i - 13] >>> 25)) ^ W[i - 6];
P1 = W[i - 16] ^ W[i - 9] ^ (W[i - 3] << 15 | (W[i - 3] >>> 17));
P1 = P1 ^ (P1 << 15 | (P1 >>> 17)) ^ (P1 << 23 | (P1 >>> 9));
W[i] = P1 ^ (W[i - 13] << 7 | (W[i - 13] >>> 25)) ^ W[i - 6];
}
for (var i = 0; 64 > i; i++) {
K[i] = W[i] ^ W[i + 4];
} | g = H0[0] << 12 | (H0[0] >>> 20);
f = (((g + H0[4]) & 4294967295) + T_00_63[i]) & 4294967295;
f = f << 7 | (f >>> 25);
g ^= f;
g = ((((((H0[0] ^ H0[1] ^ H0[2]) + H0[3]) & 4294967295) + g) & 4294967295) + K[i]) & 4294967295;
f = ((((((H0[4] ^ H0[5] ^ H0[6]) + H0[7]) & 4294967295) + f) & 4294967295) + W[i]) & 4294967295;
H0[3] = H0[2];
H0[2] = H0[1] << 9 | (H0[1] >>> 23);
H0[1] = H0[0];
H0[0] = g;
H0[7] = H0[6];
H0[6] = H0[5] << 19 | (H0[5] >>> 13);
H0[5] = H0[4];
H0[4] = f ^ (f << 9 | (f >>> 23)) ^ (f << 17 | (f >>> 15));
}
for (var i = 16; 64 > i; i++) {
g = H0[0] << 12 | (H0[0] >>> 20);
f = (((g + H0[4]) & 4294967295) + T_00_63[i]) & 4294967295;
f = f << 7 | (f >>> 25);
g ^= f;
g = ((((((H0[0] & H0[1] | H0[0] & H0[2] | H0[1] & H0[2]) + H0[3]) & 4294967295) + g) & 4294967295) + K[i]) & 4294967295;
f = ((((((H0[4] & H0[5] | ~H0[4] & H0[6]) + H0[7]) & 4294967295) + f) & 4294967295) + W[i]) & 4294967295;
H0[3] = H0[2];
H0[2] = H0[1] << 9 | (H0[1] >>> 23);
H0[1] = H0[0];
H0[0] = g;
H0[7] = H0[6];
H0[6] = H0[5] << 19 | (H0[5] >>> 13);
H0[5] = H0[4];
H0[4] = f ^ (f << 9 | (f >>> 23)) ^ (f << 17 | (f >>> 15));
}
// Intermediate hash value
for (var i = 0; i < 8; i++) {
H[i] ^= H0[i];
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal & 4294967295;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SM3('message');
* var hash = CryptoJS.SM3(wordArray);
*/
C.SM3 = Hasher._createHelper(SM3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSM3(message, key);
*/
C.HmacSM3 = Hasher._createHmacHelper(SM3);
}(Math)); |
var g, f;
//roateLeft
for (var i = 0; 16 > i; i++) { |
util.go | // Copyright (c) 2015 HPE Software Inc. All rights reserved.
// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
package util
import (
"fmt"
"log"
"os"
"runtime/debug"
)
type Logger struct {
*log.Logger
}
var LOGGER = &Logger{log.New(os.Stderr, "", log.LstdFlags)}
// fatal is like panic except it displays only the current goroutine's stack.
func Fatal(format string, v ...interface{}) {
// https://github.com/N-WhiteHole/log/blob/master/log.go#L45
LOGGER.Output(2, fmt.Sprintf("FATAL -- "+format, v...)+"\n"+string(debug.Stack()))
os.Exit(1)
}
// partitionString partitions the string into chunks of given size,
// with the last chunk of variable size.
func | (s string, chunkSize int) []string {
if chunkSize <= 0 {
panic("invalid chunkSize")
}
length := len(s)
chunks := 1 + length/chunkSize
start := 0
end := chunkSize
parts := make([]string, 0, chunks)
for {
if end > length {
end = length
}
parts = append(parts, s[start:end])
if end == length {
break
}
start, end = end, end+chunkSize
}
return parts
}
| PartitionString |
index-state.ts | 'use strict';
export namespace PanelCompState { | }
} | export interface IState {
// Empty |
jsre_test.go | // Copyright 2018 The go-juchain Authors
// This file is part of the go-juchain library.
//
// The go-juchain library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-juchain library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-juchain library. If not, see <http://www.gnu.org/licenses/>.
package jsre
import (
"io/ioutil"
"os"
"path"
"testing"
"time"
"github.com/robertkrimen/otto"
)
type testNativeObjectBinding struct{}
type msg struct {
Msg string
}
func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value {
m, err := call.Argument(0).ToString()
if err != nil {
return otto.UndefinedValue()
}
v, _ := call.Otto.ToValue(&msg{m})
return v
}
func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) {
dir, err := ioutil.TempDir("", "jsre-test")
if err != nil {
t.Fatal("cannot create temporary directory:", err)
}
if testjs != "" {
if err := ioutil.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil {
t.Fatal("cannot create test.js:", err)
}
}
return New(dir, os.Stdout), dir
}
func TestExec(t *testing.T) {
jsre, dir := newWithTestJS(t, `msg = "testMsg"`)
defer os.RemoveAll(dir)
err := jsre.Exec("test.js")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
val, err := jsre.Run("msg")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
if !val.IsString() {
t.Errorf("expected string value, got %v", val)
}
exp := "testMsg"
got, _ := val.ToString()
if exp != got {
t.Errorf("expected '%v', got '%v'", exp, got)
}
jsre.Stop(false)
}
func TestNatto(t *testing.T) |
func TestBind(t *testing.T) {
jsre := New("", os.Stdout)
defer jsre.Stop(false)
jsre.Bind("no", &testNativeObjectBinding{})
_, err := jsre.Run(`no.TestMethod("testMsg")`)
if err != nil {
t.Errorf("expected no error, got %v", err)
}
}
func TestLoadScript(t *testing.T) {
jsre, dir := newWithTestJS(t, `msg = "testMsg"`)
defer os.RemoveAll(dir)
_, err := jsre.Run(`loadScript("test.js")`)
if err != nil {
t.Errorf("expected no error, got %v", err)
}
val, err := jsre.Run("msg")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
if !val.IsString() {
t.Errorf("expected string value, got %v", val)
}
exp := "testMsg"
got, _ := val.ToString()
if exp != got {
t.Errorf("expected '%v', got '%v'", exp, got)
}
jsre.Stop(false)
}
| {
jsre, dir := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`)
defer os.RemoveAll(dir)
err := jsre.Exec("test.js")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
time.Sleep(100 * time.Millisecond)
val, err := jsre.Run("msg")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
if !val.IsString() {
t.Errorf("expected string value, got %v", val)
}
exp := "testMsg"
got, _ := val.ToString()
if exp != got {
t.Errorf("expected '%v', got '%v'", exp, got)
}
jsre.Stop(false)
} |
test_06_01.py | def | ():
from tensorflow.keras import datasets
assert model.get_layer("class_prediction").get_config()["units"]==43, "Check the number of output classes"
assert model.get_layer("class_prediction").get_config()["activation"]=="softmax", "Check your activation function"
assert model.output[0].name== 'class_prediction/Identity:0', "How does the output look like?"
assert model.output[2].name== 'y1_prediction/Identity:0', "How does the output look like?"
assert model.output[3].name== 'x2_prediction/Identity:0', "How does the output look like?"
assert model.output[4].name== 'y2_prediction/Identity:0', "How does the output look like?"
assert model.get_layer("y1_prediction").get_config()["units"]==1, "Check the number of outputs"
assert model.get_layer("x2_prediction").get_config()["units"]==1, "Check the number of outputs"
assert model.get_layer("y2_prediction").get_config()["units"]==1, "Check the number of outputs"
assert model.get_layer("x1_prediction").get_config()["units"]==1, "Check the number of outputs"
__msg__.good("WELL DONE!")
| test |
main.ts | import {createSlackService, SlackService} from './services/slack';
import {createFirebaseService, FirebaseService} from './services/firebase';
import {dotw} from './dotw';
import {createMicroBitService, MicroBitService} from './services/microBit';
import {createFake} from './utilities';
import {Actuators, createActuators} from './actuators';
import {createMessageLogic} from './logic/message-logic';
import {programLogic} from './logic/program-logic';
import { createBuildStatusProcessor } from './build-status/build-status-processor';
import { startWebserver } from './webserver';
import {GpioService} from './services/gpio';
import { createUdpService, MessageProcessor } from './services/udp-service';
let config: any = require('../local-config.json');
let gpioService: GpioService;
let microBitService: MicroBitService;
let slackService: SlackService;
let firebaseService: FirebaseService;
let temperature: number | undefined;
let processors: MessageProcessor[] = [];
if (config.udp) {
processors.push(createUdpService(config.udp));
}
let messageLogic = createMessageLogic({
getTemperature: () => temperature,
aboutLogic: programLogic,
processors
});
gpioService = {
lightEar: createFake('gpioService.lightEar')
};
if (config.gpio) {
try {
gpioService = require('./services/gpio').createGpioService();
} catch (e) {
console.error('GpioService could not be loaded:' + e);
}
}
try {
if (!config.microBitSerialPort) {
throw new Error('localConfig did not contain microBitSerialPort');
}
microBitService = createMicroBitService(config.microBitSerialPort);
microBitService.sendCommand('away'); // webservice not yet connected
messageLogic.registerBeforeExit(microBitService.quit);
} catch (e) {
console.error('MicroBitService could not be loaded' + e);
microBitService = {
onValueReceived: () => undefined,
sendCommand: createFake('microBitService.sendCommand'),
quit: createFake('microBitService.quit')
};
}
if (config.slackBotToken) {
slackService = createSlackService(config.slackBotToken, messageLogic, programLogic);
messageLogic.registerDiagnosticLogger(slackService.logDiagnostic);
} else {
slackService = {
sendMessage: createFake('slackService.sendMessage'),
logDiagnostic: createFake('slackService.logDiagnostic')
}
}
if (config.firebase) {
firebaseService = createFirebaseService(config.firebase, programLogic);
if (config.slackBotToken) { | devOfTheWeek.initialize(result.devs, result.cycle, result.cron);
});
}
} else {
firebaseService = {
getDOTWData: () => undefined,
onActuatorsUpdate: () => undefined,
publishSensors: createFake('firebaseService.publishSensors'),
updateDOTWCycle: () => undefined,
getDOTWcycle: () => undefined,
getBuildStatus: () => ({child: () => ({ on: () => false } as any)}) as any
}
}
let actuators: Actuators = createActuators({gpio: gpioService, microBit: microBitService});
firebaseService.onActuatorsUpdate((actuatorData) => {
console.log('updating actuators', JSON.stringify({
alarm: actuatorData.alarm,
faceDirection: actuatorData.faceDirection
}));
if (actuatorData.alarm) {
actuators.setAlarm(actuatorData.alarm);
} else {
actuators.clearAlarm();
}
if (actuatorData.faceDirection) {
// actuators.turnFace(actuatorData.faceDirection);
}
});
let lastReportedTemperature = 0;
let lastReportedTimestamp = 0;
microBitService.onValueReceived('temperature', (value: number) => {
temperature = (value - 85 /* empirically determined value */) / 10;
let timestamp = new Date().getTime();
let delta = timestamp - lastReportedTimestamp;
if (Math.abs(lastReportedTemperature - temperature) * (delta / (1000 * 60)) > 1) { // 1 degree 1 minute
firebaseService.publishSensors({ temperature });
lastReportedTemperature = temperature;
lastReportedTimestamp = timestamp;
}
});
if (config.webserver) {
let server = startWebserver(config.webserver, {messageLogic, microBit: microBitService});
programLogic.beforeShutdown(server.stop);
}
//createBuildStatusProcessor({firebase: firebaseService}); | let devOfTheWeek = dotw(config.slackBotToken, firebaseService.updateDOTWCycle);
firebaseService.getDOTWData().then((result: any) => { |
models.rs | #![doc = "generated by AutoRust"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckRestrictionsRequest {
#[serde(rename = "resourceDetails")]
pub resource_details: CheckRestrictionsResourceDetails,
#[serde(rename = "pendingFields", default, skip_serializing_if = "Vec::is_empty")]
pub pending_fields: Vec<PendingField>,
}
impl CheckRestrictionsRequest {
pub fn new(resource_details: CheckRestrictionsResourceDetails) -> Self {
Self {
resource_details,
pending_fields: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckRestrictionsResourceDetails {
#[serde(rename = "resourceContent")]
pub resource_content: serde_json::Value,
#[serde(rename = "apiVersion", default, skip_serializing_if = "Option::is_none")]
pub api_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
impl CheckRestrictionsResourceDetails {
pub fn new(resource_content: serde_json::Value) -> Self {
Self {
resource_content,
api_version: None,
scope: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct CheckRestrictionsResult {
#[serde(rename = "fieldRestrictions", default, skip_serializing_if = "Vec::is_empty")]
pub field_restrictions: Vec<FieldRestrictions>,
#[serde(rename = "contentEvaluationResult", default, skip_serializing_if = "Option::is_none")]
pub content_evaluation_result: Option<check_restrictions_result::ContentEvaluationResult>,
}
impl CheckRestrictionsResult {
pub fn new() -> Self {
Self::default()
}
}
pub mod check_restrictions_result {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ContentEvaluationResult {
#[serde(rename = "policyEvaluations", default, skip_serializing_if = "Vec::is_empty")]
pub policy_evaluations: Vec<PolicyEvaluationResult>,
}
impl ContentEvaluationResult {
pub fn new() -> Self {
Self::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ComplianceDetail {
#[serde(rename = "complianceState", default, skip_serializing_if = "Option::is_none")]
pub compliance_state: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
}
impl ComplianceDetail {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ComponentEventDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "principalOid", default, skip_serializing_if = "Option::is_none")]
pub principal_oid: Option<String>,
#[serde(rename = "policyDefinitionAction", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_action: Option<String>,
}
impl ComponentEventDetails {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ComponentStateDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(rename = "complianceState", default, skip_serializing_if = "Option::is_none")]
pub compliance_state: Option<String>,
}
impl ComponentStateDetails {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ErrorDefinition {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDefinition>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<TypedErrorInfo>,
}
impl ErrorDefinition {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDefinition>,
}
impl ErrorResponse {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct ExpressionEvaluationDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expression: Option<String>,
#[serde(rename = "expressionKind", default, skip_serializing_if = "Option::is_none")]
pub expression_kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(rename = "expressionValue", default, skip_serializing_if = "Option::is_none")]
pub expression_value: Option<serde_json::Value>,
#[serde(rename = "targetValue", default, skip_serializing_if = "Option::is_none")]
pub target_value: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operator: Option<String>,
}
impl ExpressionEvaluationDetails {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct FieldRestriction {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<field_restriction::Result>,
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub policy: Option<PolicyReference>,
}
impl FieldRestriction {
pub fn new() -> Self {
Self::default()
}
}
pub mod field_restriction {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Result {
Required,
Removed,
Deny,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct FieldRestrictions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub restrictions: Vec<FieldRestriction>,
}
impl FieldRestrictions {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct IfNotExistsEvaluationDetails {
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "totalResources", default, skip_serializing_if = "Option::is_none")]
pub total_resources: Option<i64>,
}
impl IfNotExistsEvaluationDetails {
pub fn new() -> Self {
Self::default()
}
}
pub type MetadataDocument = String;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
impl Operation {
pub fn new() -> Self {
Self::default()
}
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
impl Display {
pub fn new() -> Self {
Self::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct OperationsListResults {
#[serde(rename = "@odata.count", default, skip_serializing_if = "Option::is_none")]
pub odata_count: Option<i32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
}
impl OperationsListResults {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PendingField {
pub field: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<String>,
}
impl PendingField {
pub fn new(field: String) -> Self {
Self { field, values: Vec::new() }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyAssignmentSummary {
#[serde(rename = "policyAssignmentId", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_id: Option<String>,
#[serde(rename = "policySetDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub results: Option<SummaryResults>,
#[serde(rename = "policyDefinitions", default, skip_serializing_if = "Vec::is_empty")]
pub policy_definitions: Vec<PolicyDefinitionSummary>,
#[serde(rename = "policyGroups", default, skip_serializing_if = "Vec::is_empty")]
pub policy_groups: Vec<PolicyGroupSummary>,
}
impl PolicyAssignmentSummary {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyDefinitionSummary {
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(rename = "policyDefinitionReferenceId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_reference_id: Option<String>,
#[serde(rename = "policyDefinitionGroupNames", default, skip_serializing_if = "Vec::is_empty")]
pub policy_definition_group_names: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effect: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub results: Option<SummaryResults>,
}
impl PolicyDefinitionSummary {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyDetails {
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(rename = "policyAssignmentId", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_id: Option<String>,
#[serde(rename = "policyAssignmentDisplayName", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_display_name: Option<String>,
#[serde(rename = "policyAssignmentScope", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_scope: Option<String>,
#[serde(rename = "policySetDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_id: Option<String>,
#[serde(rename = "policyDefinitionReferenceId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_reference_id: Option<String>,
}
impl PolicyDetails {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyEvaluationDetails {
#[serde(rename = "evaluatedExpressions", default, skip_serializing_if = "Vec::is_empty")]
pub evaluated_expressions: Vec<ExpressionEvaluationDetails>,
#[serde(rename = "ifNotExistsDetails", default, skip_serializing_if = "Option::is_none")]
pub if_not_exists_details: Option<IfNotExistsEvaluationDetails>,
}
impl PolicyEvaluationDetails {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyEvaluationResult {
#[serde(rename = "policyInfo", default, skip_serializing_if = "Option::is_none")]
pub policy_info: Option<PolicyReference>,
#[serde(rename = "evaluationResult", default, skip_serializing_if = "Option::is_none")]
pub evaluation_result: Option<String>,
#[serde(rename = "evaluationDetails", default, skip_serializing_if = "Option::is_none")]
pub evaluation_details: Option<PolicyEvaluationDetails>,
}
impl PolicyEvaluationResult {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyEvent {
#[serde(rename = "@odata.id", default, skip_serializing_if = "Option::is_none")]
pub odata_id: Option<String>,
#[serde(rename = "@odata.context", default, skip_serializing_if = "Option::is_none")]
pub odata_context: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "policyAssignmentId", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_id: Option<String>,
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(rename = "effectiveParameters", default, skip_serializing_if = "Option::is_none")]
pub effective_parameters: Option<String>,
#[serde(rename = "isCompliant", default, skip_serializing_if = "Option::is_none")]
pub is_compliant: Option<bool>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")]
pub resource_type: Option<String>,
#[serde(rename = "resourceLocation", default, skip_serializing_if = "Option::is_none")]
pub resource_location: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(rename = "resourceTags", default, skip_serializing_if = "Option::is_none")]
pub resource_tags: Option<String>,
#[serde(rename = "policyAssignmentName", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_name: Option<String>,
#[serde(rename = "policyAssignmentOwner", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_owner: Option<String>,
#[serde(rename = "policyAssignmentParameters", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_parameters: Option<String>,
#[serde(rename = "policyAssignmentScope", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_scope: Option<String>,
#[serde(rename = "policyDefinitionName", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_name: Option<String>,
#[serde(rename = "policyDefinitionAction", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_action: Option<String>,
#[serde(rename = "policyDefinitionCategory", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_category: Option<String>,
#[serde(rename = "policySetDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_id: Option<String>,
#[serde(rename = "policySetDefinitionName", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_name: Option<String>,
#[serde(rename = "policySetDefinitionOwner", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_owner: Option<String>,
#[serde(rename = "policySetDefinitionCategory", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_category: Option<String>,
#[serde(rename = "policySetDefinitionParameters", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_parameters: Option<String>,
#[serde(rename = "managementGroupIds", default, skip_serializing_if = "Option::is_none")]
pub management_group_ids: Option<String>,
#[serde(rename = "policyDefinitionReferenceId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_reference_id: Option<String>,
#[serde(rename = "complianceState", default, skip_serializing_if = "Option::is_none")]
pub compliance_state: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "principalOid", default, skip_serializing_if = "Option::is_none")]
pub principal_oid: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub components: Vec<ComponentEventDetails>,
}
impl PolicyEvent {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyEventsQueryResults {
#[serde(rename = "@odata.context", default, skip_serializing_if = "Option::is_none")]
pub odata_context: Option<String>,
#[serde(rename = "@odata.count", default, skip_serializing_if = "Option::is_none")]
pub odata_count: Option<i32>,
#[serde(rename = "@odata.nextLink", default, skip_serializing_if = "Option::is_none")]
pub odata_next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PolicyEvent>,
}
impl PolicyEventsQueryResults {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyGroupSummary {
#[serde(rename = "policyGroupName", default, skip_serializing_if = "Option::is_none")]
pub policy_group_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub results: Option<SummaryResults>,
}
impl PolicyGroupSummary {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyMetadata {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PolicyMetadataProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl PolicyMetadata {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyMetadataCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SlimPolicyMetadata>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl PolicyMetadataCollection {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyMetadataProperties {
#[serde(flatten)]
pub policy_metadata_slim_properties: PolicyMetadataSlimProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub requirements: Option<String>,
}
impl PolicyMetadataProperties {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyMetadataSlimProperties {
#[serde(rename = "metadataId", default, skip_serializing_if = "Option::is_none")]
pub metadata_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub owner: Option<String>,
#[serde(rename = "additionalContentUrl", default, skip_serializing_if = "Option::is_none")]
pub additional_content_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata: Option<serde_json::Value>,
}
impl PolicyMetadataSlimProperties {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyReference {
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(rename = "policySetDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_id: Option<String>,
#[serde(rename = "policyDefinitionReferenceId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_reference_id: Option<String>,
#[serde(rename = "policyAssignmentId", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_id: Option<String>,
}
impl PolicyReference {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyState {
#[serde(rename = "@odata.id", default, skip_serializing_if = "Option::is_none")]
pub odata_id: Option<String>,
#[serde(rename = "@odata.context", default, skip_serializing_if = "Option::is_none")]
pub odata_context: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
#[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
#[serde(rename = "policyAssignmentId", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_id: Option<String>,
#[serde(rename = "policyDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_id: Option<String>,
#[serde(rename = "effectiveParameters", default, skip_serializing_if = "Option::is_none")]
pub effective_parameters: Option<String>,
#[serde(rename = "isCompliant", default, skip_serializing_if = "Option::is_none")]
pub is_compliant: Option<bool>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")]
pub resource_type: Option<String>,
#[serde(rename = "resourceLocation", default, skip_serializing_if = "Option::is_none")]
pub resource_location: Option<String>,
#[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")]
pub resource_group: Option<String>,
#[serde(rename = "resourceTags", default, skip_serializing_if = "Option::is_none")]
pub resource_tags: Option<String>,
#[serde(rename = "policyAssignmentName", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_name: Option<String>,
#[serde(rename = "policyAssignmentOwner", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_owner: Option<String>,
#[serde(rename = "policyAssignmentParameters", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_parameters: Option<String>,
#[serde(rename = "policyAssignmentScope", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_scope: Option<String>,
#[serde(rename = "policyDefinitionName", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_name: Option<String>,
#[serde(rename = "policyDefinitionAction", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_action: Option<String>,
#[serde(rename = "policyDefinitionCategory", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_category: Option<String>,
#[serde(rename = "policySetDefinitionId", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_id: Option<String>,
#[serde(rename = "policySetDefinitionName", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_name: Option<String>,
#[serde(rename = "policySetDefinitionOwner", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_owner: Option<String>,
#[serde(rename = "policySetDefinitionCategory", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_category: Option<String>,
#[serde(rename = "policySetDefinitionParameters", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_parameters: Option<String>,
#[serde(rename = "managementGroupIds", default, skip_serializing_if = "Option::is_none")]
pub management_group_ids: Option<String>,
#[serde(rename = "policyDefinitionReferenceId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_reference_id: Option<String>,
#[serde(rename = "complianceState", default, skip_serializing_if = "Option::is_none")]
pub compliance_state: Option<String>,
#[serde(rename = "policyEvaluationDetails", default, skip_serializing_if = "Option::is_none")]
pub policy_evaluation_details: Option<PolicyEvaluationDetails>,
#[serde(rename = "policyDefinitionGroupNames", default, skip_serializing_if = "Vec::is_empty")]
pub policy_definition_group_names: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub components: Vec<ComponentStateDetails>,
#[serde(rename = "policyDefinitionVersion", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_version: Option<String>,
#[serde(rename = "policySetDefinitionVersion", default, skip_serializing_if = "Option::is_none")]
pub policy_set_definition_version: Option<String>,
#[serde(rename = "policyAssignmentVersion", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_version: Option<String>,
}
impl PolicyState {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyStatesQueryResults {
#[serde(rename = "@odata.context", default, skip_serializing_if = "Option::is_none")]
pub odata_context: Option<String>,
#[serde(rename = "@odata.count", default, skip_serializing_if = "Option::is_none")]
pub odata_count: Option<i32>,
#[serde(rename = "@odata.nextLink", default, skip_serializing_if = "Option::is_none")]
pub odata_next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PolicyState>,
}
impl PolicyStatesQueryResults {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyTrackedResource {
#[serde(rename = "trackedResourceId", default, skip_serializing_if = "Option::is_none")]
pub tracked_resource_id: Option<String>,
#[serde(rename = "policyDetails", default, skip_serializing_if = "Option::is_none")]
pub policy_details: Option<PolicyDetails>,
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<TrackedResourceModificationDetails>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<TrackedResourceModificationDetails>,
#[serde(rename = "lastUpdateUtc", default, skip_serializing_if = "Option::is_none")]
pub last_update_utc: Option<String>,
}
impl PolicyTrackedResource {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PolicyTrackedResourcesQueryResults {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PolicyTrackedResource>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl PolicyTrackedResourcesQueryResults {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct QueryFailure {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<query_failure::Error>,
}
impl QueryFailure {
pub fn new() -> Self {
Self::default()
}
}
pub mod query_failure {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Error {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
impl Error {
pub fn new() -> Self {
Self::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Remediation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<RemediationProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl Remediation {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RemediationDeployment {
#[serde(rename = "remediatedResourceId", default, skip_serializing_if = "Option::is_none")]
pub remediated_resource_id: Option<String>,
#[serde(rename = "deploymentId", default, skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "resourceLocation", default, skip_serializing_if = "Option::is_none")]
pub resource_location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDefinition>,
#[serde(rename = "createdOn", default, skip_serializing_if = "Option::is_none")]
pub created_on: Option<String>,
#[serde(rename = "lastUpdatedOn", default, skip_serializing_if = "Option::is_none")]
pub last_updated_on: Option<String>,
}
impl RemediationDeployment {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RemediationDeploymentSummary {
#[serde(rename = "totalDeployments", default, skip_serializing_if = "Option::is_none")]
pub total_deployments: Option<i64>,
#[serde(rename = "successfulDeployments", default, skip_serializing_if = "Option::is_none")]
pub successful_deployments: Option<i64>,
#[serde(rename = "failedDeployments", default, skip_serializing_if = "Option::is_none")]
pub failed_deployments: Option<i64>,
}
impl RemediationDeploymentSummary {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RemediationDeploymentsListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<RemediationDeployment>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl RemediationDeploymentsListResult {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RemediationFilters {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub locations: Vec<String>,
}
impl RemediationFilters {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RemediationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Remediation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
impl RemediationListResult {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct RemediationProperties {
#[serde(rename = "policyAssignmentId", default, skip_serializing_if = "Option::is_none")]
pub policy_assignment_id: Option<String>,
#[serde(rename = "policyDefinitionReferenceId", default, skip_serializing_if = "Option::is_none")]
pub policy_definition_reference_id: Option<String>,
#[serde(rename = "resourceDiscoveryMode", default, skip_serializing_if = "Option::is_none")]
pub resource_discovery_mode: Option<remediation_properties::ResourceDiscoveryMode>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "createdOn", default, skip_serializing_if = "Option::is_none")]
pub created_on: Option<String>,
#[serde(rename = "lastUpdatedOn", default, skip_serializing_if = "Option::is_none")]
pub last_updated_on: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filters: Option<RemediationFilters>,
#[serde(rename = "deploymentStatus", default, skip_serializing_if = "Option::is_none")]
pub deployment_status: Option<RemediationDeploymentSummary>,
}
impl RemediationProperties {
pub fn new() -> Self {
Self::default()
}
}
pub mod remediation_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum | {
ExistingNonCompliant,
ReEvaluateCompliance,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SlimPolicyMetadata {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PolicyMetadataSlimProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl SlimPolicyMetadata {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SummarizeResults {
#[serde(rename = "@odata.context", default, skip_serializing_if = "Option::is_none")]
pub odata_context: Option<String>,
#[serde(rename = "@odata.count", default, skip_serializing_if = "Option::is_none")]
pub odata_count: Option<i32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Summary>,
}
impl SummarizeResults {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Summary {
#[serde(rename = "@odata.id", default, skip_serializing_if = "Option::is_none")]
pub odata_id: Option<String>,
#[serde(rename = "@odata.context", default, skip_serializing_if = "Option::is_none")]
pub odata_context: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub results: Option<SummaryResults>,
#[serde(rename = "policyAssignments", default, skip_serializing_if = "Vec::is_empty")]
pub policy_assignments: Vec<PolicyAssignmentSummary>,
}
impl Summary {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct SummaryResults {
#[serde(rename = "queryResultsUri", default, skip_serializing_if = "Option::is_none")]
pub query_results_uri: Option<String>,
#[serde(rename = "nonCompliantResources", default, skip_serializing_if = "Option::is_none")]
pub non_compliant_resources: Option<i32>,
#[serde(rename = "nonCompliantPolicies", default, skip_serializing_if = "Option::is_none")]
pub non_compliant_policies: Option<i32>,
#[serde(rename = "resourceDetails", default, skip_serializing_if = "Vec::is_empty")]
pub resource_details: Vec<ComplianceDetail>,
#[serde(rename = "policyDetails", default, skip_serializing_if = "Vec::is_empty")]
pub policy_details: Vec<ComplianceDetail>,
#[serde(rename = "policyGroupDetails", default, skip_serializing_if = "Vec::is_empty")]
pub policy_group_details: Vec<ComplianceDetail>,
}
impl SummaryResults {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TrackedResourceModificationDetails {
#[serde(rename = "policyDetails", default, skip_serializing_if = "Option::is_none")]
pub policy_details: Option<PolicyDetails>,
#[serde(rename = "deploymentId", default, skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
#[serde(rename = "deploymentTime", default, skip_serializing_if = "Option::is_none")]
pub deployment_time: Option<String>,
}
impl TrackedResourceModificationDetails {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct TypedErrorInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
impl TypedErrorInfo {
pub fn new() -> Self {
Self::default()
}
}
| ResourceDiscoveryMode |
mg0.py | g = [ ([],[('sel','V'),('cat','C')]),
([],[('sel','V'),('pos','wh'),('cat','C')]),
(['the'],[('sel','N'),('cat','D')]),
(['which'],[('sel','N'),('cat','D'),('neg','wh')]),
(['king'],[('cat','N')]),
(['queen'],[('cat','N')]),
(['wine'],[('cat','N')]),
(['beer'],[('cat','N')]),
(['drinks'],[('sel','D'),('sel','D'),('cat','V')]),
(['prefers'],[('sel','D'),('sel','D'),('cat','V')]),
(['knows'],[('sel','C'),('sel','D'),('cat','V')]), | (['says'],[('sel','C'),('sel','D'),('cat','V')])
] | |
error.go | package gqlerrors
import (
"fmt"
"reflect"
"github.com/ahmadmuzakki/graphql/language/ast"
"github.com/ahmadmuzakki/graphql/language/location"
"github.com/ahmadmuzakki/graphql/language/source"
)
type Error struct {
Message string
Stack string
Nodes []ast.Node
Source *source.Source
Positions []int
Locations []location.SourceLocation
OriginalError error
}
// implements Golang's built-in `error` interface
func (g Error) Error() string {
return fmt.Sprintf("%v", g.Message)
}
func | (message string, nodes []ast.Node, stack string, source *source.Source, positions []int, origError error) *Error {
if stack == "" && message != "" {
stack = message
}
if source == nil {
for _, node := range nodes {
// get source from first node
if node == nil || reflect.ValueOf(node).IsNil() {
continue
}
if node.GetLoc() != nil {
source = node.GetLoc().Source
}
break
}
}
if len(positions) == 0 && len(nodes) > 0 {
for _, node := range nodes {
if node == nil || reflect.ValueOf(node).IsNil() {
continue
}
if node.GetLoc() == nil {
continue
}
positions = append(positions, node.GetLoc().Start)
}
}
locations := []location.SourceLocation{}
for _, pos := range positions {
loc := location.GetLocation(source, pos)
locations = append(locations, loc)
}
return &Error{
Message: message,
Stack: stack,
Nodes: nodes,
Source: source,
Positions: positions,
Locations: locations,
OriginalError: origError,
}
}
| NewError |
date.rs | #[doc = "Register `DATE` reader"]
pub struct R(crate::R<DATE_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DATE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DATE_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DATE_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DATE` writer"]
pub struct W(crate::W<DATE_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DATE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DATE_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DATE_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `DATE` reader - reg_dateVersion control"]
pub struct DATE_R(crate::FieldReader<u32, u32>);
impl DATE_R {
#[inline(always)]
pub(crate) fn new(bits: u32) -> Self {
DATE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DATE_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DATE` writer - reg_dateVersion control"]
pub struct DATE_W<'a> {
w: &'a mut W,
}
impl<'a> DATE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = value as u32;
self.w
}
}
impl R {
#[doc = "Bits 0:31 - reg_dateVersion control"]
#[inline(always)]
pub fn date(&self) -> DATE_R {
DATE_R::new(self.bits as u32)
}
}
impl W {
#[doc = "Bits 0:31 - reg_dateVersion control"]
#[inline(always)]
pub fn date(&mut self) -> DATE_W {
DATE_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn | (&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "APB_CTRL_DATE_REG\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [date](index.html) module"]
pub struct DATE_SPEC;
impl crate::RegisterSpec for DATE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [date::R](R) reader structure"]
impl crate::Readable for DATE_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [date::W](W) writer structure"]
impl crate::Writable for DATE_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DATE to value 0x0200_7210"]
impl crate::Resettable for DATE_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x0200_7210
}
}
| bits |
statussender.py | import logging
import requests
import os
import copy
from kubee2etests.helpers_and_globals import TEST_NAMESPACE, FLASK_PORT, StatusEvent
LOGGER = logging.getLogger(__name__)
class StatusSender(object):
def __init__(self):
self.errors = []
@property
def results(self):
passed = len(self.errors) == 0
error_msgs = copy.deepcopy(self.errors)
self.errors = []
return passed, error_msgs
def flush_errors(self):
self.errors = []
def add_error(self, err):
error_list = [error[0] for error in self.errors]
try:
idx = error_list.index(err)
self.errors[idx] = (err, self.errors[idx][1] + 1)
except ValueError:
self.errors.append((err, 1)) | when a status update is needed. It also does deduping of errors which have come up twice
since the last status was sent to the frontend.
Args:
errors: (list) list of tuples to add to the error list - first entry being the error, second being the number of occurences
Returns: None, as a side effect will update `self.errors`
"""
error_list = [error[0] for error in self.errors]
for err in errors:
try:
idx = error_list.index(err[0])
self.errors[idx] = (err, self.errors[idx][1] + err[1])
except ValueError:
self.errors.append(err)
def send_update(self, name):
"""
Method which will send an update on the current test to the flask frontend. If not running, will log it and carry on
Args:
name: (str) name of the test being ran
Returns: (Response) requests response from the action.
"""
namespace = os.environ.get("TEST_NAMESPACE", TEST_NAMESPACE)
passing, msgs = self.results
event = StatusEvent(name, passing, namespace, msgs)
try:
response = requests.post("http://localhost:{}/update".format(FLASK_PORT), json=event.event_data)
return response
except Exception as e:
LOGGER.error("Flask endpoint not available, continuing")
LOGGER.debug("Exception: %s", str(e)) |
def add_errors(self, errors):
"""
Method which adds errors to the object's error list - this allows us to batch send them |
mod.rs | //! Traits for miscellaneous operations on ChunkedArray
use std::marker::Sized;
use arrow::array::ArrayRef;
pub use self::take::*;
#[cfg(feature = "object")]
use crate::chunked_array::object::ObjectType;
use crate::prelude::*;
use arrow::buffer::Buffer;
use polars_arrow::prelude::QuantileInterpolOptions;
#[cfg(feature = "dtype-categorical")]
use std::ops::Deref;
#[cfg(feature = "abs")]
mod abs;
pub(crate) mod aggregate;
pub(crate) mod any_value;
mod append;
mod apply;
mod bit_repr;
pub(crate) mod chunkops;
pub(crate) mod compare_inner;
#[cfg(feature = "concat_str")]
mod concat_str;
#[cfg(feature = "cum_agg")]
mod cum_agg;
pub(crate) mod downcast;
pub(crate) mod explode;
mod extend;
mod fill_null;
mod filter;
pub mod full;
#[cfg(feature = "interpolate")]
mod interpolate;
#[cfg(feature = "is_in")]
mod is_in;
mod len;
mod peaks;
#[cfg(feature = "repeat_by")]
mod repeat_by;
mod reverse;
pub(crate) mod rolling_window;
mod set;
mod shift;
pub(crate) mod sort;
pub(crate) mod take;
pub(crate) mod unique;
#[cfg(feature = "zip_with")]
pub mod zip;
#[cfg(feature = "to_list")]
pub trait ToList<T: PolarsDataType> {
fn to_list(&self) -> Result<ListChunked> {
Err(PolarsError::InvalidOperation(
format!("to_list not supported for dtype: {:?}", T::get_dtype()).into(),
))
}
}
#[cfg(feature = "interpolate")]
pub trait Interpolate {
#[must_use]
fn interpolate(&self) -> Self;
}
#[cfg(feature = "reinterpret")]
pub trait Reinterpret {
fn reinterpret_signed(&self) -> Series {
unimplemented!()
}
fn reinterpret_unsigned(&self) -> Series {
unimplemented!()
}
}
| fn bit_repr_is_large() -> bool;
fn bit_repr_large(&self) -> UInt64Chunked;
fn bit_repr_small(&self) -> UInt32Chunked;
}
pub trait ChunkAnyValue {
/// Get a single value. Beware this is slow.
/// If you need to use this slightly performant, cast Categorical to UInt32
///
/// # Safety
/// Does not do any bounds checking.
unsafe fn get_any_value_unchecked(&self, index: usize) -> AnyValue;
/// Get a single value. Beware this is slow.
fn get_any_value(&self, index: usize) -> AnyValue;
}
#[cfg(feature = "cum_agg")]
pub trait ChunkCumAgg<T> {
/// Get an array with the cumulative max computed at every element
fn cummax(&self, _reverse: bool) -> ChunkedArray<T> {
panic!("operation cummax not supported for this dtype")
}
/// Get an array with the cumulative min computed at every element
fn cummin(&self, _reverse: bool) -> ChunkedArray<T> {
panic!("operation cummin not supported for this dtype")
}
/// Get an array with the cumulative sum computed at every element
fn cumsum(&self, _reverse: bool) -> ChunkedArray<T> {
panic!("operation cumsum not supported for this dtype")
}
/// Get an array with the cumulative product computed at every element
fn cumprod(&self, _reverse: bool) -> ChunkedArray<T> {
panic!("operation cumprod not supported for this dtype")
}
}
/// Traverse and collect every nth element
pub trait ChunkTakeEvery<T> {
/// Traverse and collect every nth element in a new array.
fn take_every(&self, n: usize) -> ChunkedArray<T>;
}
/// Explode/ flatten a
pub trait ChunkExplode {
fn explode(&self) -> Result<Series> {
self.explode_and_offsets().map(|t| t.0)
}
fn explode_and_offsets(&self) -> Result<(Series, Buffer<i64>)>;
}
pub trait ChunkBytes {
fn to_byte_slices(&self) -> Vec<&[u8]>;
}
/// This differs from ChunkWindowCustom and ChunkWindow
/// by not using a fold aggregator, but reusing a `Series` wrapper and calling `Series` aggregators.
/// This likely is a bit slower than ChunkWindow
#[cfg(feature = "rolling_window")]
pub trait ChunkRollApply {
fn rolling_apply(
&self,
_f: &dyn Fn(&Series) -> Series,
_options: RollingOptions,
) -> Result<Series>
where
Self: Sized,
{
Err(PolarsError::InvalidOperation(
"rolling mean not supported for this datatype".into(),
))
}
}
/// Random access
pub trait TakeRandom {
type Item;
/// Get a nullable value by index.
///
/// # Panics
/// Panics if `index >= self.len()`
fn get(&self, index: usize) -> Option<Self::Item>;
/// Get a value by index and ignore the null bit.
///
/// # Safety
///
/// Does not do bound checks.
unsafe fn get_unchecked(&self, index: usize) -> Option<Self::Item>
where
Self: Sized,
{
self.get(index)
}
}
// Utility trait because associated type needs a lifetime
pub trait TakeRandomUtf8 {
type Item;
/// Get a nullable value by index.
///
/// # Panics
/// Panics if `index >= self.len()`
fn get(self, index: usize) -> Option<Self::Item>;
/// Get a value by index and ignore the null bit.
///
/// # Safety
///
/// Does not do bound checks.
unsafe fn get_unchecked(self, index: usize) -> Option<Self::Item>
where
Self: Sized,
{
self.get(index)
}
}
/// Fast access by index.
pub trait ChunkTake {
/// Take values from ChunkedArray by index.
///
/// # Safety
///
/// Doesn't do any bound checking.
#[must_use]
unsafe fn take_unchecked<I, INulls>(&self, indices: TakeIdx<I, INulls>) -> Self
where
Self: std::marker::Sized,
I: TakeIterator,
INulls: TakeIteratorNulls;
/// Take values from ChunkedArray by index.
/// Note that the iterator will be cloned, so prefer an iterator that takes the owned memory
/// by reference.
fn take<I, INulls>(&self, indices: TakeIdx<I, INulls>) -> Result<Self>
where
Self: std::marker::Sized,
I: TakeIterator,
INulls: TakeIteratorNulls;
}
/// Create a `ChunkedArray` with new values by index or by boolean mask.
/// Note that these operations clone data. This is however the only way we can modify at mask or
/// index level as the underlying Arrow arrays are immutable.
pub trait ChunkSet<'a, A, B> {
/// Set the values at indexes `idx` to some optional value `Option<T>`.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let ca = UInt32Chunked::new("a", &[1, 2, 3]);
/// let new = ca.set_at_idx(vec![0, 1], Some(10)).unwrap();
///
/// assert_eq!(Vec::from(&new), &[Some(10), Some(10), Some(3)]);
/// ```
fn set_at_idx<I: IntoIterator<Item = usize>>(
&'a self,
idx: I,
opt_value: Option<A>,
) -> Result<Self>
where
Self: Sized;
/// Set the values at indexes `idx` by applying a closure to these values.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let ca = Int32Chunked::new("a", &[1, 2, 3]);
/// let new = ca.set_at_idx_with(vec![0, 1], |opt_v| opt_v.map(|v| v - 5)).unwrap();
///
/// assert_eq!(Vec::from(&new), &[Some(-4), Some(-3), Some(3)]);
/// ```
fn set_at_idx_with<I: IntoIterator<Item = usize>, F>(&'a self, idx: I, f: F) -> Result<Self>
where
Self: Sized,
F: Fn(Option<A>) -> Option<B>;
/// Set the values where the mask evaluates to `true` to some optional value `Option<T>`.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let ca = Int32Chunked::new("a", &[1, 2, 3]);
/// let mask = BooleanChunked::new("mask", &[false, true, false]);
/// let new = ca.set(&mask, Some(5)).unwrap();
/// assert_eq!(Vec::from(&new), &[Some(1), Some(5), Some(3)]);
/// ```
fn set(&'a self, mask: &BooleanChunked, opt_value: Option<A>) -> Result<Self>
where
Self: Sized;
/// Set the values where the mask evaluates to `true` by applying a closure to these values.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let ca = UInt32Chunked::new("a", &[1, 2, 3]);
/// let mask = BooleanChunked::new("mask", &[false, true, false]);
/// let new = ca.set_with(&mask, |opt_v| opt_v.map(
/// |v| v * 2
/// )).unwrap();
/// assert_eq!(Vec::from(&new), &[Some(1), Some(4), Some(3)]);
/// ```
fn set_with<F>(&'a self, mask: &BooleanChunked, f: F) -> Result<Self>
where
Self: Sized,
F: Fn(Option<A>) -> Option<B>;
}
/// Cast `ChunkedArray<T>` to `ChunkedArray<N>`
pub trait ChunkCast {
/// Cast a `[ChunkedArray]` to `[DataType]`
fn cast(&self, data_type: &DataType) -> Result<Series>;
}
/// Fastest way to do elementwise operations on a ChunkedArray<T> when the operation is cheaper than
/// branching due to null checking
pub trait ChunkApply<'a, A, B> {
/// Apply a closure elementwise and cast to a Numeric ChunkedArray. This is fastest when the null check branching is more expensive
/// than the closure application.
///
/// Null values remain null.
fn apply_cast_numeric<F, S>(&'a self, f: F) -> ChunkedArray<S>
where
F: Fn(A) -> S::Native + Copy,
S: PolarsNumericType;
/// Apply a closure on optional values and cast to Numeric ChunkedArray without null values.
fn branch_apply_cast_numeric_no_null<F, S>(&'a self, f: F) -> ChunkedArray<S>
where
F: Fn(Option<A>) -> S::Native + Copy,
S: PolarsNumericType;
/// Apply a closure elementwise. This is fastest when the null check branching is more expensive
/// than the closure application. Often it is.
///
/// Null values remain null.
///
/// # Example
///
/// ```
/// use polars_core::prelude::*;
/// fn double(ca: &UInt32Chunked) -> UInt32Chunked {
/// ca.apply(|v| v * 2)
/// }
/// ```
#[must_use]
fn apply<F>(&'a self, f: F) -> Self
where
F: Fn(A) -> B + Copy;
fn try_apply<F>(&'a self, f: F) -> Result<Self>
where
F: Fn(A) -> Result<B> + Copy,
Self: Sized;
/// Apply a closure elementwise including null values.
#[must_use]
fn apply_on_opt<F>(&'a self, f: F) -> Self
where
F: Fn(Option<A>) -> Option<B> + Copy;
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
#[must_use]
fn apply_with_idx<F>(&'a self, f: F) -> Self
where
F: Fn((usize, A)) -> B + Copy;
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
#[must_use]
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where
F: Fn((usize, Option<A>)) -> Option<B> + Copy;
/// Apply a closure elementwise and write results to a mutable slice.
fn apply_to_slice<F, T>(&'a self, f: F, slice: &mut [T])
// (value of chunkedarray, value of slice) -> value of slice
where
F: Fn(Option<A>, &T) -> T;
}
/// Aggregation operations
pub trait ChunkAgg<T> {
/// Aggregate the sum of the ChunkedArray.
/// Returns `None` if the array is empty or only contains null values.
fn sum(&self) -> Option<T> {
None
}
fn min(&self) -> Option<T> {
None
}
/// Returns the maximum value in the array, according to the natural order.
/// Returns `None` if the array is empty or only contains null values.
fn max(&self) -> Option<T> {
None
}
/// Returns the mean value in the array.
/// Returns `None` if the array is empty or only contains null values.
fn mean(&self) -> Option<f64> {
None
}
}
/// Quantile and median aggregation
pub trait ChunkQuantile<T> {
/// Returns the mean value in the array.
/// Returns `None` if the array is empty or only contains null values.
fn median(&self) -> Option<T> {
None
}
/// Aggregate a given quantile of the ChunkedArray.
/// Returns `None` if the array is empty or only contains null values.
fn quantile(&self, _quantile: f64, _interpol: QuantileInterpolOptions) -> Result<Option<T>> {
Ok(None)
}
}
/// Variance and standard deviation aggregation.
pub trait ChunkVar<T> {
/// Compute the variance of this ChunkedArray/Series.
fn var(&self) -> Option<T> {
None
}
/// Compute the standard deviation of this ChunkedArray/Series.
fn std(&self) -> Option<T> {
None
}
}
/// Compare [Series](series/series/enum.Series.html)
/// and [ChunkedArray](series/chunked_array/struct.ChunkedArray.html)'s and get a `boolean` mask that
/// can be used to filter rows.
///
/// # Example
///
/// ```
/// use polars_core::prelude::*;
/// fn filter_all_ones(df: &DataFrame) -> Result<DataFrame> {
/// let mask = df
/// .column("column_a")?
/// .equal(1);
///
/// df.filter(&mask)
/// }
/// ```
pub trait ChunkCompare<Rhs> {
/// Check for equality and regard missing values as equal.
fn eq_missing(&self, rhs: Rhs) -> BooleanChunked;
/// Check for equality.
fn equal(&self, rhs: Rhs) -> BooleanChunked;
/// Check for inequality.
fn not_equal(&self, rhs: Rhs) -> BooleanChunked;
/// Greater than comparison.
fn gt(&self, rhs: Rhs) -> BooleanChunked;
/// Greater than or equal comparison.
fn gt_eq(&self, rhs: Rhs) -> BooleanChunked;
/// Less than comparison.
fn lt(&self, rhs: Rhs) -> BooleanChunked;
/// Less than or equal comparison
fn lt_eq(&self, rhs: Rhs) -> BooleanChunked;
}
/// Get unique values in a `ChunkedArray`
pub trait ChunkUnique<T> {
// We don't return Self to be able to use AutoRef specialization
/// Get unique values of a ChunkedArray
fn unique(&self) -> Result<ChunkedArray<T>>;
/// Get first index of the unique values in a `ChunkedArray`.
/// This Vec is sorted.
fn arg_unique(&self) -> Result<UInt32Chunked>;
/// Number of unique values in the `ChunkedArray`
fn n_unique(&self) -> Result<usize> {
self.arg_unique().map(|v| v.len())
}
/// Get a mask of all the unique values.
fn is_unique(&self) -> Result<BooleanChunked> {
Err(PolarsError::InvalidOperation(
"is_unique is not implemented for this dtype".into(),
))
}
/// Get a mask of all the duplicated values.
fn is_duplicated(&self) -> Result<BooleanChunked> {
Err(PolarsError::InvalidOperation(
"is_duplicated is not implemented for this dtype".into(),
))
}
/// Count the unique values.
fn value_counts(&self) -> Result<DataFrame> {
Err(PolarsError::InvalidOperation(
"is_duplicated is not implemented for this dtype".into(),
))
}
/// The most occurring value(s). Can return multiple Values
#[cfg(feature = "mode")]
#[cfg_attr(docsrs, doc(cfg(feature = "mode")))]
fn mode(&self) -> Result<ChunkedArray<T>> {
Err(PolarsError::InvalidOperation(
"mode is not implemented for this dtype".into(),
))
}
}
pub trait ToDummies<T>: ChunkUnique<T> {
fn to_dummies(&self) -> Result<DataFrame> {
Err(PolarsError::InvalidOperation(
"is_duplicated is not implemented for this dtype".into(),
))
}
}
#[derive(Default, Copy, Clone, Eq, PartialEq, Debug)]
pub struct SortOptions {
pub descending: bool,
pub nulls_last: bool,
}
/// Sort operations on `ChunkedArray`.
pub trait ChunkSort<T> {
#[allow(unused_variables)]
fn sort_with(&self, options: SortOptions) -> ChunkedArray<T>;
/// Returned a sorted `ChunkedArray`.
fn sort(&self, reverse: bool) -> ChunkedArray<T>;
/// Retrieve the indexes needed to sort this array.
fn argsort(&self, reverse: bool) -> UInt32Chunked;
/// Retrieve the indexes need to sort this and the other arrays.
fn argsort_multiple(&self, _other: &[Series], _reverse: &[bool]) -> Result<UInt32Chunked> {
Err(PolarsError::InvalidOperation(
"argsort_multiple not implemented for this dtype".into(),
))
}
}
#[derive(Copy, Clone, Debug)]
pub enum FillNullStrategy {
/// previous value in array
Backward,
/// next value in array
Forward,
/// mean value of array
Mean,
/// minimal value in array
Min,
/// maximum value in array
Max,
/// replace with the value zero
Zero,
/// replace with the value one
One,
/// replace with the maximum value of that data type
MaxBound,
/// replace with the minimal value of that data type
MinBound,
}
/// Replace None values with various strategies
pub trait ChunkFillNull {
/// Replace None values with one of the following strategies:
/// * Forward fill (replace None with the previous value)
/// * Backward fill (replace None with the next value)
/// * Mean fill (replace None with the mean of the whole array)
/// * Min fill (replace None with the minimum of the whole array)
/// * Max fill (replace None with the maximum of the whole array)
fn fill_null(&self, strategy: FillNullStrategy) -> Result<Self>
where
Self: Sized;
}
/// Replace None values with a value
pub trait ChunkFillNullValue<T> {
/// Replace None values with a give value `T`.
fn fill_null_with_values(&self, value: T) -> Result<Self>
where
Self: Sized;
}
/// Fill a ChunkedArray with one value.
pub trait ChunkFull<T> {
/// Create a ChunkedArray with a single value.
fn full(name: &str, value: T, length: usize) -> Self
where
Self: std::marker::Sized;
}
pub trait ChunkFullNull {
fn full_null(_name: &str, _length: usize) -> Self
where
Self: std::marker::Sized;
}
/// Reverse a ChunkedArray<T>
pub trait ChunkReverse<T> {
/// Return a reversed version of this array.
fn reverse(&self) -> ChunkedArray<T>;
}
/// Filter values by a boolean mask.
pub trait ChunkFilter<T> {
/// Filter values in the ChunkedArray with a boolean mask.
///
/// ```rust
/// # use polars_core::prelude::*;
/// let array = Int32Chunked::new("array", &[1, 2, 3]);
/// let mask = BooleanChunked::new("mask", &[true, false, true]);
///
/// let filtered = array.filter(&mask).unwrap();
/// assert_eq!(Vec::from(&filtered), [Some(1), Some(3)])
/// ```
fn filter(&self, filter: &BooleanChunked) -> Result<ChunkedArray<T>>
where
Self: Sized;
}
/// Create a new ChunkedArray filled with values at that index.
pub trait ChunkExpandAtIndex<T> {
/// Create a new ChunkedArray filled with values at that index.
fn expand_at_index(&self, length: usize, index: usize) -> ChunkedArray<T>;
}
macro_rules! impl_chunk_expand {
($self:ident, $length:ident, $index:ident) => {{
let opt_val = $self.get($index);
match opt_val {
Some(val) => ChunkedArray::full($self.name(), val, $length),
None => ChunkedArray::full_null($self.name(), $length),
}
}};
}
impl<T> ChunkExpandAtIndex<T> for ChunkedArray<T>
where
ChunkedArray<T>: ChunkFull<T::Native> + TakeRandom<Item = T::Native>,
T: PolarsNumericType,
{
fn expand_at_index(&self, index: usize, length: usize) -> ChunkedArray<T> {
impl_chunk_expand!(self, length, index)
}
}
impl ChunkExpandAtIndex<BooleanType> for BooleanChunked {
fn expand_at_index(&self, index: usize, length: usize) -> BooleanChunked {
impl_chunk_expand!(self, length, index)
}
}
impl ChunkExpandAtIndex<Utf8Type> for Utf8Chunked {
fn expand_at_index(&self, index: usize, length: usize) -> Utf8Chunked {
impl_chunk_expand!(self, length, index)
}
}
#[cfg(feature = "dtype-categorical")]
impl ChunkExpandAtIndex<CategoricalType> for CategoricalChunked {
fn expand_at_index(&self, index: usize, length: usize) -> CategoricalChunked {
let ca: CategoricalChunked = self.deref().expand_at_index(index, length).into();
ca.set_state(self)
}
}
impl ChunkExpandAtIndex<ListType> for ListChunked {
fn expand_at_index(&self, index: usize, length: usize) -> ListChunked {
let opt_val = self.get(index);
match opt_val {
Some(val) => ListChunked::full(self.name(), &val, length),
None => ListChunked::full_null_with_dtype(self.name(), length, &self.inner_dtype()),
}
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkExpandAtIndex<ObjectType<T>> for ObjectChunked<T> {
fn expand_at_index(&self, index: usize, length: usize) -> ObjectChunked<T> {
let opt_val = self.get(index);
match opt_val {
Some(val) => ObjectChunked::<T>::full(self.name(), val.clone(), length),
None => ObjectChunked::<T>::full_null(self.name(), length),
}
}
}
/// Shift the values of a ChunkedArray by a number of periods.
pub trait ChunkShiftFill<T, V> {
/// Shift the values by a given period and fill the parts that will be empty due to this operation
/// with `fill_value`.
fn shift_and_fill(&self, periods: i64, fill_value: V) -> ChunkedArray<T>;
}
pub trait ChunkShift<T> {
fn shift(&self, periods: i64) -> ChunkedArray<T>;
}
/// Combine 2 ChunkedArrays based on some predicate.
pub trait ChunkZip<T> {
/// Create a new ChunkedArray with values from self where the mask evaluates `true` and values
/// from `other` where the mask evaluates `false`
fn zip_with(&self, mask: &BooleanChunked, other: &ChunkedArray<T>) -> Result<ChunkedArray<T>>;
}
/// Apply kernels on the arrow array chunks in a ChunkedArray.
pub trait ChunkApplyKernel<A: Array> {
/// Apply kernel and return result as a new ChunkedArray.
#[must_use]
fn apply_kernel<F>(&self, f: F) -> Self
where
F: Fn(&A) -> ArrayRef;
/// Apply a kernel that outputs an array of different type.
fn apply_kernel_cast<F, S>(&self, f: F) -> ChunkedArray<S>
where
F: Fn(&A) -> ArrayRef,
S: PolarsDataType;
}
/// Find local minima/ maxima
pub trait ChunkPeaks {
/// Get a boolean mask of the local maximum peaks.
fn peak_max(&self) -> BooleanChunked {
unimplemented!()
}
/// Get a boolean mask of the local minimum peaks.
fn peak_min(&self) -> BooleanChunked {
unimplemented!()
}
}
/// Check if element is member of list array
#[cfg(feature = "is_in")]
#[cfg_attr(docsrs, doc(cfg(feature = "is_in")))]
pub trait IsIn {
/// Check if elements of this array are in the right Series, or List values of the right Series.
fn is_in(&self, _other: &Series) -> Result<BooleanChunked> {
unimplemented!()
}
}
/// Argmin/ Argmax
pub trait ArgAgg {
/// Get the index of the minimal value
fn arg_min(&self) -> Option<usize> {
None
}
/// Get the index of the maximal value
fn arg_max(&self) -> Option<usize> {
None
}
}
/// Repeat the values `n` times.
#[cfg(feature = "repeat_by")]
#[cfg_attr(docsrs, doc(cfg(feature = "repeat_by")))]
pub trait RepeatBy {
/// Repeat the values `n` times, where `n` is determined by the values in `by`.
fn repeat_by(&self, _by: &UInt32Chunked) -> ListChunked {
unimplemented!()
}
}
#[cfg(feature = "is_first")]
#[cfg_attr(docsrs, doc(cfg(feature = "is_first")))]
/// Mask the first unique values as `true`
pub trait IsFirst<T: PolarsDataType> {
fn is_first(&self) -> Result<BooleanChunked> {
Err(PolarsError::InvalidOperation(
format!("operation not supported by {:?}", T::get_dtype()).into(),
))
}
}
#[cfg(feature = "is_first")]
#[cfg_attr(docsrs, doc(cfg(feature = "is_first")))]
/// Mask the last unique values as `true`
pub trait IsLast<T: PolarsDataType> {
fn is_last(&self) -> Result<BooleanChunked> {
Err(PolarsError::InvalidOperation(
format!("operation not supported by {:?}", T::get_dtype()).into(),
))
}
}
#[cfg(feature = "concat_str")]
#[cfg_attr(docsrs, doc(cfg(feature = "concat_str")))]
/// Concat the values into a string array.
pub trait StrConcat {
/// Concat the values into a string array.
/// # Arguments
///
/// * `delimiter` - A string that will act as delimiter between values.
fn str_concat(&self, delimiter: &str) -> Utf8Chunked;
}
pub trait ChunkLen {
/// Get the length of the ChunkedArray
fn len(&self) -> usize;
/// Check if ChunkedArray is empty.
fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub trait ChunkOps: ChunkLen {
/// Aggregate to contiguous memory.
#[must_use]
fn rechunk(&self) -> Self
where
Self: std::marker::Sized;
/// Slice the array. The chunks are reallocated the underlying data slices are zero copy.
///
/// When offset is negative it will be counted from the end of the array.
/// This method will never error,
/// and will slice the best match when offset, or length is out of bounds
#[must_use]
fn slice(&self, offset: i64, length: usize) -> Self
where
Self: std::marker::Sized;
/// Take a view of top n elements
#[must_use]
fn limit(&self, num_elements: usize) -> Self
where
Self: Sized,
{
self.slice(0, num_elements)
}
/// Get the head of the ChunkedArray
#[must_use]
fn head(&self, length: Option<usize>) -> Self
where
Self: Sized,
{
match length {
Some(len) => self.slice(0, std::cmp::min(len, self.len())),
None => self.slice(0, std::cmp::min(10, self.len())),
}
}
/// Get the tail of the ChunkedArray
#[must_use]
fn tail(&self, length: Option<usize>) -> Self
where
Self: Sized,
{
let len = match length {
Some(len) => std::cmp::min(len, self.len()),
None => std::cmp::min(10, self.len()),
};
self.slice(-(len as i64), len)
}
} | /// Transmute ChunkedArray to bit representation.
/// This is useful in hashing context and reduces no.
/// of compiled code paths.
pub(crate) trait ToBitRepr { |
mixer.rs | use alloc::{boxed::Box, sync::Arc, vec};
use core::cell::RefCell;
use crate::{frame, set, Controlled, Frame, Handle, Set, SetHandle, Signal, Stop};
/// Handle for controlling a [`Mixer`] from another thread
pub struct MixerControl<'a, T>(&'a Mixer<T>);
impl<T> MixerControl<'_, T> {
/// Begin playing `signal`, returning a handle that can be used to pause or stop it and access
/// other controls
///
/// Finished signals are automatically stopped, and their storage reused for future `play`
/// calls.
///
/// The type of signal given determines what additional controls can be used. See the
/// examples for a detailed guide.
pub fn play<S>(&mut self, signal: S) -> Handle<Stop<S>>
where
S: Signal<Frame = T> + Send + 'static,
{
let signal = Arc::new(Stop::new(signal));
let handle = unsafe { Handle::from_arc(signal.clone()) };
self.0.send.borrow_mut().insert(signal);
handle
}
}
/// A [`Signal`] that mixes a dynamic set of [`Signal`]s
pub struct Mixer<T> {
send: RefCell<SetHandle<ErasedSignal<T>>>,
recv: RefCell<Inner<T>>,
}
impl<T> Mixer<T>
where
T: Frame + Clone,
{
/// Construct a new mixer
pub fn new() -> Self {
let (handle, set) = set();
Self {
send: RefCell::new(handle),
recv: RefCell::new(Inner {
set,
buffer: vec![T::ZERO; 1024].into(),
}),
}
}
}
impl<T> Default for Mixer<T>
where
T: Frame + Clone,
{
fn | () -> Self {
Self::new()
}
}
unsafe impl<'a, T: 'a> Controlled<'a> for Mixer<T> {
type Control = MixerControl<'a, T>;
unsafe fn make_control(signal: &'a Mixer<T>) -> Self::Control {
MixerControl(signal)
}
}
struct Inner<T> {
set: Set<ErasedSignal<T>>,
buffer: Box<[T]>,
}
impl<T: Frame> Signal for Mixer<T> {
type Frame = T;
fn sample(&self, interval: f32, out: &mut [T]) {
let this = &mut *self.recv.borrow_mut();
this.set.update();
for o in out.iter_mut() {
*o = T::ZERO;
}
for i in (0..this.set.len()).rev() {
let signal = &this.set[i];
if Arc::strong_count(signal) == 1 {
signal.handle_dropped();
}
if signal.remaining() <= 0.0 {
signal.stop();
}
if signal.is_stopped() {
this.set.remove(i);
continue;
}
if signal.is_paused() {
continue;
}
// Sample into `buffer`, then mix into `out`
let mut iter = out.iter_mut();
while iter.len() > 0 {
let n = iter.len().min(this.buffer.len());
let staging = &mut this.buffer[..n];
signal.sample(interval, staging);
for (staged, o) in staging.iter().zip(&mut iter) {
*o = frame::mix(o, staged);
}
}
}
}
}
type ErasedSignal<T> = Arc<Stop<dyn Signal<Frame = T>>>;
| default |
audio.rs | //! Generate audio data.
//!
//! Normally you only need to use the high level RomBuilder methods:
//! RomBuilder::add_audio_data and RomBuilder::add_audio_player.
//! So check those out first.
//!
//! The audio player that plays the generated audio can be found at:
//! [audio_player.asm](https://github.com/rukai/ggbasm/blob/master/src/audio_player.asm)
use anyhow::{Error, bail};
use crate::ast::{Instruction, Expr};
/// Processes `Vec<AudioLine>` into `Vec<Instruction>` that can be played by the audio player
/// Despite returning Instruction, the only variants used are Db* and Label.
pub fn generate_audio_data(lines: Vec<AudioLine>) -> Result<Vec<Instruction>, Error> {
// Bail if a clean exit is impossible
let mut bad_label = None;
let mut clean_exit = false;
for line in &lines {
match line {
AudioLine::Disable => { clean_exit = true }
AudioLine::PlayFrom (_) => { clean_exit = true }
AudioLine::Label (label) => {
clean_exit = false;
bad_label = Some(label.clone());
}
_ => { }
}
}
if !clean_exit {
if let Some(bad_label) = bad_label {
bail!("It is impossible to cleanly exit from label \"{}\". Please ensure `disable` or `playfrom song_label` is used at least once after this label.", bad_label);
}
else {
bail!("Audio has no labels so there is no way to use it.");
}
}
let mut result = vec!();
for line in lines {
match line {
AudioLine::SetRegisters { rest, ch1, ch2, .. } => {
let mut bytes = vec!();
if let Some(state) = ch1 {
// validate values
if state.length > 0x3f {
bail!("Length of {} is > 0x3F", state.length);
}
if state.duty > 3 {
bail!("Duty of {} is > 3", state.duty);
}
if state.envelope_initial_volume > 0x0F {
bail!("envelope initial volume of {} is > 0x0F", state.envelope_initial_volume);
}
if state.envelope_argument > 7 {
bail!("envelope initial volume of {} is > 7", state.envelope_argument);
}
// TODO: Validate ff10 inputs
// generate register values
let frequency = note_to_frequency(state.octave, &state.note, state.sharp)?;
let length = 0x3f - state.length; // make length start at 0 and higher values mean longer length.
let ff10 = 0;
let ff11 = ((state.duty << 6 & 0b11000000))
| length & 0b00111111;
let ff12 = (state.envelope_initial_volume << 4)
| (if state.envelope_increase { 1 } else { 0 } << 3)
| (state.envelope_argument & 0b00000111);
let ff13 = (frequency & 0xFF) as u8;
let ff14 = ((frequency >> 8) as u8 & 0b00000111)
| if state.enable_length { 1 } else { 0 } << 6
| if state.initial { 1 } else { 0 } << 7;
// insert command/argument pairs
bytes.push(0x10);
bytes.push(ff10);
bytes.push(0x11);
bytes.push(ff11);
bytes.push(0x12);
bytes.push(ff12);
bytes.push(0x13);
bytes.push(ff13);
bytes.push(0x14);
bytes.push(ff14);
}
if let Some(state) = ch2 {
// validate values
if state.length > 0x3f {
bail!("Length of {} is > 0x3F", state.length);
}
if state.duty > 3 {
bail!("Duty of {} is > 3", state.duty);
}
if state.envelope_initial_volume > 0x0F {
bail!("envelope initial volume of {} is > 0x0F", state.envelope_initial_volume);
}
if state.envelope_argument > 7 {
bail!("envelope initial volume of {} is > 7", state.envelope_argument);
}
// generate register values
let frequency = note_to_frequency(state.octave, &state.note, state.sharp)?;
let length = 0x3f - state.length; // make length start at 0 and higher values mean longer length.
let ff16 = ((state.duty << 6 & 0b11000000))
| length & 0b00111111;
let ff17 = (state.envelope_initial_volume << 4)
| (if state.envelope_increase { 1 } else { 0 } << 3)
| (state.envelope_argument & 0b00000111);
let ff18 = (frequency & 0xFF) as u8;
let ff19 = ((frequency >> 8) as u8 & 0b00000111)
| if state.enable_length { 1 } else { 0 } << 6
| if state.initial { 1 } else { 0 } << 7;
// insert command/argument pairs
bytes.push(0x16);
bytes.push(ff16);
bytes.push(0x17);
bytes.push(ff17);
bytes.push(0x18);
bytes.push(ff18);
bytes.push(0x19);
bytes.push(ff19);
}
bytes.push(0xFF);
bytes.push(rest);
result.push(Instruction::Db(bytes));
}
AudioLine::Rest (rest) => result.push(Instruction::Db (vec!(0xFF, rest))),
AudioLine::Disable => result.push(Instruction::Db (vec!(0xFC))),
AudioLine::PlayFrom (label) => {
result.push(Instruction::Db (vec!(0xFE)));
result.push(Instruction::DbExpr16 (Expr::Ident (label)));
}
AudioLine::Label (label) => result.push(Instruction::Label (label)),
}
}
Ok(result)
}
/// Parses `&str` into `Vec<AudioLine>`
/// Returns `Err` if the text does not conform to the audio text format.
///
/// Documentation on the input format is given for RomBuilder::add_audio_data.
/// Each AudioLine cooresponds to a line in the input file. Empty lines are skipped.
pub fn parse_audio_text(text: &str) -> Result<Vec<AudioLine>, Error> {
let mut result = vec!();
for (i, line) in text.lines().enumerate() {
let tokens: Vec<&str> = line.split_whitespace().collect();
// empty lines for formatting are ok
if tokens.len() == 0 {
continue;
}
let line = match parse_audio_line(line) {
Ok(line) => line,
Err(error) => {
bail!("Invalid command or values on line {}: {}", i + 1, error);
}
};
result.push(line);
}
Ok(result)
}
fn parse_audio_line(line: &str) -> Result<AudioLine, Error> {
let tokens: Vec<&str> = line.split_whitespace().collect();
if tokens[0].to_lowercase() == "rest" {
if let Some(value) = tokens.get(1) {
if let Ok(value) = u8::from_str_radix(value, 16) {
Ok(AudioLine::Rest (value))
} else {
bail!("rest instruction argument is not a hexadecimal integer");
}
} else {
bail!("rest instruction needs an argument");
}
} else if tokens[0].to_lowercase() == "playfrom" {
if tokens.len() == 2 {
Ok(AudioLine::PlayFrom (tokens[1].to_string()))
} else {
bail!("Expected 1 argument for playfrom, however there is {} arguments", tokens.len());
}
} else if tokens[0].to_lowercase() == "label" {
if tokens.len() == 2 {
Ok(AudioLine::Label (tokens[1].to_string()))
} else {
bail!("Expected 1 argument for label, however there is {} arguments", tokens.len());
}
} else if tokens[0].to_lowercase() == "disable" {
Ok(AudioLine::Disable)
}
else {
let line: Vec<char> = line.chars().collect();
let rest = match u8::from_str_radix(line[0..2].iter().cloned().collect::<String>().as_ref(), 16) {
Ok(value) => value,
Err(_) => bail!("Invalid character for rest"),
};
let ch1 = if line.len() < 23 || line[4..23].iter().all(|x| x.is_whitespace()) {
None
} else {
let line = &line;
// these are the only values unique to channel 1
let sweep_time = 0;
let sweep_increase = true;
let sweep_number = 0;
// use channel 2 logic as a base for channel 1
let channel2 = read_channel2(&line[4..])?;
Some(Channel1State {
note: channel2.note,
sharp: channel2.sharp,
octave: channel2.octave,
duty: channel2.duty,
length: channel2.length,
envelope_initial_volume: channel2.envelope_initial_volume,
envelope_argument: channel2.envelope_argument,
envelope_increase: channel2.envelope_increase,
enable_length: channel2.enable_length,
initial: channel2.initial,
sweep_time, sweep_increase, sweep_number,
})
};
let ch2 = if line.len() < 40 || line[25..40].iter().all(|x| x.is_whitespace()) {
None
} else {
Some(read_channel2(&line[25..])?)
};
let ch3 = if line.len() < 41 {
None
} else {
unimplemented!("Channel 3 and 4 are unimplemented");
};
let ch4 = None;
Ok(AudioLine::SetRegisters { rest, ch1, ch2, ch3, ch4 })
}
}
/// return (Note, sharp, octave)
fn | (line: &[char]) -> Result<(Note, bool, u8), Error> {
let note = match line[0] {
'a' | 'A' => Note::A,
'b' | 'B' => Note::B,
'c' | 'C' => Note::C,
'd' | 'D' => Note::D,
'e' | 'E' => Note::E,
'f' | 'F' => Note::F,
'g' | 'G' => Note::G,
_ => bail!("Invalid character for note"),
};
let sharp = line[0].is_lowercase();
let octave = match line[1].to_string().parse() {
Ok(value) => value,
Err(_) => bail!("Invalid character for octave"),
};
Ok((note, sharp, octave))
}
/// return channel 2 data
fn read_channel2(line: &[char]) -> Result<Channel2State, Error> {
let (note, sharp, octave) = read_note(line)?;
let duty = match line[3].to_string().parse() {
Ok(value) => value,
Err(_) => bail!("Invalid character for duty"),
};
if duty > 3 {
bail!("Duty of {} is > 3", duty);
}
let length = match u8::from_str_radix(line[5..7].iter().cloned().collect::<String>().as_ref(), 16) {
Ok(value) => value,
Err(_) => bail!("Invalid character for length"),
};
if length > 0x3f {
bail!("Length of {} is > 0x3F", length);
}
let envelope_initial_volume = match u8::from_str_radix(line[8].to_string().as_ref(), 16) {
Ok(value) => value,
Err(_) => bail!("Invalid character for envelope initial volume"),
};
if envelope_initial_volume > 0x0F {
bail!("envelope initial volume of {} is > 0x0F", envelope_initial_volume);
}
let envelope_argument = match line[10].to_string().parse() {
Ok(value) => value,
Err(_) => bail!("Invalid character for envelope argument"),
};
if envelope_argument > 7 {
bail!("envelope initial volume of {} is > 7", envelope_argument);
}
let envelope_increase = match line[11] {
'Y' => true,
'N' => false,
_ => bail!("Invalid character for envelope increase"),
};
let enable_length = match line[13] {
'Y' => true,
'N' => false,
_ => bail!("Invalid character for enable length"),
};
let initial = match line[14] {
'Y' => true,
'N' => false,
_ => bail!("Invalid character for initial"),
};
Ok(Channel2State {
note, sharp, octave, duty, length,
envelope_initial_volume,
envelope_argument,
envelope_increase,
enable_length,
initial,
})
}
/// Represents a line from the audio file
pub enum AudioLine {
SetRegisters {
rest: u8,
ch1: Option<Channel1State>,
ch2: Option<Channel2State>,
ch3: Option<Channel3State>,
ch4: Option<Channel4State>,
},
Label (String),
PlayFrom (String),
Rest (u8),
Disable,
}
/// Represents a Note to be played by a channel
pub enum Note {
A,
B,
C,
D,
E,
F,
G,
}
impl Note {
pub fn to_string(&self) -> String {
match self {
Note::A => String::from("A"),
Note::B => String::from("B"),
Note::C => String::from("C"),
Note::D => String::from("D"),
Note::E => String::from("E"),
Note::F => String::from("F"),
Note::G => String::from("G"),
}
}
}
/// Represents the state of channel 1
pub struct Channel1State {
pub note: Note,
pub sharp: bool,
pub octave: u8,
pub duty: u8,
pub length: u8,
pub envelope_initial_volume: u8,
pub envelope_argument: u8,
pub envelope_increase: bool,
pub enable_length: bool,
pub initial: bool,
pub sweep_time: u8,
pub sweep_increase: bool,
pub sweep_number: u8,
}
/// Represents the state of channel 2
pub struct Channel2State {
pub note: Note,
pub sharp: bool,
pub octave: u8,
pub duty: u8,
pub length: u8,
pub envelope_initial_volume: u8,
pub envelope_argument: u8,
pub envelope_increase: bool,
pub enable_length: bool,
pub initial: bool,
}
/// Represents the state of channel 3
pub struct Channel3State {
}
/// Represents the state of channel 4
pub struct Channel4State {
}
/// Converts an octave, note and sharp into the 16 bit value the gameboy uses for frequency.
fn note_to_frequency(octave: u8, note: &Note, sharp: bool) -> Result<u16, Error> {
Ok(match (octave, note, sharp) {
(3, Note::C, false) => 44,
(3, Note::C, true) => 156,
(3, Note::D, false) => 262,
(3, Note::D, true) => 363,
(3, Note::E, false) => 457,
(3, Note::F, false) => 547,
(3, Note::F, true) => 631,
(3, Note::G, false) => 710,
(3, Note::G, true) => 786,
(3, Note::A, false) => 854,
(3, Note::A, true) => 923,
(3, Note::B, false) => 986,
(4, Note::C, false) => 1046,
(4, Note::C, true) => 1102,
(4, Note::D, false) => 1155,
(4, Note::D, true) => 1205,
(4, Note::E, false) => 1253,
(4, Note::F, false) => 1297,
(4, Note::F, true) => 1339,
(4, Note::G, false) => 1379,
(4, Note::G, true) => 1417,
(4, Note::A, false) => 1452,
(4, Note::A, true) => 1486,
(4, Note::B, false) => 1517,
(5, Note::C, false) => 1546,
(5, Note::C, true) => 1575,
(5, Note::D, false) => 1602,
(5, Note::D, true) => 1627,
(5, Note::E, false) => 1650,
(5, Note::F, false) => 1673,
(5, Note::F, true) => 1694,
(5, Note::G, false) => 1714,
(5, Note::G, true) => 1732,
(5, Note::A, false) => 1750,
(5, Note::A, true) => 1767,
(5, Note::B, false) => 1783,
(6, Note::C, false) => 1798,
(6, Note::C, true) => 1812,
(6, Note::D, false) => 1825,
(6, Note::D, true) => 1837,
(6, Note::E, false) => 1849,
(6, Note::F, false) => 1860,
(6, Note::F, true) => 1871,
(6, Note::G, false) => 1881,
(6, Note::G, true) => 1890,
(6, Note::A, false) => 1899,
(6, Note::A, true) => 1907,
(6, Note::B, false) => 1915,
(7, Note::C, false) => 1923,
(7, Note::C, true) => 1930,
(7, Note::D, false) => 1936,
(7, Note::D, true) => 1943,
(7, Note::E, false) => 1949,
(7, Note::F, false) => 1954,
(7, Note::F, true) => 1959,
(7, Note::G, false) => 1964,
(7, Note::G, true) => 1969,
(7, Note::A, false) => 1974,
(7, Note::A, true) => 1978,
(7, Note::B, false) => 1982,
(8, Note::C, false) => 1985,
(8, Note::C, true) => 1988,
(8, Note::D, false) => 1992,
(8, Note::D, true) => 1995,
(8, Note::E, false) => 1998,
(8, Note::F, false) => 2001,
(8, Note::F, true) => 2004,
(8, Note::G, false) => 2006,
(8, Note::G, true) => 2009,
(8, Note::A, false) => 2011,
(8, Note::A, true) => 2013,
(8, Note::B, false) => 2015,
(octave, note, false) => bail!("Invalid note: {}{}", note.to_string().to_uppercase(), octave),
(octave, note, true) => bail!("Invalid note: {}{}", note.to_string().to_lowercase(), octave)
})
}
| read_note |
test_tools_ark_data_exporter.py | import os
import shutil
from typing import List, Tuple
import unittest
from google.protobuf import json_format
from mir.protos import mir_command_pb2 as mirpb
from mir.tools import data_exporter, hash_utils, mir_storage_ops
from tests import utils as test_utils
class TestArkDataExporter(unittest.TestCase):
# life cycle
def __init__(self, methodName: str) -> None:
super().__init__(methodName=methodName)
self._test_root = test_utils.dir_test_root(self.id().split('.')[-3:])
self._assets_location = os.path.join(self._test_root, 'assets_location')
self._dest_root = os.path.join(self._test_root, 'export_dest')
self._mir_root = os.path.join(self._test_root, 'mir-repo')
def setUp(self) -> None:
self.__prepare_dirs()
self.__prepare_mir_repo()
self.__prepare_assets()
return super().setUp()
def tearDown(self) -> None:
# self.__deprepare_dirs()
return super().tearDown()
# private: prepare env
def __prepare_dirs(self):
test_utils.remake_dirs(self._test_root)
test_utils.remake_dirs(self._assets_location)
test_utils.remake_dirs(self._dest_root)
test_utils.remake_dirs(self._mir_root)
def __deprepare_dirs(self):
if os.path.isdir(self._test_root):
shutil.rmtree(self._test_root)
def __prepare_assets(self):
'''
copy all assets from project to assets_location, assumes that `self._assets_location` already created
'''
image_paths = ['tests/assets/2007_000032.jpg', 'tests/assets/2007_000243.jpg']
sha1sum_path_pairs = [(hash_utils.sha1sum_for_file(image_path), image_path)
for image_path in image_paths] # type: List[Tuple[str, str]]
for sha1sum, image_path in sha1sum_path_pairs:
shutil.copyfile(image_path, os.path.join(self._assets_location, sha1sum))
def __prepare_mir_repo(self):
'''
creates mir repo, assumes that `self._mir_root` already created
'''
test_utils.mir_repo_init(self._mir_root)
test_utils.mir_repo_create_branch(self._mir_root, 'a')
# metadatas
metadatas_dict = {
'attributes': {
'430df22960b0f369318705800139fcc8ec38a3e4': {
'assetType': 'AssetTypeImageJpeg',
'width': 500,
'height': 281,
'imageChannels': 3
},
'a3008c032eb11c8d9ffcb58208a36682ee40900f': {
'assetType': 'AssetTypeImageJpeg',
'width': 500,
'height': 333,
'imageChannels': 3
}
}
}
mir_metadatas = mirpb.MirMetadatas()
json_format.ParseDict(metadatas_dict, mir_metadatas)
# annotations
annotations_dict = {
'task_annotations': {
'a': {
'image_annotations': {
'430df22960b0f369318705800139fcc8ec38a3e4': {
'annotations': [{
'index': 0,
'box': {
'x': 104,
'y': 78,
'w': 272,
'h': 105
},
'class_id': 52,
'score': 1,
}, {
'index': 1,
'box': {
'x': 133,
'y': 88,
'w': 65,
'h': 36
}, | 'index': 2,
'box': {
'x': 195,
'y': 180,
'w': 19,
'h': 50
},
'class_id': 2,
'score': 1,
}, {
'index': 3,
'box': {
'x': 26,
'y': 189,
'w': 19,
'h': 95
},
'class_id': 2,
'score': 1,
}]
},
'a3008c032eb11c8d9ffcb58208a36682ee40900f': {
'annotations': [{
'index': 0,
'box': {
'x': 181,
'y': 127,
'w': 94,
'h': 67
},
'class_id': 52,
'score': 1,
}]
},
}
}
},
'head_task_id': 'a',
}
mir_annotations = mirpb.MirAnnotations()
json_format.ParseDict(annotations_dict, mir_annotations)
# keywords
keywords_dict = {
'keywords': {
'430df22960b0f369318705800139fcc8ec38a3e4': {
'predifined_keyids': [2, 52],
'customized_keywords': ['pascal']
},
'a3008c032eb11c8d9ffcb58208a36682ee40900f': {
'predifined_keyids': [52],
'customized_keywords': ['pascal']
},
}
}
mir_keywords = mirpb.MirKeywords()
json_format.ParseDict(keywords_dict, mir_keywords)
# task
task = mir_storage_ops.create_task(task_type=mirpb.TaskType.TaskTypeImportData,
task_id='a',
message='import')
# save and commit
mir_storage_ops.MirStorageOps.save_and_commit(mir_root=self._mir_root,
mir_branch='a',
his_branch='master',
mir_datas={
mirpb.MirStorage.MIR_METADATAS: mir_metadatas,
mirpb.MirStorage.MIR_ANNOTATIONS: mir_annotations,
},
task=task)
# private: check result
def __check_result(self, asset_ids, format_type, export_path, index_file_path):
# check files
for asset_id in asset_ids:
asset_path = os.path.join(export_path, asset_id + '.jpeg')
self.assertTrue(os.path.isfile(asset_path))
if format_type == data_exporter.ExportFormat.EXPORT_FORMAT_ARK:
annotation_path = os.path.join(export_path, asset_id + '.txt')
elif format_type == data_exporter.ExportFormat.EXPORT_FORMAT_VOC:
annotation_path = os.path.join(export_path, asset_id + '.xml')
self.assertTrue(os.path.isfile(annotation_path))
# index file exists
self.assertTrue(os.path.isfile(index_file_path))
# index file have enough lines
# and each line is accessable
with open(index_file_path, 'r') as idx_f:
lines = idx_f.readlines()
self.assertEqual(len(lines), len(asset_ids))
for line in lines:
asset_rel_path, annotation_rel_path = line.split()
self.assertTrue(os.path.isfile(os.path.join(export_path, asset_rel_path)))
self.assertTrue(os.path.isfile(os.path.join(export_path, annotation_rel_path)))
def __check_ark_annotations(self, asset_id: str, export_path: str, expected_first_two_cols: List[Tuple[int, int]]):
annotation_path = os.path.join(export_path, asset_id + '.txt')
with open(annotation_path, 'r') as f:
lines = f.read().splitlines()
self.assertEqual(len(expected_first_two_cols), len(lines))
for line_idx, line in enumerate(lines):
line_components = line.split(',')
for col_idx in range(2):
self.assertEqual(expected_first_two_cols[line_idx][col_idx], int(line_components[col_idx].strip()))
# public: test cases
def test_normal_00(self):
''' normal case: ark format '''
asset_ids = {'430df22960b0f369318705800139fcc8ec38a3e4', 'a3008c032eb11c8d9ffcb58208a36682ee40900f'}
train_path = os.path.join(self._dest_root, 'train')
data_exporter.export(mir_root=self._mir_root,
assets_location=self._assets_location,
class_type_ids={
2: 0,
52: 1
},
asset_ids=asset_ids,
asset_dir=train_path,
annotation_dir=train_path,
need_ext=True,
need_id_sub_folder=False,
base_branch='a',
base_task_id='a',
format_type=data_exporter.ExportFormat.EXPORT_FORMAT_ARK,
index_file_path=os.path.join(train_path, 'index.tsv'),
index_assets_prefix='')
# check result
self.__check_result(asset_ids=asset_ids,
format_type=data_exporter.ExportFormat.EXPORT_FORMAT_ARK,
export_path=train_path,
index_file_path=os.path.join(train_path, 'index.tsv'))
self.__check_ark_annotations(asset_id='430df22960b0f369318705800139fcc8ec38a3e4',
export_path=train_path,
expected_first_two_cols=[(1, 104), (1, 133), (0, 195), (0, 26)])
def test_normal_01(self):
''' normal case: voc format '''
asset_ids = {'430df22960b0f369318705800139fcc8ec38a3e4', 'a3008c032eb11c8d9ffcb58208a36682ee40900f'}
train_path = os.path.join(self._dest_root, 'train')
data_exporter.export(mir_root=self._mir_root,
assets_location=self._assets_location,
class_type_ids={
2: 0,
52: 1
},
asset_ids=asset_ids,
asset_dir=train_path,
annotation_dir=train_path,
need_ext=True,
need_id_sub_folder=False,
base_branch='a',
base_task_id='a',
format_type=data_exporter.ExportFormat.EXPORT_FORMAT_VOC,
index_file_path=os.path.join(train_path, 'index.tsv'),
index_assets_prefix='')
# check result
self.__check_result(asset_ids=asset_ids,
format_type=data_exporter.ExportFormat.EXPORT_FORMAT_VOC,
export_path=train_path,
index_file_path=os.path.join(train_path, 'index.tsv')) | 'class_id': 52,
'score': 1,
}, { |
pool.rs | use cfg_if::cfg_if;
use log::*;
#[cfg(any(feature = "with-postgres", feature = "with-sqlite"))]
use r2d2;
cfg_if! {if #[cfg(feature = "with-postgres")]{
use r2d2_postgres::PostgresConnectionManager;
use crate::pg::{self, PostgresDB};
}}
cfg_if! {if #[cfg(feature = "with-sqlite")]{
use r2d2_sqlite::SqliteConnectionManager;
use crate::sq::{self, SqliteDB};
}}
cfg_if! {if #[cfg(feature = "with-mysql")]{
use r2d2_mysql::MysqlConnectionManager;
use crate::my::{self, MysqlDB};
}}
use crate::{
error::{
ConnectError,
ParseError,
},
platform::{
DBPlatform,
Platform,
},
platform_mut::DBPlatformMut,
DaoManager,
DbError,
EntityManager,
EntityManagerMut,
};
use std::{
collections::BTreeMap,
convert::TryFrom,
};
#[derive(Default)]
pub struct Pool(BTreeMap<String, ConnPool>);
pub enum ConnPool {
#[cfg(feature = "with-postgres")]
PoolPg(r2d2::Pool<PostgresConnectionManager>),
#[cfg(feature = "with-sqlite")]
PoolSq(r2d2::Pool<SqliteConnectionManager>),
#[cfg(feature = "with-mysql")]
PoolMy(r2d2::Pool<MysqlConnectionManager>),
}
pub enum PooledConn {
#[cfg(feature = "with-postgres")]
PooledPg(Box<r2d2::PooledConnection<PostgresConnectionManager>>),
#[cfg(feature = "with-sqlite")]
PooledSq(Box<r2d2::PooledConnection<SqliteConnectionManager>>),
#[cfg(feature = "with-mysql")]
PooledMy(Box<r2d2::PooledConnection<MysqlConnectionManager>>),
}
impl Pool {
pub fn new() -> Self { Default::default() }
/// ensure that a connection pool for this db_url exist
pub fn ensure(&mut self, db_url: &str) -> Result<(), DbError> {
info!("ensure db_url: {}", db_url);
let platform: Result<Platform, _> = TryFrom::try_from(db_url);
match platform {
Ok(platform) => {
match platform {
#[cfg(feature = "with-postgres")]
Platform::Postgres => {
let pool_pg = pg::init_pool(db_url)?;
if self.0.get(db_url).is_none() {
self.0.insert(db_url.to_string(), ConnPool::PoolPg(pool_pg));
}
Ok(())
}
#[cfg(feature = "with-sqlite")]
Platform::Sqlite(path) => {
info!("matched sqlite");
let pool_sq = sq::init_pool(&path)?;
if self.0.get(db_url).is_none() |
Ok(())
}
#[cfg(feature = "with-mysql")]
Platform::Mysql => {
let pool_my = my::init_pool(db_url)?;
if self.0.get(db_url).is_none() {
self.0.insert(db_url.to_string(), ConnPool::PoolMy(pool_my));
}
Ok(())
}
Platform::Unsupported(scheme) => {
info!("unsupported");
Err(DbError::ConnectError(ConnectError::UnsupportedDb(scheme)))
}
}
}
Err(e) => Err(DbError::ConnectError(ConnectError::ParseError(e))),
}
}
/// get the pool for this specific db_url, create one if it doesn't have yet.
fn get_pool(&mut self, db_url: &str) -> Result<&ConnPool, DbError> {
self.ensure(db_url)?;
let platform: Result<Platform, ParseError> = TryFrom::try_from(db_url);
match platform {
Ok(platform) => {
match platform {
#[cfg(feature = "with-postgres")]
Platform::Postgres => {
let conn: Option<&ConnPool> = self.0.get(db_url);
if let Some(conn) = conn {
Ok(conn)
} else {
Err(DbError::ConnectError(ConnectError::NoSuchPoolConnection))
}
}
#[cfg(feature = "with-sqlite")]
Platform::Sqlite(_path) => {
info!("getting sqlite pool");
let conn: Option<&ConnPool> = self.0.get(db_url);
if let Some(conn) = conn {
Ok(conn)
} else {
Err(DbError::ConnectError(ConnectError::NoSuchPoolConnection))
}
}
#[cfg(feature = "with-mysql")]
Platform::Mysql => {
let conn: Option<&ConnPool> = self.0.get(db_url);
if let Some(conn) = conn {
Ok(conn)
} else {
Err(DbError::ConnectError(ConnectError::NoSuchPoolConnection))
}
}
Platform::Unsupported(scheme) => {
Err(DbError::ConnectError(ConnectError::UnsupportedDb(scheme)))
}
}
}
Err(e) => Err(DbError::ConnectError(ConnectError::ParseError(e))),
}
}
/// get a usable database connection from
pub fn connect(&mut self, db_url: &str) -> Result<PooledConn, DbError> {
let pool = self.get_pool(db_url)?;
match *pool {
#[cfg(feature = "with-postgres")]
ConnPool::PoolPg(ref pool_pg) => {
let pooled_conn = pool_pg.get();
match pooled_conn {
Ok(pooled_conn) => Ok(PooledConn::PooledPg(Box::new(pooled_conn))),
Err(e) => Err(DbError::ConnectError(ConnectError::R2d2Error(e))),
}
}
#[cfg(feature = "with-sqlite")]
ConnPool::PoolSq(ref pool_sq) => {
let pooled_conn = pool_sq.get();
match pooled_conn {
Ok(pooled_conn) => Ok(PooledConn::PooledSq(Box::new(pooled_conn))),
Err(e) => Err(DbError::ConnectError(ConnectError::R2d2Error(e))),
}
}
#[cfg(feature = "with-mysql")]
ConnPool::PoolMy(ref pool_my) => {
let pooled_conn = pool_my.get();
match pooled_conn {
Ok(pooled_conn) => Ok(PooledConn::PooledMy(Box::new(pooled_conn))),
Err(e) => Err(DbError::ConnectError(ConnectError::R2d2Error(e))),
}
}
}
}
/// get a database instance with a connection, ready to send sql statements
pub fn db(&mut self, db_url: &str) -> Result<DBPlatform, DbError> {
let pooled_conn = self.connect(db_url)?;
match pooled_conn {
#[cfg(feature = "with-postgres")]
PooledConn::PooledPg(pooled_pg) => {
Ok(DBPlatform::Postgres(Box::new(PostgresDB(*pooled_pg))))
}
#[cfg(feature = "with-sqlite")]
PooledConn::PooledSq(pooled_sq) => {
Ok(DBPlatform::Sqlite(Box::new(SqliteDB(*pooled_sq))))
}
#[cfg(feature = "with-mysql")]
_ => panic!("mysql unsupported in `db()`"),
}
}
pub fn em(&mut self, db_url: &str) -> Result<EntityManager, DbError> {
let db = self.db(db_url)?;
Ok(EntityManager(db))
}
pub fn dm(&mut self, db_url: &str) -> Result<DaoManager, DbError> {
let db = self.db(db_url)?;
Ok(DaoManager(db))
}
/// get the pool for this specific db_url, create one if it doesn't have yet.
fn get_pool2(&self, db_url: &str) -> Result<&ConnPool, DbError> {
let platform: Result<Platform, ParseError> = TryFrom::try_from(db_url);
match platform {
Ok(platform) => {
match platform {
#[cfg(feature = "with-postgres")]
Platform::Postgres => {
let conn: Option<&ConnPool> = self.0.get(db_url);
if let Some(conn) = conn {
Ok(conn)
} else {
Err(DbError::ConnectError(ConnectError::NoSuchPoolConnection))
}
}
#[cfg(feature = "with-sqlite")]
Platform::Sqlite(_path) => {
info!("getting sqlite pool");
let conn: Option<&ConnPool> = self.0.get(db_url);
if let Some(conn) = conn {
Ok(conn)
} else {
Err(DbError::ConnectError(ConnectError::NoSuchPoolConnection))
}
}
#[cfg(feature = "with-mysql")]
Platform::Mysql => {
let conn: Option<&ConnPool> = self.0.get(db_url);
if let Some(conn) = conn {
Ok(conn)
} else {
Err(DbError::ConnectError(ConnectError::NoSuchPoolConnection))
}
}
Platform::Unsupported(scheme) => {
Err(DbError::ConnectError(ConnectError::UnsupportedDb(scheme)))
}
}
}
Err(e) => Err(DbError::ConnectError(ConnectError::ParseError(e))),
}
}
/// get a usable database connection from
pub fn connect2(&self, db_url: &str) -> Result<PooledConn, DbError> {
let pool = self.get_pool2(db_url)?;
match *pool {
#[cfg(feature = "with-postgres")]
ConnPool::PoolPg(ref pool_pg) => {
let pooled_conn = pool_pg.get();
match pooled_conn {
Ok(pooled_conn) => Ok(PooledConn::PooledPg(Box::new(pooled_conn))),
Err(e) => Err(DbError::ConnectError(ConnectError::R2d2Error(e))),
}
}
#[cfg(feature = "with-sqlite")]
ConnPool::PoolSq(ref pool_sq) => {
let pooled_conn = pool_sq.get();
match pooled_conn {
Ok(pooled_conn) => Ok(PooledConn::PooledSq(Box::new(pooled_conn))),
Err(e) => Err(DbError::ConnectError(ConnectError::R2d2Error(e))),
}
}
#[cfg(feature = "with-mysql")]
ConnPool::PoolMy(ref pool_my) => {
let pooled_conn = pool_my.get();
match pooled_conn {
Ok(pooled_conn) => Ok(PooledConn::PooledMy(Box::new(pooled_conn))),
Err(e) => Err(DbError::ConnectError(ConnectError::R2d2Error(e))),
}
}
}
}
/// get a database instance with a connection, ready to send sql statements
pub fn db_mut(&self, db_url: &str) -> Result<DBPlatformMut, DbError> {
let pooled_conn = self.connect2(db_url)?;
#[allow(unreachable_patterns)]
match pooled_conn {
#[cfg(feature = "with-mysql")]
PooledConn::PooledMy(pooled_sq) => {
Ok(DBPlatformMut::Mysql(Box::new(MysqlDB(*pooled_sq))))
}
_ => panic!("postgres and sqlite unsupported in `db_mut()`"),
}
}
pub fn em_mut(&self, db_url: &str) -> Result<EntityManagerMut, DbError> {
let db = self.db_mut(db_url)?;
Ok(EntityManagerMut(db))
}
}
pub fn test_connection(db_url: &str) -> Result<(), DbError> {
let platform: Result<Platform, ParseError> = TryFrom::try_from(db_url);
match platform {
Ok(platform) => {
match platform {
#[cfg(feature = "with-postgres")]
Platform::Postgres => {
pg::test_connection(db_url)?;
Ok(())
}
#[cfg(feature = "with-sqlite")]
Platform::Sqlite(path) => {
info!("testing connection: {}", path);
sq::test_connection(&path)?;
Ok(())
}
#[cfg(feature = "with-mysql")]
Platform::Mysql => {
my::test_connection(db_url)?;
Ok(())
}
Platform::Unsupported(scheme) => {
Err(DbError::ConnectError(ConnectError::UnsupportedDb(scheme)))
}
}
}
Err(e) => Err(DbError::ConnectError(ConnectError::ParseError(e))),
}
}
#[cfg(test)]
#[cfg(feature = "with-postgres")]
mod tests_pg {
use super::*;
#[test]
fn connect() {
let db_url = "postgres://postgres:p0stgr3s@localhost:5432/sakila";
let mut pool = Pool::new();
pool.ensure(db_url).expect("Unable to initialize pool");
let pooled = pool.get_pool(db_url);
match pooled {
Ok(_) => info!("ok"),
Err(ref e) => info!("error: {:?}", e),
}
assert!(pooled.is_ok());
}
#[test]
fn connect_no_ensure() {
let db_url = "postgres://postgres:p0stgr3s@localhost:5432/sakila";
let mut pool = Pool::new();
assert!(pool.get_pool(db_url).is_ok());
}
}
| {
self.0.insert(db_url.to_string(), ConnPool::PoolSq(pool_sq));
} |
parser.py | import sqlite3
con = sqlite3.connect('./public/index.db')
import os
def recipe_already_indexed(name):
cur = con.cursor()
cur.execute("SELECT * FROM recipes_info WHERE path=?", (name,))
rows = cur.fetchall()
for r in rows: print(r)
return len(rows) > 0
def add_tag(name, recipe_id):
print(name)
cur = con.cursor()
cur.execute("SELECT tag_id FROM tags WHERE name=?", (name,) )
rows = cur.fetchall()
id = 0
if len(rows) == 0:
sql = '''INSERT INTO tags(name) VALUES(?)'''
cur.execute(sql, (name,))
con.commit()
id = cur.lastrowid
else:
id = rows[0][0]
sql = '''INSERT INTO recipes_tags(recipe_id, tag_id) VALUES(?,?)'''
print(f"recipe id{recipe_id} id{id}")
cur.execute(sql, (recipe_id,id))
con.commit()
return rows
def add_ingredient(name, quantity, recipe_id):
print(name)
cur = con.cursor()
cur.execute("SELECT ingredient_id FROM ingredients WHERE name=?", (name,) )
rows = cur.fetchall()
id = 0 | cur.execute(sql, (name,))
con.commit()
id = cur.lastrowid
else:
id = rows[0][0]
sql = '''INSERT INTO recipes_ingredients(recipe_id, ingredient_id, quantity) VALUES(?,?,?)'''
cur.execute(sql, (recipe_id,id,quantity,))
con.commit()
return rows
def add_new_recipe(title, path):
cur = con.cursor()
sql = ''' INSERT INTO recipes_info(title, path)
VALUES(?,?) '''
cur.execute(sql, (title, path))
con.commit()
id = cur.lastrowid
print(id)
return id
def add_new_tag(recipe_id, name):
cur = con.cursor()
sql = ''' INSERT INTO recipes_tags(name, recipe_id)
VALUES(?,?) '''
cur.execute(sql, (name, recipe_id))
con.commit()
return id
def add_new_ingredient(recipe_id, info):
cur = con.cursor()
sql = ''' INSERT INTO recipes_ingredients(info, recipe_id)
VALUES(?,?) '''
cur.execute(sql, (info, recipe_id))
con.commit()
return id
def parse_recipe(folder, filename):
if recipe_already_indexed(filename): return
section = 0
title = ''
section_title = True
tags = []
ingredients = []
path = os.path.join(folder, filename)
with open(path) as f:
recipe_id = -1;
for index, line in enumerate(f):
print("Line {}: {}".format(index, line.strip()))
if line == '\n':
section += 1
section_title = True
continue
if section == 0:
# Title Section
title = line[2:].strip()
print(f"Adding new recipe {title} from {filename}")
recipe_id = add_new_recipe(title, filename)
elif section == 1:
# Tags Section
if section_title: section_title = False; continue
tag = ''.join(ch for ch in line if ch.isalnum())
print(f"Tag => {tag}")
#add_new_tag(recipe_id, tag)
add_tag(tag, recipe_id)
elif section == 2:
# Ingredients Section
if section_title: section_title = False; continue
# 0 > "-"
# 1 > ammount
# 2.. name
ingredient = line.split(' ');
ammount = ingredient[1]
name = ' '.join(ingredient[2:]).strip()
add_ingredient(name, ammount, recipe_id)
elif section == 3:
break
print(tags)
print(ingredients)
def parse(path):
for filename in os.listdir(path):
if filename.endswith(".md"):
# print()
parse_recipe(path, filename)
continue
else:
continue
def main():
parse('./recipes')
if __name__ == "__main__":
main() | if len(rows) == 0:
sql = '''INSERT INTO ingredients(name) VALUES(?)''' |
branched_action_values.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
from cached_property import cached_property
from chainer import functions as F
from chainerrl.action_value import ActionValue
class BranchedActionValue(ActionValue):
"""Q-function output for a branched action space.
Args:
branches (list):
Each element of the list is a Q-function for an action dimension
"""
def __init__(self, branches, q_values_formatter=lambda x: x):
self.branches = branches
self.q_values_formatter = q_values_formatter
@cached_property
def greedy_actions(self): |
return F.hstack(actions)
@cached_property
def max(self):
chosen_q_values = []
for branch in self.branches:
chosen_q_values.append(branch.max.reshape(-1, 1))
return F.hstack(chosen_q_values)
def evaluate_actions(self, actions):
branch_q_values = []
for i, branch in enumerate(self.branches):
branch_actions = actions[:, i]
branch_q_values.append(branch.evaluate_actions(
branch_actions).reshape(-1, 1))
return F.hstack(branch_q_values)
@property
def params(self):
branch_params = []
for branch in self.branches:
branch_params.extend(list(branch.params))
return tuple(branch_params) | actions = []
for branch in self.branches:
actions.append(branch.q_values.array.argmax(axis=1).reshape(-1, 1)) |
points.py | # -*- coding: utf-8 -*-
import hashlib, random
def sha(s):
return hashlib.sha256(s).hexdigest()[:16]
def _salt():
return str(random.randint(1,99999999))
def save_point(phash,u):
|
def check_hash(s):
p = open('points.txt').read().splitlines()
for i,n in enumerate(p,1):
ud = n.split(':',1)
if ud[0] == s: return ud[1].decode('utf-8'),i
return '', None
if __name__ == '__main__':
import sys
user = ' '.join(sys.argv[1:])
if user:
phash = sha(user+_salt())
save_point(phash,user)
print user; print phash
| open('points.txt','a').write('%s:%s\n' % (phash,u)) |
component.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
__all__ = ['ComponentArgs', 'Component']
@pulumi.input_type
class ComponentArgs:
def __init__(__self__, *,
application_type: pulumi.Input[Union[str, 'ApplicationType']],
kind: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_name: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a Component resource.
:param pulumi.Input[Union[str, 'ApplicationType']] application_type: Type of application being monitored.
:param pulumi.Input[str] kind: The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
:param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive.
:param pulumi.Input[bool] disable_ip_masking: Disable IP masking.
:param pulumi.Input[Union[str, 'FlowType']] flow_type: Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
:param pulumi.Input[str] hockey_app_id: The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
:param pulumi.Input[bool] immediate_purge_data_on30_days: Purge data immediately after 30 days.
:param pulumi.Input[Union[str, 'IngestionMode']] ingestion_mode: Indicates the flow of the ingestion.
:param pulumi.Input[str] location: Resource location
:param pulumi.Input[Union[str, 'RequestSource']] request_source: Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
:param pulumi.Input[str] resource_name: The name of the Application Insights component resource.
:param pulumi.Input[int] retention_in_days: Retention period in days.
:param pulumi.Input[float] sampling_percentage: Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags
"""
if application_type is None:
application_type = 'web'
pulumi.set(__self__, "application_type", application_type)
pulumi.set(__self__, "kind", kind)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if disable_ip_masking is not None:
pulumi.set(__self__, "disable_ip_masking", disable_ip_masking)
if flow_type is None:
flow_type = 'Bluefield'
if flow_type is not None:
pulumi.set(__self__, "flow_type", flow_type)
if hockey_app_id is not None:
pulumi.set(__self__, "hockey_app_id", hockey_app_id)
if immediate_purge_data_on30_days is not None:
pulumi.set(__self__, "immediate_purge_data_on30_days", immediate_purge_data_on30_days)
if ingestion_mode is None:
ingestion_mode = 'ApplicationInsights'
if ingestion_mode is not None:
pulumi.set(__self__, "ingestion_mode", ingestion_mode)
if location is not None:
pulumi.set(__self__, "location", location)
if request_source is None:
request_source = 'rest'
if request_source is not None:
pulumi.set(__self__, "request_source", request_source)
if resource_name is not None:
pulumi.set(__self__, "resource_name", resource_name)
if retention_in_days is None:
retention_in_days = 90
if retention_in_days is not None:
pulumi.set(__self__, "retention_in_days", retention_in_days)
if sampling_percentage is not None:
pulumi.set(__self__, "sampling_percentage", sampling_percentage)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="applicationType")
def application_type(self) -> pulumi.Input[Union[str, 'ApplicationType']]:
"""
Type of application being monitored.
"""
return pulumi.get(self, "application_type")
@application_type.setter
def application_type(self, value: pulumi.Input[Union[str, 'ApplicationType']]):
pulumi.set(self, "application_type", value)
@property
@pulumi.getter
def kind(self) -> pulumi.Input[str]:
"""
The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
"""
return pulumi.get(self, "kind")
@kind.setter
def kind(self, value: pulumi.Input[str]):
pulumi.set(self, "kind", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group. The name is case insensitive.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="disableIpMasking")
def disable_ip_masking(self) -> Optional[pulumi.Input[bool]]:
"""
Disable IP masking.
"""
return pulumi.get(self, "disable_ip_masking")
@disable_ip_masking.setter
def disable_ip_masking(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "disable_ip_masking", value)
@property
@pulumi.getter(name="flowType")
def flow_type(self) -> Optional[pulumi.Input[Union[str, 'FlowType']]]:
"""
Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
"""
return pulumi.get(self, "flow_type")
@flow_type.setter
def flow_type(self, value: Optional[pulumi.Input[Union[str, 'FlowType']]]):
pulumi.set(self, "flow_type", value)
@property
@pulumi.getter(name="hockeyAppId")
def hockey_app_id(self) -> Optional[pulumi.Input[str]]:
"""
The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
"""
return pulumi.get(self, "hockey_app_id")
@hockey_app_id.setter
def hockey_app_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "hockey_app_id", value)
@property
@pulumi.getter(name="immediatePurgeDataOn30Days")
def immediate_purge_data_on30_days(self) -> Optional[pulumi.Input[bool]]:
"""
Purge data immediately after 30 days.
"""
return pulumi.get(self, "immediate_purge_data_on30_days")
@immediate_purge_data_on30_days.setter
def immediate_purge_data_on30_days(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "immediate_purge_data_on30_days", value)
@property
@pulumi.getter(name="ingestionMode")
def ingestion_mode(self) -> Optional[pulumi.Input[Union[str, 'IngestionMode']]]:
"""
Indicates the flow of the ingestion.
"""
return pulumi.get(self, "ingestion_mode")
@ingestion_mode.setter
def ingestion_mode(self, value: Optional[pulumi.Input[Union[str, 'IngestionMode']]]):
pulumi.set(self, "ingestion_mode", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Resource location
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="requestSource")
def request_source(self) -> Optional[pulumi.Input[Union[str, 'RequestSource']]]:
"""
Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
"""
return pulumi.get(self, "request_source")
@request_source.setter
def request_source(self, value: Optional[pulumi.Input[Union[str, 'RequestSource']]]):
pulumi.set(self, "request_source", value)
@property
@pulumi.getter(name="resourceName")
def resource_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the Application Insights component resource.
"""
return pulumi.get(self, "resource_name")
@resource_name.setter
def resource_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "resource_name", value)
@property
@pulumi.getter(name="retentionInDays")
def retention_in_days(self) -> Optional[pulumi.Input[int]]:
"""
Retention period in days.
"""
return pulumi.get(self, "retention_in_days")
@retention_in_days.setter
def | (self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "retention_in_days", value)
@property
@pulumi.getter(name="samplingPercentage")
def sampling_percentage(self) -> Optional[pulumi.Input[float]]:
"""
Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
"""
return pulumi.get(self, "sampling_percentage")
@sampling_percentage.setter
def sampling_percentage(self, value: Optional[pulumi.Input[float]]):
pulumi.set(self, "sampling_percentage", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Resource tags
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
class Component(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None,
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_name_: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
"""
An Application Insights component definition.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[Union[str, 'ApplicationType']] application_type: Type of application being monitored.
:param pulumi.Input[bool] disable_ip_masking: Disable IP masking.
:param pulumi.Input[Union[str, 'FlowType']] flow_type: Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
:param pulumi.Input[str] hockey_app_id: The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
:param pulumi.Input[bool] immediate_purge_data_on30_days: Purge data immediately after 30 days.
:param pulumi.Input[Union[str, 'IngestionMode']] ingestion_mode: Indicates the flow of the ingestion.
:param pulumi.Input[str] kind: The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
:param pulumi.Input[str] location: Resource location
:param pulumi.Input[Union[str, 'RequestSource']] request_source: Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
:param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive.
:param pulumi.Input[str] resource_name_: The name of the Application Insights component resource.
:param pulumi.Input[int] retention_in_days: Retention period in days.
:param pulumi.Input[float] sampling_percentage: Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: ComponentArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
An Application Insights component definition.
:param str resource_name: The name of the resource.
:param ComponentArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ComponentArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
application_type: Optional[pulumi.Input[Union[str, 'ApplicationType']]] = None,
disable_ip_masking: Optional[pulumi.Input[bool]] = None,
flow_type: Optional[pulumi.Input[Union[str, 'FlowType']]] = None,
hockey_app_id: Optional[pulumi.Input[str]] = None,
immediate_purge_data_on30_days: Optional[pulumi.Input[bool]] = None,
ingestion_mode: Optional[pulumi.Input[Union[str, 'IngestionMode']]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
request_source: Optional[pulumi.Input[Union[str, 'RequestSource']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_name_: Optional[pulumi.Input[str]] = None,
retention_in_days: Optional[pulumi.Input[int]] = None,
sampling_percentage: Optional[pulumi.Input[float]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = ComponentArgs.__new__(ComponentArgs)
if application_type is None:
application_type = 'web'
if application_type is None and not opts.urn:
raise TypeError("Missing required property 'application_type'")
__props__.__dict__["application_type"] = application_type
__props__.__dict__["disable_ip_masking"] = disable_ip_masking
if flow_type is None:
flow_type = 'Bluefield'
__props__.__dict__["flow_type"] = flow_type
__props__.__dict__["hockey_app_id"] = hockey_app_id
__props__.__dict__["immediate_purge_data_on30_days"] = immediate_purge_data_on30_days
if ingestion_mode is None:
ingestion_mode = 'ApplicationInsights'
__props__.__dict__["ingestion_mode"] = ingestion_mode
if kind is None and not opts.urn:
raise TypeError("Missing required property 'kind'")
__props__.__dict__["kind"] = kind
__props__.__dict__["location"] = location
if request_source is None:
request_source = 'rest'
__props__.__dict__["request_source"] = request_source
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["resource_name"] = resource_name_
if retention_in_days is None:
retention_in_days = 90
__props__.__dict__["retention_in_days"] = retention_in_days
__props__.__dict__["sampling_percentage"] = sampling_percentage
__props__.__dict__["tags"] = tags
__props__.__dict__["app_id"] = None
__props__.__dict__["application_id"] = None
__props__.__dict__["connection_string"] = None
__props__.__dict__["creation_date"] = None
__props__.__dict__["hockey_app_token"] = None
__props__.__dict__["instrumentation_key"] = None
__props__.__dict__["name"] = None
__props__.__dict__["private_link_scoped_resources"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["tenant_id"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:insights/v20150501:Component"), pulumi.Alias(type_="azure-native:insights:Component"), pulumi.Alias(type_="azure-nextgen:insights:Component"), pulumi.Alias(type_="azure-native:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20180501preview:Component"), pulumi.Alias(type_="azure-native:insights/v20200202:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202:Component"), pulumi.Alias(type_="azure-native:insights/v20200202preview:Component"), pulumi.Alias(type_="azure-nextgen:insights/v20200202preview:Component")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(Component, __self__).__init__(
'azure-native:insights/v20150501:Component',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Component':
"""
Get an existing Component resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = ComponentArgs.__new__(ComponentArgs)
__props__.__dict__["app_id"] = None
__props__.__dict__["application_id"] = None
__props__.__dict__["application_type"] = None
__props__.__dict__["connection_string"] = None
__props__.__dict__["creation_date"] = None
__props__.__dict__["disable_ip_masking"] = None
__props__.__dict__["flow_type"] = None
__props__.__dict__["hockey_app_id"] = None
__props__.__dict__["hockey_app_token"] = None
__props__.__dict__["immediate_purge_data_on30_days"] = None
__props__.__dict__["ingestion_mode"] = None
__props__.__dict__["instrumentation_key"] = None
__props__.__dict__["kind"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["private_link_scoped_resources"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["request_source"] = None
__props__.__dict__["retention_in_days"] = None
__props__.__dict__["sampling_percentage"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["tenant_id"] = None
__props__.__dict__["type"] = None
return Component(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="appId")
def app_id(self) -> pulumi.Output[str]:
"""
Application Insights Unique ID for your Application.
"""
return pulumi.get(self, "app_id")
@property
@pulumi.getter(name="applicationId")
def application_id(self) -> pulumi.Output[str]:
"""
The unique ID of your application. This field mirrors the 'Name' field and cannot be changed.
"""
return pulumi.get(self, "application_id")
@property
@pulumi.getter(name="applicationType")
def application_type(self) -> pulumi.Output[str]:
"""
Type of application being monitored.
"""
return pulumi.get(self, "application_type")
@property
@pulumi.getter(name="connectionString")
def connection_string(self) -> pulumi.Output[str]:
"""
Application Insights component connection string.
"""
return pulumi.get(self, "connection_string")
@property
@pulumi.getter(name="creationDate")
def creation_date(self) -> pulumi.Output[str]:
"""
Creation Date for the Application Insights component, in ISO 8601 format.
"""
return pulumi.get(self, "creation_date")
@property
@pulumi.getter(name="disableIpMasking")
def disable_ip_masking(self) -> pulumi.Output[Optional[bool]]:
"""
Disable IP masking.
"""
return pulumi.get(self, "disable_ip_masking")
@property
@pulumi.getter(name="flowType")
def flow_type(self) -> pulumi.Output[Optional[str]]:
"""
Used by the Application Insights system to determine what kind of flow this component was created by. This is to be set to 'Bluefield' when creating/updating a component via the REST API.
"""
return pulumi.get(self, "flow_type")
@property
@pulumi.getter(name="hockeyAppId")
def hockey_app_id(self) -> pulumi.Output[Optional[str]]:
"""
The unique application ID created when a new application is added to HockeyApp, used for communications with HockeyApp.
"""
return pulumi.get(self, "hockey_app_id")
@property
@pulumi.getter(name="hockeyAppToken")
def hockey_app_token(self) -> pulumi.Output[str]:
"""
Token used to authenticate communications with between Application Insights and HockeyApp.
"""
return pulumi.get(self, "hockey_app_token")
@property
@pulumi.getter(name="immediatePurgeDataOn30Days")
def immediate_purge_data_on30_days(self) -> pulumi.Output[Optional[bool]]:
"""
Purge data immediately after 30 days.
"""
return pulumi.get(self, "immediate_purge_data_on30_days")
@property
@pulumi.getter(name="ingestionMode")
def ingestion_mode(self) -> pulumi.Output[Optional[str]]:
"""
Indicates the flow of the ingestion.
"""
return pulumi.get(self, "ingestion_mode")
@property
@pulumi.getter(name="instrumentationKey")
def instrumentation_key(self) -> pulumi.Output[str]:
"""
Application Insights Instrumentation key. A read-only value that applications can use to identify the destination for all telemetry sent to Azure Application Insights. This value will be supplied upon construction of each new Application Insights component.
"""
return pulumi.get(self, "instrumentation_key")
@property
@pulumi.getter
def kind(self) -> pulumi.Output[str]:
"""
The kind of application that this component refers to, used to customize UI. This value is a freeform string, values should typically be one of the following: web, ios, other, store, java, phone.
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
"""
Resource location
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Azure resource name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="privateLinkScopedResources")
def private_link_scoped_resources(self) -> pulumi.Output[Sequence['outputs.PrivateLinkScopedResourceResponse']]:
"""
List of linked private link scope resources.
"""
return pulumi.get(self, "private_link_scoped_resources")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
Current state of this component: whether or not is has been provisioned within the resource group it is defined. Users cannot change this value but are able to read from it. Values will include Succeeded, Deploying, Canceled, and Failed.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="requestSource")
def request_source(self) -> pulumi.Output[Optional[str]]:
"""
Describes what tool created this Application Insights component. Customers using this API should set this to the default 'rest'.
"""
return pulumi.get(self, "request_source")
@property
@pulumi.getter(name="retentionInDays")
def retention_in_days(self) -> pulumi.Output[Optional[int]]:
"""
Retention period in days.
"""
return pulumi.get(self, "retention_in_days")
@property
@pulumi.getter(name="samplingPercentage")
def sampling_percentage(self) -> pulumi.Output[Optional[float]]:
"""
Percentage of the data produced by the application being monitored that is being sampled for Application Insights telemetry.
"""
return pulumi.get(self, "sampling_percentage")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Resource tags
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="tenantId")
def tenant_id(self) -> pulumi.Output[str]:
"""
Azure Tenant Id.
"""
return pulumi.get(self, "tenant_id")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Azure resource type
"""
return pulumi.get(self, "type")
| retention_in_days |
metrics.py | """Implementations of metrics for 3D semantic segmentation."""
import tensorflow as tf
def average_volume_difference():
raise NotImplementedError()
def dice(y_true, y_pred, axis=(1, 2, 3, 4)):
"""Calculate Dice similarity between labels and predictions.
Dice similarity is in [0, 1], where 1 is perfect overlap and 0 is no
overlap. If both labels and predictions are empty (e.g., all background),
then Dice similarity is 1.
If we assume the inputs are rank 5 [`(batch, x, y, z, classes)`], then an
axis parameter of `(1, 2, 3)` will result in a tensor that contains a Dice
score for every class in every item in the batch. The shape of this tensor
will be `(batch, classes)`. If the inputs only have one class (e.g., binary
segmentation), then an axis parameter of `(1, 2, 3, 4)` should be used.
This will result in a tensor of shape `(batch,)`, where every value is the
Dice similarity for that prediction.
Implemented according to https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4533825/#Equ6
Returns
-------
Tensor of Dice similarities.
Citations
---------
Taha AA, Hanbury A. Metrics for evaluating 3D medical image segmentation:
analysis, selection, and tool. BMC Med Imaging. 2015;15:29. Published 2015
Aug 12. doi:10.1186/s12880-015-0068-x
"""
y_pred = tf.convert_to_tensor(y_pred)
y_true = tf.cast(y_true, y_pred.dtype)
eps = tf.keras.backend.epsilon()
intersection = tf.reduce_sum(y_true * y_pred, axis=axis)
summation = tf.reduce_sum(y_true, axis=axis) + tf.reduce_sum(y_pred, axis=axis)
return (2 * intersection + eps) / (summation + eps)
def generalized_dice(y_true, y_pred, axis=(1, 2, 3)):
"""Calculate Generalized Dice similarity. This is useful for multi-class
predictions.
If we assume the inputs are rank 5 [`(batch, x, y, z, classes)`], then an
axis parameter of `(1, 2, 3)` should be used. This will result in a tensor
of shape `(batch,)`, where every value is the Generalized Dice similarity
for that prediction, across all classes.
Returns
-------
Tensor of Generalized Dice similarities.
"""
y_pred = tf.convert_to_tensor(y_pred)
y_true = tf.cast(y_true, y_pred.dtype)
if y_true.get_shape().ndims < 2 or y_pred.get_shape().ndims < 2:
raise ValueError("y_true and y_pred must be at least rank 2.")
epsilon = tf.keras.backend.epsilon()
w = tf.math.reciprocal(tf.square(tf.reduce_sum(y_true, axis=axis)))
w = tf.where(tf.math.is_finite(w), w, epsilon)
num = 2 * tf.reduce_sum(w * tf.reduce_sum(y_true * y_pred, axis= axis), axis=-1)
den = tf.reduce_sum(w * tf.reduce_sum(y_true + y_pred, axis= axis), axis=-1)
gdice = num/den
gdice = tf.where(tf.math.is_finite(gdice), gdice, tf.zeros_like(gdice))
return gdice
def hamming(y_true, y_pred, axis=(1, 2, 3)):
y_pred = tf.convert_to_tensor(y_pred)
y_true = tf.cast(y_true, y_pred.dtype)
return tf.reduce_mean(tf.not_equal(y_pred, y_true), axis=axis)
def | ():
raise NotADirectoryError()
def jaccard(y_true, y_pred, axis=(1, 2, 3, 4)):
"""Calculate Jaccard similarity between labels and predictions.
Jaccard similarity is in [0, 1], where 1 is perfect overlap and 0 is no
overlap. If both labels and predictions are empty (e.g., all background),
then Jaccard similarity is 1.
If we assume the inputs are rank 5 [`(batch, x, y, z, classes)`], then an
axis parameter of `(1, 2, 3)` will result in a tensor that contains a Jaccard
score for every class in every item in the batch. The shape of this tensor
will be `(batch, classes)`. If the inputs only have one class (e.g., binary
segmentation), then an axis parameter of `(1, 2, 3, 4)` should be used.
This will result in a tensor of shape `(batch,)`, where every value is the
Jaccard similarity for that prediction.
Implemented according to https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4533825/#Equ7
Returns
-------
Tensor of Jaccard similarities.
Citations
---------
Taha AA, Hanbury A. Metrics for evaluating 3D medical image segmentation:
analysis, selection, and tool. BMC Med Imaging. 2015;15:29. Published 2015
Aug 12. doi:10.1186/s12880-015-0068-x
"""
y_pred = tf.convert_to_tensor(y_pred)
y_true = tf.cast(y_true, y_pred.dtype)
eps = tf.keras.backend.epsilon()
intersection = tf.reduce_sum(y_true * y_pred, axis=axis)
union = tf.reduce_sum(y_true, axis=axis) + tf.reduce_sum(y_pred, axis=axis)
return (intersection + eps) / (union - intersection + eps)
def tversky(y_true, y_pred, axis=(1, 2, 3), alpha=0.3, beta=0.7):
y_pred = tf.convert_to_tensor(y_pred)
y_true = tf.cast(y_true, y_pred.dtype)
if y_true.get_shape().ndims < 2 or y_pred.get_shape().ndims < 2:
raise ValueError("y_true and y_pred must be at least rank 2.")
eps = tf.keras.backend.epsilon()
num = tf.reduce_sum(y_pred * y_true, axis=axis)
den = (
num
+ alpha * tf.reduce_sum(y_pred * (1 - y_true), axis=axis)
+ beta * tf.reduce_sum((1 - y_pred) * y_true, axis=axis)
)
# Sum over classes.
return tf.reduce_sum((num + eps) / (den + eps), axis=-1)
def dice_coef_multilabel(y_true, y_pred):
n_classes= tf.shape(y_pred)[-1]
dice_coeff=0
for index in range(n_classes):
dice_coeff -= dice(y_true[:,:,:,:,index], y_pred[:,:,:,:,index])
return dice_coeff
| haussdorf |
test_sklearn_pipeline.py | import unittest
import numpy as np
from sklearn import datasets
from sklearn.compose import ColumnTransformer
from sklearn.datasets import load_iris, load_diabetes
from sklearn.svm import LinearSVC, LinearSVR
from sklearn.datasets import make_regression
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression, RidgeCV
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, FeatureUnion, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler, MinMaxScaler
import hummingbird.ml
from hummingbird.ml._utils import pandas_installed, onnx_runtime_installed
from hummingbird.ml import constants
from onnxconverter_common.data_types import (
FloatTensorType,
Int64TensorType,
StringTensorType,
)
try:
from sklearn.impute import SimpleImputer
except ImportError:
from sklearn.preprocessing import Imputer as SimpleImputer
try:
from sklearn.ensemble import StackingClassifier, StackingRegressor
except ImportError:
StackingClassifier = None
if pandas_installed():
import pandas
class TestSklearnPipeline(unittest.TestCase):
def test_pipeline(self):
data = np.array([[0, 0], [0, 0], [1, 1], [1, 1]], dtype=np.float32)
scaler = StandardScaler()
scaler.fit(data)
model = Pipeline([("scaler1", scaler), ("scaler2", scaler)])
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06,
)
def test_pipeline2(self):
data = np.array([[0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [1.0, 1.0]], dtype=np.float32)
scaler = StandardScaler()
scaler.fit(data)
model = Pipeline([("scaler1", scaler), ("scaler2", scaler)])
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06,
)
def test_combine_inputs_union_in_pipeline(self):
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
data = np.array([[0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [1.0, 1.0]], dtype=np.float32)
model = Pipeline(
[
("scaler1", StandardScaler()),
("union", FeatureUnion([("scaler2", StandardScaler()), ("scaler3", MinMaxScaler())])),
]
)
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06,
)
def test_combine_inputs_floats_ints(self):
data = [[0, 0.0], [0, 0.0], [1, 1.0], [1, 1.0]]
scaler = StandardScaler()
scaler.fit(data)
model = Pipeline([("scaler1", scaler), ("scaler2", scaler)])
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_1(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1, 2] # ["vA", "vB", "vC"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
preprocessor = ColumnTransformer(transformers=[("num", numeric_transformer, numeric_features)])
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_string(self):
"""
TODO: Hummingbird does not yet support strings in this context. Should raise error.
When this feature is complete, change this test.
"""
# fit
titanic_url = "https://raw.githubusercontent.com/amueller/scipy-2017-sklearn/091d371/notebooks/datasets/titanic3.csv"
data = pandas.read_csv(titanic_url)
X = data.drop("survived", axis=1)
y = data["survived"]
# SimpleImputer on string is not available for string
# in ONNX-ML specifications.
# So we do it beforehand.
X["pclass"].fillna("missing", inplace=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
numeric_features = ["age", "fare"]
numeric_transformer = Pipeline(steps=[("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler())])
categorical_features = ["pclass"]
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
]
)
clf = Pipeline(steps=[("preprocessor", preprocessor), ("classifier", LogisticRegression(solver="liblinear"))])
to_drop = {"parch", "sibsp", "cabin", "ticket", "name", "body", "home.dest", "boat", "sex", "embarked"}
X_train = X_train.copy()
X_test = X_test.copy()
X_train["pclass"] = X_train["pclass"].astype(np.int64)
X_test["pclass"] = X_test["pclass"].astype(np.int64)
X_train = X_train.drop(to_drop, axis=1)
X_test = X_test.drop(to_drop, axis=1)
clf.fit(X_train, y_train)
torch_model = hummingbird.ml.convert(clf, "torch", X_test)
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
clf.predict(X_test), torch_model.predict(X_test), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1, 2] # ["vA", "vB", "vC"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
]
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_pandas(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1, 2] # ["vA", "vB", "vC"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
]
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch", X_test)
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_pandas_ts(self):
iris = datasets.load_iris()
X = np.array(iris.data[:, :3], np.float32) # If we don't use float32 here, with python 3.5 and torch 1.5.1 will fail.
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1, 2] # ["vA", "vB", "vC"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
]
)
model = Pipeline(steps=[("preprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch.jit", X_test)
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_weights(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1, 2] # ["vA", "vB", "vC"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
transformer_weights={"num": 2, "cat": 3},
)
model = Pipeline(steps=[("preprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_weights_pandas(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1, 2] # ["vA", "vB", "vC"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
transformer_weights={"num": 2, "cat": 3},
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch", X_test)
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_drop(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1] # ["vA", "vB"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
transformer_weights={"num": 2, "cat": 3},
remainder="drop",
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_drop_noweights(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1] # ["vA", "vB"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
remainder="drop",
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_passthrough(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1] # ["vA", "vB"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
transformer_weights={"num": 2, "cat": 3},
remainder="passthrough",
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_passthrough_noweights(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = [0, 1] # ["vA", "vB"]
categorical_features = [3, 4] # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
remainder="passthrough",
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not pandas_installed(), reason="Test requires pandas installed")
def test_pipeline_column_transformer_passthrough_slice(self):
iris = datasets.load_iris()
X = iris.data[:, :3]
y = iris.target
X_train = pandas.DataFrame(X, columns=["vA", "vB", "vC"])
X_train["vcat"] = X_train["vA"].apply(lambda x: 1 if x > 0.5 else 2)
X_train["vcat2"] = X_train["vB"].apply(lambda x: 3 if x > 0.5 else 4)
y_train = y % 2
numeric_features = slice(0, 1) # ["vA", "vB"]
categorical_features = slice(3, 4) # ["vcat", "vcat2"]
classifier = LogisticRegression(
C=0.01, class_weight=dict(zip([False, True], [0.2, 0.8])), n_jobs=1, max_iter=10, solver="liblinear", tol=1e-3,
)
numeric_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(steps=[("onehot", OneHotEncoder(sparse=True, handle_unknown="ignore"))])
preprocessor = ColumnTransformer(
transformers=[
("num", numeric_transformer, numeric_features),
("cat", categorical_transformer, categorical_features),
],
transformer_weights={"num": 2, "cat": 3},
remainder="passthrough",
)
model = Pipeline(steps=[("precprocessor", preprocessor), ("classifier", classifier)])
model.fit(X_train, y_train)
X_test = X_train[:11]
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(
model.predict_proba(X_test), torch_model.predict_proba(X_test.values), rtol=1e-06, atol=1e-06,
)
# Taken from https://github.com/microsoft/hummingbird/issues/388https://github.com/microsoft/hummingbird/issues/388
def test_pipeline_pca_rf(self):
X, y = make_regression(n_samples=1000, n_features=8, n_informative=5, n_targets=1, random_state=0, shuffle=True)
pca = PCA(n_components=8, svd_solver="randomized", whiten=True)
clf = make_pipeline(StandardScaler(), pca, RandomForestRegressor(n_estimators=10, max_depth=30, random_state=0))
clf.fit(X, y)
model = hummingbird.ml.convert(clf, "pytorch")
prediction_sk = clf.predict([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])
prediction_hb = model.predict([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])
np.testing.assert_allclose(prediction_sk, prediction_hb, rtol=1e-06, atol=1e-06)
@unittest.skipIf(not onnx_runtime_installed(), reason="Test requires ORT installed")
def test_pipeline_many_inputs(self):
n_features = 18
X = np.random.rand(100, n_features)
y = np.random.randint(1000, size=100)
scaler_transformer = Pipeline(steps=[("scaler", StandardScaler())])
preprocessor = ColumnTransformer(transformers=[("scaling", scaler_transformer, list(range(n_features)))])
model = RandomForestRegressor(n_estimators=10, max_depth=9)
pipeline = Pipeline(steps=[("preprocessor", preprocessor), ("model", model)])
pipeline.fit(X, y)
X_test = tuple(np.split(X, n_features, axis=1))
hb_model = hummingbird.ml.convert(pipeline, "onnx", X_test)
assert len(hb_model.model.graph.input) == n_features
np.testing.assert_allclose(
pipeline.predict(X), np.array(hb_model.predict(X_test)).flatten(), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(not onnx_runtime_installed(), reason="Test requires ORT installed")
def test_pipeline_many_inputs_with_schema(self):
n_features = 5
X = np.random.rand(100, n_features)
y = np.random.randint(1000, size=100)
input_column_names = ["A", "B", "C", "D", "E"]
output_column_names = ["score"]
scaler_transformer = Pipeline(steps=[("scaler", StandardScaler())])
preprocessor = ColumnTransformer(transformers=[("scaling", scaler_transformer, list(range(n_features)))])
model = RandomForestRegressor(n_estimators=10, max_depth=9)
pipeline = Pipeline(steps=[("preprocessor", preprocessor), ("model", model)])
pipeline.fit(X, y)
X_test = tuple(np.split(X, n_features, axis=1))
extra_config = {constants.INPUT_NAMES: input_column_names, constants.OUTPUT_NAMES: output_column_names}
hb_model = hummingbird.ml.convert(pipeline, "onnx", X_test, extra_config=extra_config)
graph_inputs = [input.name for input in hb_model.model.graph.input]
graph_outputs = [output.name for output in hb_model.model.graph.output]
assert len(hb_model.model.graph.input) == n_features
assert graph_inputs == input_column_names
assert graph_outputs == output_column_names
@unittest.skipIf(StackingClassifier is None, reason="StackingClassifier not available in scikit-learn < 0.22")
def test_stacking_classifier(self):
X, y = load_iris(return_X_y=True)
estimators = [
("rf", RandomForestClassifier(n_estimators=10, random_state=42)),
("svr", make_pipeline(StandardScaler(), LogisticRegression(random_state=42))),
]
clf = StackingClassifier(estimators=estimators, final_estimator=LogisticRegression())
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
clf.fit(X_train, y_train)
hb_model = hummingbird.ml.convert(clf, "torch")
np.testing.assert_allclose(
clf.predict(X_test), hb_model.predict(X_test), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(StackingClassifier is None, reason="StackingClassifier not available in scikit-learn < 0.22")
def test_stacking_classifier_passthrough(self):
X, y = load_iris(return_X_y=True)
estimators = [
("rf", RandomForestClassifier(n_estimators=10, random_state=42)),
("svr", make_pipeline(StandardScaler(), LogisticRegression(random_state=42))),
]
clf = StackingClassifier(estimators=estimators, final_estimator=LogisticRegression(), passthrough=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
clf.fit(X_train, y_train)
hb_model = hummingbird.ml.convert(clf, "torch")
np.testing.assert_allclose(
clf.predict(X_test), hb_model.predict(X_test), rtol=1e-06, atol=1e-06,
)
@unittest.skipIf(StackingClassifier is None, reason="StackingClassifier not available in scikit-learn < 0.22")
def | (self):
X, y = load_iris(return_X_y=True)
estimators = [
("rf", RandomForestClassifier(n_estimators=10, random_state=42)),
("svr", make_pipeline(StandardScaler(), LinearSVC(random_state=42))),
]
clf = StackingClassifier(estimators=estimators, final_estimator=LogisticRegression())
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
clf.fit(X_train, y_train)
self.assertRaises(ValueError, hummingbird.ml.convert, clf, "torch")
@unittest.skipIf(StackingClassifier is None, reason="StackingRegressor not available in scikit-learn < 0.22")
def test_stacking_regressor(self):
X, y = load_diabetes(return_X_y=True)
estimators = [("lr", RidgeCV()), ("svr", LinearSVR(random_state=42))]
reg = StackingRegressor(estimators=estimators, final_estimator=RandomForestRegressor(n_estimators=10, random_state=42))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
reg.fit(X_train, y_train)
hb_model = hummingbird.ml.convert(reg, "torch")
np.testing.assert_allclose(
reg.predict(X_test), hb_model.predict(X_test), rtol=1e-06, atol=1e-06,
)
if __name__ == "__main__":
unittest.main()
| test_stacking_classifier_decision_function |
intensitydatawrapper.py | #!/usr/bin/env python3
# Copyright © 2021 Helmholtz Centre Potsdam GFZ German Research Centre for Geosciences, Potsdam, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
"""
This is the module to provide
an interface and some implementations
for accesing intensity data
either using dicts with lists
or using dataframes or others.
The commom protocol is to support the following methods:
- get_list_x_coordinates():
Returns a list / series / array of x coordinates
- get_list_y_coordinates():
Same for the y coordinates
- get_data_columns():
String list with the names of the columns to read from.
- get_value_for_column_and_index(column, index):
Reads the value for the column and the index.
The index will be given by the ckd tree search in the
intensity provider classes.
- get_unit_for_column_and_index(column, index):
Similar to te get_value_for_column_and_index method,
but returns the unit. Can ignore the index if it is the
same for the whole dataset.
"""
import re
import geopandas as gpd
class GeopandasDataFrameWrapper:
"""
Wraps a geopandas data frame
to support the common intensity data protocol.
This implementation uses prefixes for the value
and unit columns.
"""
def __init__(self, gdf, prefix_value_columns="value_", prefix_unit_columns="unit_"):
self._gdf = gdf
self._prefix_value_columns = prefix_value_columns
self._prefix_unit_columns = prefix_unit_columns
def get_list_x_coordinates(self):
"""
Returns a list / series / array of the x coordinates.
"""
return self._get_centroid().x
def get_list_y_coordinates(self):
"""
Returns a list / series / array of the y coordinates.
"""
return self._get_centroid().y
def _get_centroid(self):
return self._gdf["geometry"].centroid
def get_data_columns(self):
"""
Returns a generator to go over all of the
data columns for the intensity data.
"""
for column in self._gdf.columns:
if column.startswith(self._prefix_value_columns):
column_without_prefix = re.sub(
r"^" + self._prefix_value_columns, "", column
)
yield column_without_prefix
def get_value_for_column_and_index(self, column, index):
"""
Returns the value for the column and the index.
"""
value_column = self._prefix_value_columns + column
series = self._gdf.iloc[index]
return series[value_column]
def get_unit_for_column_and_index(self, column, index):
"""
Returns the unit for the column and the index.
"""
unit_column = self._prefix_unit_columns + column
series = self._gdf.iloc[index]
return series[unit_column]
class GeopandasDataFrameWrapperWithColumnUnit:
"""
Like the GeopandasDataFrameWrapper it
wraps a geopandas dataframe, but
this only cares about one single
column
"""
def __init__(self, gdf, column, name, unit):
self._gdf = gdf
self._column = column
self._name = name
self._unit = unit
def get_list_x_coordinates(self):
"""
Returns a list / series / array of the x coordinates.
"""
return self._get_centroid().x
def get_list_y_coordinates(self):
"""
Returns a list / series / array of the y coordinates.
"""
return self._get_centroid().y
def _get_centroid(self):
return self._gdf["geometry"].centroid
def get_data_columns(self):
"""
Returns a generator to go over all of the
data columns for the intensity data.
"""
yield self._name
def get_value_for_column_and_index(self, column, index):
"""
Returns the value for the column and the index.
"""
series = self._gdf.iloc[index]
return series[self._column]
def get_unit_for_column_and_index(self, column, index):
"""
Returns the unit for the column and the index.
"""
return self._unit
class RasterDataWrapper:
"""
This is a wrapper to read the data from
raster.
The raster for the data is assumed to be
created using the georasters package
and the load_file function.
It works by converting the raster to a dataframe
and using the wrapper that exists therefore.
In case that we get utm coordinates we may
have to reproject the data to wgs84 in order to
work property with it (as in the same way as
with the shakemaps).
"""
def __init__(
self,
raster,
value_name,
unit,
input_epsg_code=None,
usage_epsg_code="epsg:4326",
):
dataframe = raster.to_pandas()
geodataframe = gpd.GeoDataFrame(
dataframe, geometry=gpd.points_from_xy(dataframe.x, dataframe.y)
)
if input_epsg_code is not None:
geodataframe.crs = {"init": input_epsg_code}
geodataframe = geodataframe.to_crs({"init": usage_epsg_code})
geodataframe["value_" + value_name] = geodataframe["value"]
geodataframe["unit_" + value_name] = unit
self._inner_data_wrapper = GeopandasDataFrameWrapper(geodataframe)
def get_list_x_coordinates(self):
"""
Returns a list / series / array of the x coordinates.
"""
return self._inner_data_wrapper.get_list_x_coordinates()
def get_list_y_coordinates(self):
"""
Returns a list / series / array of the y coordinates.
"""
return self._inner_data_wrapper.get_list_y_coordinates()
def get_data_columns(self):
" |
def get_value_for_column_and_index(self, column, index):
"""
Returns the value for the column and the index.
"""
return self._inner_data_wrapper.get_value_for_column_and_index(
column,
index,
)
def get_unit_for_column_and_index(self, column, index):
"""
Returns the unit for the column and the index.
"""
return self._inner_data_wrapper.get_unit_for_column_and_index(column, index)
class DictWithListDataWrapper:
"""
Wrapper for accessing the intensity data using
a dict with lists for the data
and an addtional dict for the units.
"""
def __init__(self, data, units, possible_x_columns, possible_y_columns):
self._data = data
self._units = units
self._x_column = None
self._y_column = None
for possible_column in possible_x_columns:
if possible_column in self._data.keys():
self._x_column = possible_column
break
assert self._x_column is not None
for possible_column in possible_y_columns:
if possible_column in self._data.keys():
self._y_column = possible_column
break
assert self._y_column is not None
def get_list_x_coordinates(self):
"""
Returns a list / series / array of the x coordinates.
"""
return self._data[self._x_column]
def get_list_y_coordinates(self):
"""
Returns a list / series / array of the y coordinates.
"""
return self._data[self._y_column]
def get_data_columns(self):
"""
Returns a generator to go over all of the
data columns for the intensity data.
"""
for column in self._data.keys():
if column != self._x_column:
if column != self._y_column:
yield column
def get_value_for_column_and_index(self, column, index):
"""
Returns the value for the column and the index.
"""
return self._data[column][index]
def get_unit_for_column_and_index(self, column, index):
"""
Returns the unit for the column and the index.
This implementation ignores the index.
"""
return self._units[column]
| ""
Returns a generator to go over all of the
data columns for the intensity data.
"""
return self._inner_data_wrapper.get_data_columns()
|
RepoStyles.js | export default {
container: {
alignItems: 'center'
},
name: {
color: '#ffffff'
},
repo: {
fontWeight: 'bold',
color: '#ffffff'
},
avatar: {
marginVertical: 15,
width: 80,
height: 80,
borderRadius: 40,
borderWidth: 4,
borderColor: '#ffffff',
backgroundColor: '#3d3d3d'
},
message: {
color: '#BBD1EA',
fontSize: 12,
height: 100,
overflow: 'hidden',
paddingHorizontal: 50,
marginTop: 20
},
middle: {
flexDirection: 'row',
alignItems: 'center'
},
center: {
alignItems: 'center',
justifyContent: 'center'
},
left: {
alignItems: 'flex-end',
justifyContent: 'flex-end',
paddingRight: 10
}, | justifyContent: 'center',
paddingLeft: 10
}
} | right: {
alignItems: 'center', |
httptarget.go | /*
Copyright 2022 TriggerMesh Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v1alpha1
import (
"context"
time "time"
targetsv1alpha1 "github.com/triggermesh/triggermesh/pkg/apis/targets/v1alpha1"
internalclientset "github.com/triggermesh/triggermesh/pkg/client/generated/clientset/internalclientset"
internalinterfaces "github.com/triggermesh/triggermesh/pkg/client/generated/informers/externalversions/internalinterfaces"
v1alpha1 "github.com/triggermesh/triggermesh/pkg/client/generated/listers/targets/v1alpha1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
cache "k8s.io/client-go/tools/cache"
)
// HTTPTargetInformer provides access to a shared informer and lister for
// HTTPTargets.
type HTTPTargetInformer interface {
Informer() cache.SharedIndexInformer
Lister() v1alpha1.HTTPTargetLister
}
type hTTPTargetInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
namespace string
}
// NewHTTPTargetInformer constructs a new informer for HTTPTarget type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func | (client internalclientset.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredHTTPTargetInformer(client, namespace, resyncPeriod, indexers, nil)
}
// NewFilteredHTTPTargetInformer constructs a new informer for HTTPTarget type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredHTTPTargetInformer(client internalclientset.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.TargetsV1alpha1().HTTPTargets(namespace).List(context.TODO(), options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.TargetsV1alpha1().HTTPTargets(namespace).Watch(context.TODO(), options)
},
},
&targetsv1alpha1.HTTPTarget{},
resyncPeriod,
indexers,
)
}
func (f *hTTPTargetInformer) defaultInformer(client internalclientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredHTTPTargetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *hTTPTargetInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&targetsv1alpha1.HTTPTarget{}, f.defaultInformer)
}
func (f *hTTPTargetInformer) Lister() v1alpha1.HTTPTargetLister {
return v1alpha1.NewHTTPTargetLister(f.Informer().GetIndexer())
}
| NewHTTPTargetInformer |
variables6.rs | // variables5.rs
// Make me compile! Execute the command `rustlings hint variables6` if you want a hint :)
const NUMBER: usize = 3;
fn main() | {
println!("Number {}", NUMBER);
} |
|
copy.js | const COPY = "content_copy";
const COPIED = "done";
const copy = async (obj) => {
// <span class="copy"><span class="material-icons">{{text}}</span></span>
await navigator.clipboard.writeText(obj.children[1].innerText).then(
() => {
let icon = obj.children[0].children[0];
icon.textContent = COPIED;
setTimeout(() => (icon.textContent = COPY), 2500);
},
(r) => alert('Could not copy codeblock:\n' + r.toString())
);
};
document.addEventListener("DOMContentLoaded", () => {
let allCodeblocks = document.querySelectorAll("div[class='highlight']");
for (let codeblock of allCodeblocks) {
codeblock.parentNode.className += " relative-copy";
let copyEl = document.createElement("span"); | copyEl.setAttribute("aria-label", "Copy Code");
copyEl.setAttribute("title", "Copy Code");
let copyIcon = document.createElement("span");
copyIcon.className = "material-icons";
copyIcon.textContent = COPY;
copyEl.append(copyIcon);
codeblock.prepend(copyEl);
}
}); | copyEl.addEventListener('click', () => copy(codeblock));
copyEl.className = "copy"; |
measurement.py | # Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Measurement(object):
""" A measurement is an object with a measure and a value attached to it
:type measure: :class: '~opencensus.stats.measure.Measure'
:param measure: A measure to pass into the measurement
:type value: int or float
:param value: value of the measurement
"""
def __init__(self, measure, value):
|
@property
def value(self):
"""The value of the current measurement"""
return self._value
@property
def measure(self):
"""The measure of the current measurement"""
return self._measure
class MeasurementInt(Measurement):
""" Creates a new Integer Measurement """
def __init__(self, measure, value):
super(MeasurementInt, self).__init__(measure, value)
class MeasurementFloat(Measurement):
""" Creates a new Float Measurement """
def __init__(self, measure, value):
super(MeasurementFloat, self).__init__(measure, value)
| self._measure = measure
self._value = value |
120Triangle.py | def minimumTotal(triangle):
|
def minimumTotal1(triangle):
if not triangle:
return 0
for i in range(len(triangle) -2, -1, -1):
for j in range(len(triangle[i])):
triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1])
return triangle[0][0]
result = minimumTotal1([[2],[3,4],[6,5,7],[4,1,8,3]])
print(result)
| if not triangle: return 0
res = triangle[-1]
for i in range(len(triangle) -2, -1, -1):
for j in range(len(triangle[i])):
res[j] = min(res[j], res[j+1]) + triangle[i][j]
return res[0] |
graph.py | """
HiddenLayer
Implementation of the Graph class. A framework independent directed graph to
represent a neural network.
Written by Waleed Abdulla. Additions by Phil Ferriere.
Licensed under the MIT License
"""
from __future__ import absolute_import, division, print_function
import os
import re
from random import getrandbits
import inspect
import numpy as np
THEMES = {
"basic": {
"background_color": "#FFFFFF",
"fill_color": "#E8E8E8",
"outline_color": "#000000",
"font_color": "#000000",
"font_name": "Times",
"font_size": "10",
"margin": "0,0",
"padding": "1.0,0.5",
},
"blue": {
"background_color": "#FFFFFF",
"fill_color": "#BCD6FC",
"outline_color": "#7C96BC",
"font_color": "#202020",
"font_name": "Verdana",
"font_size": "10",
"margin": "0,0",
"padding": "1.0,0.5",
},
}
###########################################################################
# Utility Functions
###########################################################################
def detect_framework(value):
# Get all base classes
classes = inspect.getmro(value.__class__)
for c in classes:
if c.__module__.startswith("torch"):
return "torch"
elif c.__module__.startswith("tensorflow"):
return "tensorflow"
###########################################################################
# Node
###########################################################################
class Node():
"""Represents a framework-agnostic neural network layer in a directed graph."""
def __init__(self, uid, name, op, output_shape=None, params=None):
"""
uid: unique ID for the layer that doesn't repeat in the computation graph.
name: Name to display
op: Framework-agnostic operation name.
"""
self.id = uid
self.name = name # TODO: clarify the use of op vs name vs title
self.op = op
self.repeat = 1
if output_shape:
assert isinstance(output_shape, (tuple, list)),\
"output_shape must be a tuple or list but received {}".format(type(output_shape))
self.output_shape = output_shape
self.params = params if params else {}
self._caption = ""
@property
def title(self):
# Default
title = self.name or self.op
if "kernel_shape" in self.params:
# Kernel
kernel = self.params["kernel_shape"]
title += "x".join(map(str, kernel))
if "stride" in self.params:
stride = self.params["stride"]
if np.unique(stride).size == 1:
stride = stride[0]
if stride != 1:
title += "/s{}".format(str(stride))
# # Transposed
# if node.transposed:
# name = "Transposed" + name
return title
@property
def caption(self):
if self._caption:
return self._caption
caption = ""
# Stride
# if "stride" in self.params:
# stride = self.params["stride"]
# if np.unique(stride).size == 1:
# stride = stride[0]
# if stride != 1:
# caption += "/{}".format(str(stride))
return caption
def __repr__(self):
args = (self.op, self.name, self.id, self.title, self.repeat)
f = "<Node: op: {}, name: {}, id: {}, title: {}, repeat: {}"
if self.output_shape:
args += (str(self.output_shape),)
f += ", shape: {:}"
if self.params:
args += (str(self.params),)
f += ", params: {:}"
f += ">"
return f.format(*args)
###########################################################################
# Graph
###########################################################################
def build_graph(model=None, args=None, input_names=None,
transforms="default", framework_transforms="default"):
# Initialize an empty graph
g = Graph()
# Detect framwork
framework = detect_framework(model)
if framework == "torch":
from .pytorch_builder import import_graph, FRAMEWORK_TRANSFORMS
assert args is not None, "Argument args must be provided for Pytorch models."
import_graph(g, model, args)
elif framework == "tensorflow":
from .tf_builder import import_graph, FRAMEWORK_TRANSFORMS
import_graph(g, model)
else:
raise ValueError("`model` input param must be a PyTorch, TensorFlow, or Keras-with-TensorFlow-backend model.")
# Apply Transforms
if framework_transforms:
if framework_transforms == "default":
framework_transforms = FRAMEWORK_TRANSFORMS
for t in framework_transforms:
g = t.apply(g)
if transforms:
if transforms == "default":
from .transforms import SIMPLICITY_TRANSFORMS
transforms = SIMPLICITY_TRANSFORMS
for t in transforms:
g = t.apply(g)
return g
class Graph():
"""Tracks nodes and edges of a directed graph and supports basic operations on them."""
def __init__(self, model=None, args=None, input_names=None,
transforms="default", framework_transforms="default",
meaningful_ids=False):
self.nodes = {}
self.edges = []
self.meaningful_ids = meaningful_ids # TODO
self.theme = THEMES["basic"]
if model:
# Detect framwork
framework = detect_framework(model)
if framework == "torch":
from .pytorch_builder import import_graph, FRAMEWORK_TRANSFORMS
assert args is not None, "Argument args must be provided for Pytorch models."
import_graph(self, model, args)
elif framework == "tensorflow":
from .tf_builder import import_graph, FRAMEWORK_TRANSFORMS
import_graph(self, model)
# Apply Transforms
if framework_transforms:
if framework_transforms == "default":
framework_transforms = FRAMEWORK_TRANSFORMS
for t in framework_transforms:
t.apply(self)
if transforms:
if transforms == "default":
from .transforms import SIMPLICITY_TRANSFORMS
transforms = SIMPLICITY_TRANSFORMS
for t in transforms:
t.apply(self)
def id(self, node):
"""Returns a unique node identifier. If the node has an id
attribute (preferred), it's used. Otherwise, the hash() is returned."""
return node.id if hasattr(node, "id") else hash(node)
def add_node(self, node):
id = self.id(node)
# assert(id not in self.nodes)
self.nodes[id] = node
def add_edge(self, node1, node2, label=None):
# If the edge is already present, don't add it again.
# TODO: If an edge exists with a different label, still don't add it again.
edge = (self.id(node1), self.id(node2), label)
if edge not in self.edges:
self.edges.append(edge)
def add_edge_by_id(self, vid1, vid2, label=None):
self.edges.append((vid1, vid2, label))
def outgoing(self, node):
"""Returns nodes connecting out of the given node (or list of nodes)."""
nodes = node if isinstance(node, list) else [node]
node_ids = [self.id(n) for n in nodes]
# Find edges outgoing from this group but not incoming to it
outgoing = [self[e[1]] for e in self.edges
if e[0] in node_ids and e[1] not in node_ids]
return outgoing
def incoming(self, node):
"""Returns nodes connecting to the given node (or list of nodes)."""
nodes = node if isinstance(node, list) else [node]
node_ids = [self.id(n) for n in nodes]
# Find edges incoming to this group but not outgoing from it
incoming = [self[e[0]] for e in self.edges
if e[1] in node_ids and e[0] not in node_ids]
return incoming
def siblings(self, node):
"""Returns all nodes that share the same parent (incoming node) with
the given node, including the node itself.
"""
incoming = self.incoming(node)
# TODO: Not handling the case of multiple incoming nodes yet
if len(incoming) == 1:
incoming = incoming[0]
siblings = self.outgoing(incoming)
return siblings
else: | def __getitem__(self, key):
if isinstance(key, list):
return [self.nodes.get(k) for k in key]
else:
return self.nodes.get(key)
def remove(self, nodes):
"""Remove a node and its edges."""
nodes = nodes if isinstance(nodes, list) else [nodes]
for node in nodes:
k = self.id(node)
self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))
del self.nodes[k]
def replace(self, nodes, node):
"""Replace nodes with node. Edges incoming to nodes[0] are connected to
the new node, and nodes outgoing from nodes[-1] become outgoing from
the new node."""
nodes = nodes if isinstance(nodes, list) else [nodes]
# Is the new node part of the replace nodes (i.e. want to collapse
# a group of nodes into one of them)?
collapse = self.id(node) in self.nodes
# Add new node and edges
if not collapse:
self.add_node(node)
for in_node in self.incoming(nodes):
# TODO: check specifically for output_shape is not generic. Consider refactoring.
self.add_edge(in_node, node, in_node.output_shape if hasattr(in_node, "output_shape") else None)
for out_node in self.outgoing(nodes):
self.add_edge(node, out_node, node.output_shape if hasattr(node, "output_shape") else None)
# Remove the old nodes
for n in nodes:
if collapse and n == node:
continue
self.remove(n)
def search(self, pattern):
"""Searches the graph for a sub-graph that matches the given pattern
and returns the first match it finds.
"""
for node in self.nodes.values():
match, following = pattern.match(self, node)
if match:
return match, following
return [], None
def sequence_id(self, sequence):
"""Make up an ID for a sequence (list) of nodes.
Note: `getrandbits()` is very uninformative as a "readable" ID. Here, we build a name
such that when the mouse hovers over the drawn node in Jupyter, one can figure out
which original nodes make up the sequence. This is actually quite useful.
"""
if self.meaningful_ids:
# TODO: This might fail if the ID becomes too long
return "><".join([node.id for node in sequence])
else:
return getrandbits(64)
def build_dot(self):
"""Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object.
"""
from graphviz import Digraph
# Build GraphViz Digraph
dot = Digraph()
dot.attr("graph",
bgcolor=self.theme["background_color"],
color=self.theme["outline_color"],
fontsize=self.theme["font_size"],
fontcolor=self.theme["font_color"],
fontname=self.theme["font_name"],
margin=self.theme["margin"],
rankdir="LR",
pad=self.theme["padding"])
dot.attr("node", shape="box",
style="filled", margin="0,0",
fillcolor=self.theme["fill_color"],
color=self.theme["outline_color"],
fontsize=self.theme["font_size"],
fontcolor=self.theme["font_color"],
fontname=self.theme["font_name"])
dot.attr("edge", style="solid",
color=self.theme["outline_color"],
fontsize=self.theme["font_size"],
fontcolor=self.theme["font_color"],
fontname=self.theme["font_name"])
for k, n in self.nodes.items():
label = "<tr><td cellpadding='6'>{}</td></tr>".format(n.title)
if n.caption:
label += "<tr><td>{}</td></tr>".format(n.caption)
if n.repeat > 1:
label += "<tr><td align='right' cellpadding='2'>x{}</td></tr>".format(n.repeat)
label = "<<table border='0' cellborder='0' cellpadding='0'>" + label + "</table>>"
dot.node(str(k), label)
for a, b, label in self.edges:
if isinstance(label, (list, tuple)):
label = "x".join([str(l or "?") for l in label])
dot.edge(str(a), str(b), label)
return dot
def _repr_svg_(self):
"""Allows Jupyter notebook to render the graph automatically."""
return self.build_dot()._repr_image_svg_xml()
def save(self, path, format="pdf"):
# TODO: assert on acceptable format values
dot = self.build_dot()
dot.format = format
directory, file_name = os.path.split(path)
# Remove extension from file name. dot.render() adds it.
file_name = file_name.replace("." + format, "")
dot.render(file_name, directory=directory, cleanup=True) | return [node]
|
sugarguidemodel.go | package db
import (
"encoding/json"
"github.com/jinzhu/gorm"
)
func SaveSugarGuidePlan(userId int, dietResult []byte, sportResult []byte, controlResult []byte) error {
var dietPlan SugarGuideDietPlan
var sportPlan SugarGuideSportPlan
var controlPlan SugarGuideControlPlan
if err := json.Unmarshal(dietResult, &dietPlan); err != nil {
return err
}
if err := json.Unmarshal(sportResult, &sportPlan); err != nil {
return err
}
if err := json.Unmarshal(controlResult, &controlPlan); err != nil {
return err
}
user, err := GetUserFromUserId(userId)
if err != nil {
return err
}
err = Transaction(func(db *gorm.DB) error {
if err := db.Model(&user).Association("SugarGuideDietPlan").Clear().Error; err != nil {
return err
}
if err := db.Model(&user).Association("SugarGuideDietPlan").Append(dietPlan).Error; err != nil {
return err
}
if err := db.Model(&user).Association("SugarGuideSportPlan").Clear().Error; err != nil {
return err
}
if err := db.Model(&user).Association("SugarGuideSportPlan").Append(sportPlan).Error; err != nil {
return err
}
if err := db.Model(&user).Association("SugarGuideControlPlan").Clear().Error; err != nil {
return err
}
if err := db.Model(&user).Association("SugarGuideControlPlan").Append(controlPlan).Error; err != nil {
return err
}
return nil
})
return err
}
func CheckWeeklyNewspaper(userId int) (bool, error) {
user, err := GetUserFromUserId(userId)
if err != nil {
return false, err
}
if mysqlDb.Model(&user).Association("SugarGuideDietPlan").Count() < 1 ||
mysqlDb.Model(&user).Association("SugarGuideSportPlan").Count() < 1 ||
mysqlDb.Model(&user).Association("SugarGuideControlPlan").Count() < 1 {
return false, nil
}
return true, nil
}
func | (userId int) (SugarGuideDietPlan, SugarGuideSportPlan, SugarGuideControlPlan, error) {
var dietPlan SugarGuideDietPlan
var sportPlan SugarGuideSportPlan
var controlPlan SugarGuideControlPlan
user, err := GetUserFromUserId(userId)
if err != nil {
return dietPlan, sportPlan, controlPlan, err
}
if err := mysqlDb.Model(&user).Association("SugarGuideDietPlan").Find(&dietPlan).Error; err != nil {
return dietPlan, sportPlan, controlPlan, err
}
if err := mysqlDb.Model(&user).Association("SugarGuideSportPlan").Find(&sportPlan).Error; err != nil {
return dietPlan, sportPlan, controlPlan, err
}
if err := mysqlDb.Model(&user).Association("SugarGuideControlPlan").Find(&controlPlan).Error; err != nil {
return dietPlan, sportPlan, controlPlan, err
}
return dietPlan, sportPlan, controlPlan, nil
}
| GetWeeklyNewspaper |
json.rs | #![cfg(feature = "macros")]
#![feature(proc_macro_hygiene)]
use parze::prelude::*;
use std::collections::HashMap;
#[derive(Debug, PartialEq)]
pub enum JsonValue {
Null,
Bool(bool),
Str(String),
Num(f64),
Array(Vec<JsonValue>),
Object(HashMap<String,JsonValue>)
}
fn | () {
parsers! {
integer = { { one_of("123456789".chars()) }.% % { one_of("0123456789".chars()) }* |% '0'.% }
frac = { '.'.% % { one_of("0123456789".chars()) }+ }
exp = { ('e' | 'E').% % ('+' | '-')? % { one_of("0123456789".chars()) }+ }
number = { '-'? % integer % frac?.# % exp?.# => { |cs| cs.collect::<String>().parse().unwrap() } }
special = { '\\' | '/' | '"' | 'b' -> '\x08' | 'f' -> '\x0C' | 'n' -> '\n' | 'r' -> '\r' | 't' -> '\t' }
escape = { '\\' -& special }
string = { '"' -& ({ none_of("\\\"".chars()) } | escape)* &- '"' => { |cs| cs.collect::<String>() } }
elements = { value ... ','~ }
array = { '['~ -& elements &- ']' }
member = { string~ &- ':'~ & value }
members = { member ... ','~ }
object = { '{'~ -& members &- '}' => { |m| m.collect() } }
value: Parser<_, _> = {
~(
| { all_of("null".chars()) } => { |_| JsonValue::Null }
| { all_of("true".chars()) } => { |_| JsonValue::Bool(true) }
| { all_of("false".chars()) } => { |_| JsonValue::Bool(false) }
| number => { |n| JsonValue::Num(n) }
| string => { |s| JsonValue::Str(s) }
| array => { |a| JsonValue::Array(a) }
| object => { |o| JsonValue::Object(o) }
)~
}
}
let test_json = r#"
{
"parze": {
"description": "parser combinator library",
"has_macros": true
},
"some_numbers": [42, 13.37, 256],
"hypothesis": null
}
"#;
println!("{:#?}", value.parse_str(test_json));
}
| main |
nim.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import random
import sys
import time
import re
import copy
from optparse import OptionParser
import pygame
from pygame.locals import *
version = "0.1"
usage = "usage: %prog [ --lvl [0-5] | ]"
parser = OptionParser(usage=usage, version="%prog 0.1")
parser.add_option("-m", help="Number of match",
default=0, action="store", dest="numberOfMatch")
parser.add_option("-v", help="The variant of Nim",
default=0, action="store", dest="varient")
parser.add_option("-w", help="Mode, there is two values possibles “ttl” and “ltl”",
default=0, action="store", dest="varient")
(options, args) = parser.parse_args()
if not options.numberOfMatch:
# If no lelvel was explicitly choosen by the user, it is automatically set
# to 0.
options.numberOfMatch = 15
innitialNumberOfMatch = int(options.numberOfMatch)
currentNumberOfMatch = int(innitialNumberOfMatch)
class borderSize:
def __init__(self):
self.top = 0
self.bototm = 0
self.right = 0
self.left = 0
class surfaceInformations:
def __init__(self):
self.width = 0
self.height = 0
self.y = 0
self.x = 0
self.top = 0
self.bototm = 0
self.right = 0
self.left = 0
if self.y != 0:
self.ratio = self.x / self.y
class whatToDo:
def __init__(self):
self.programHaveToContinue = True
self.variant = "trivial"
self.number = numberOfInitialMatch
self.wtw = "ttl"
print("This is Nim " + version + "\n")
mainDir = os.path.dirname(os.path.realpath(__file__))
# Colour deffinitions
background_colour = (144, 124, 106)
text_zone_colour = (81, 69, 58)
history_area_colour = (69, 59, 49)
indicator_colour = (70, 60, 50)
prompt_colour = (25, 21, 18)
creme_colour = (236, 228, 217)
yellow_colour = (205, 153, 29)
winingMainText_colour = (236, 232, 228)
purple_colour = (133, 0, 58)
red = (225, 0, 0)
class variants:
def __init__(self):
self.name = ""
self.number = 15
self.wtw = "ttl"
trivial = variants()
trivial.name = "Trivial"
trivial.number = 15
trivial.wtw = "ttl"
marienbad = variants()
marienbad.name = "Marienbad"
marienbad.number = 5
marienbad.wtw = "ttl"
knowenVarients = [trivial, marienbad]
viarentNames = []
for varientRow in knowenVarients:
viarentNames.append(varientRow.name)
# Sizes deffinitions
xSize = 640
ySize = 480
textZoneHeigh = 16
maxPaddingBetwenMatch = 3
matchPicRatio = 6.925
numberOfInitialMatch = innitialNumberOfMatch
historyAreaWidth = 67
circleRadius = 10
gameAreaDim = [0, 0]
matchAreaDim = [0, 0]
matchAreaPos = [0, 0]
indicatorDim = [127, 55]
matchAreaBorder = borderSize()
matchAreaBorder.top = 40
matchAreaBorder.bottom = 80
matchAreaBorder.left = 40
matchAreaBorder.right = 40
trianglePromptWidth = 7
textUserInput = []
normaUserInput = []
textUserInput = []
normalUserInput = []
exMode = False
normalMode = True
textToAnalyse = ""
normalTextToAnalyse = ""
allowedMatchDel = ["1", "2", "3"]
pygame.init()
screen = pygame.display.set_mode((xSize, ySize), RESIZABLE)
charInputed = [K_TAB, K_SPACE, K_EXCLAIM, K_QUOTEDBL, K_HASH, K_DOLLAR, K_AMPERSAND, K_QUOTE, K_LEFTPAREN, K_RIGHTPAREN, K_ASTERISK, K_PLUS, K_COMMA, K_MINUS, K_PERIOD, K_SLASH, K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_COLON, K_SEMICOLON, K_LESS, K_EQUALS, K_GREATER, K_QUESTION,
K_AT, K_LEFTBRACKET, K_BACKSLASH, K_RIGHTBRACKET, K_CARET, K_UNDERSCORE, K_BACKQUOTE, K_a, K_b, K_c, K_d, K_e, K_f, K_g, K_h, K_i, K_j, K_k, K_l, K_m, K_n, K_o, K_p, K_q, K_r, K_s, K_t, K_u, K_v, K_w, K_x, K_y, K_z, K_KP_PERIOD, K_KP_DIVIDE, K_KP_MULTIPLY, K_KP_MINUS, K_KP_PLUS, K_KP_EQUALS]
def makeTextZone(nameToDisplay, secondName):
# Redifining variables
xSize, ySize = screen.get_size()
# Textzone deffinition
textZone = pygame.Surface((xSize, textZoneHeigh))
textZone.fill(text_zone_colour)
heighTextZonePosition = ySize - textZoneHeigh
promptFont = pygame.font.SysFont("monospace", 14, bold=True)
# Option title deffinition
secondPromptZone = pygame.Surface((1, 1))
secondPromptZoneInfo = surfaceInformations()
secondEcart = 0
secondLittleEcart = 0
secondPromptZoneInfo.width = 0
if secondName != None:
textSecondSizeWidth, textSecondSizeHeight = promptFont.size(secondName)
secondPromptZoneInfo.width = textSecondSizeWidth + 8
secondPromptZoneInfo.heigh = textZoneHeigh
secondPromptZone = pygame.Surface((secondPromptZoneInfo.width, secondPromptZoneInfo.heigh))
secondPromptZone.fill(yellow_colour)
secondPromptText = promptFont.render(secondName, 1, prompt_colour)
secondTextSizeWidth, secondTextSizeHeight = promptFont.size(secondName)
secondPromptTriangle = pygame.draw.polygon(screen, prompt_colour, [[secondPromptZoneInfo.width, ySize - textZoneHeigh], [
secondPromptZoneInfo.width, ySize], [secondPromptZoneInfo.width + trianglePromptWidth, ySize - (textZoneHeigh / 2)]], 0)
secondEcart = secondPromptZoneInfo.width + trianglePromptWidth
secondLittleEcart = trianglePromptWidth
# promptzone deffinition
textSizeWidth, textSizeHeight = promptFont.size(nameToDisplay)
promptZoneInfo = surfaceInformations()
promptZoneInfo.width = textSizeWidth + 8
promptZoneInfo.heigh = textZoneHeigh
promptZone = pygame.Surface((promptZoneInfo.width + secondLittleEcart, promptZoneInfo.heigh))
promptZone.fill(prompt_colour)
promptText = promptFont.render(nameToDisplay, 1, (205, 153, 29))
textSizeWidth, textSizeHeight = promptFont.size(nameToDisplay)
# initialize font; must be called after 'pygame.init()' to avoid 'Font not
# Initialized' error
myfont = pygame.font.SysFont("monospace", 14)
# render text
label = myfont.render("".join(textUserInput), 1, (255, 255, 255))
#bliting cascade
screen.blit(textZone, (0, heighTextZonePosition))
screen.blit(promptZone, (0 + secondPromptZoneInfo.width, heighTextZonePosition))
promptTriangle = pygame.draw.polygon(screen, prompt_colour, [[promptZoneInfo.width + secondEcart, ySize - textZoneHeigh], [
promptZoneInfo.width + secondEcart, ySize], [promptZoneInfo.width + secondEcart + trianglePromptWidth, ySize - (textZoneHeigh / 2)]], 0)
screen.blit(promptText, (4 + secondEcart, heighTextZonePosition + 1))
if secondName != None:
screen.blit(secondPromptZone, (0, heighTextZonePosition))
screen.blit(secondPromptText, (4, heighTextZonePosition + 1))
secondPromptTriangle = pygame.draw.polygon(screen, yellow_colour, [[secondPromptZoneInfo.width, ySize - textZoneHeigh], [
secondPromptZoneInfo.width, ySize], [secondPromptZoneInfo.width + trianglePromptWidth, ySize - (textZoneHeigh / 2)]], 0)
screen.blit(label, (promptZoneInfo.width +
trianglePromptWidth + 4, heighTextZonePosition))
finalNormalUserInput = ""
def analyseTyping(variant, numberOfInitialMatch, wtw):
global programHaveToContinue
global textUserInput
global normalUserInput
global exMode
global normalMode
global textToAnalyse
global normalTextToAnalyse
global screen
global finalNormalUserInput
global generalState
keyboardInput = dict()
keyboardInput["mode"] = "normal"
keyboardInput["content"] = ""
functionHaveToContinue = True
for event in pygame.event.get():
if event.type == VIDEORESIZE:
screen = pygame.display.set_mode(event.size, RESIZABLE)
if event.type == QUIT:
programHaveToContinue = False
if event.type == KEYDOWN:
if (event.unicode == ":") and ("".join(normalUserInput) == ""):
exMode = True
normalMode = False
if exMode == True:
if event.key is K_ESCAPE:
exMode = False
normalMode = True
textUserInput = []
elif event.key in charInputed:
textUserInput.append(event.unicode)
elif event.key == K_BACKSPACE and textUserInput != []:
del textUserInput[-1]
if len(textUserInput) == 1:
exMode = False
normalMode = True
del textUserInput[-1]
elif event.key in [K_RETURN, K_KP_ENTER]:
textToAnalyse = "".join(textUserInput[1:])
textUserInput = []
exMode = False
if textUserInput == []:
exMode = False
normalMode = True
elif normalMode == True:
if (event.key is K_ESCAPE) and (normalUserInput != []):
normalUserInput = []
elif event.key == K_p:
normalUserInput = []
keyboardInput["mode"] = "pause"
elif (event.key is K_ESCAPE) and (normalUserInput == []):
normalUserInput = []
keyboardInput["mode"] = "escape"
elif (event.key not in [K_RETURN, K_KP_ENTER, K_ESCAPE]):
normalUserInput.append(event.unicode)
elif (event.key in [K_RETURN, K_KP_ENTER]):
finalNormalUserInput = "".join(normalUserInput)
normalUserInput = []
if textToAnalyse == "about":
textToAnalyse = ""
aboutScreen(screen)
elif textToAnalyse in ["quit", "q"]:
textToAnalyse = ""
programHaveToContinue = False
# elif textToAnalyse in ["new", "n"]:
#elif re.match("n(ew| *)?$", textToAnalyse) is not None:
elif re.match("n(ew)?( +((trivial)|(marienbad)))?( +[0-9]+)?( +(((ttl)|(take-the-last))|((ltl)|(let-the-last))))? *$", textToAnalyse) is not None:
programHaveToContinue = True
functionHaveToContinue = False
syntaxToExtractOptions = "n(ew)?( +(?P<variente>(trivial|marienbad)))?( +(?P<number>[0-9]+))?( +(?P<wtw>((ttl)|(ltl))))?"
newGameOptions = re.match(syntaxToExtractOptions,textToAnalyse)
textToAnalyse = ""
if (newGameOptions.group("variente") == None) :
generalState.variant = variant
else:
generalState.variant = newGameOptions.group("variente")
if ( newGameOptions.group("number") == None) :
generalState.number = numberOfInitialMatch
else:
generalState.number = int(newGameOptions.group("number"))
if ( newGameOptions.group("wtw") == None) :
generalState.wtw = wtw
else:
generalState.wtw = newGameOptions.group("wtw")
print("New " + str(generalState.variant) + ";" + str(generalState.number) + ";" + str(generalState.wtw) + " game.")
elif keyboardInput["mode"] == "escape":
keyboardInput["mode"] = "escape"
elif keyboardInput["mode"] == "pause":
keyboardInput["mode"] = "pause"
else:
keyboardInput["mode"] = "ex"
keyboardInput["content"] = textToAnalyse
if normalUserInput != []:
keyboardInput["mode"] = "normal"
keyboardInput["content"] = normalUserInput
return functionHaveToContinue, keyboardInput
def makeAPause(variant, numberOfInitialMatch, wtw, beginingOfGame):
global winingMainText_colour
global indicator_colour
global programHaveToContinue
resumeMainText_colour = (163, 143, 125)
pauseMainText_colour = winingMainText_colour
pauseTextInfo = surfaceInformations()
resumeTextInfo = surfaceInformations()
timeBeforePause = int(time.time()) - beginingOfGame
timeOfEndOfGame = int(time.time()) - beginingOfGame
functionHaveToContinue = True
while functionHaveToContinue and programHaveToContinue:
xSize, ySize = screen.get_size()
functionHaveToContinue, textToanalyse = analyseTyping(None, None, None)
screen.fill(indicator_colour)
if textToanalyse["mode"] == "escape":
functionHaveToContinue = False
# Bliting the text "PAUSE"
pauseTextContent = "Pause".upper()
pauseFont = pygame.font.SysFont("CMU Typewriter Text", 112, bold=True)
pauseText = pauseFont.render(pauseTextContent, 1, pauseMainText_colour)
pauseTextInfo.width, pauseTextInfo.height = pauseFont.size(pauseTextContent)
pauseTextInfo.x = (xSize - pauseTextInfo.width) / 2
pauseTextInfo.y = (ySize/2) - pauseTextInfo.height
screen.blit(pauseText, (pauseTextInfo.x, pauseTextInfo.y))
# Bliting the text resume text
resumeTextContent = "Type Escape key to continue."
resumeFont = pygame.font.SysFont("CMU Typewriter Text", 14, bold=True)
resumeText = resumeFont.render(resumeTextContent, 1, resumeMainText_colour)
resumeTextInfo.width, resumeTextInfo.height = resumeFont.size(resumeTextContent)
resumeTextInfo.x = (xSize - resumeTextInfo.width) / 2
resumeTextInfo.y = (ySize- 14) - resumeTextInfo.height - 30
screen.blit(resumeText, (resumeTextInfo.x, resumeTextInfo.y))
makeTextZone(variant,"Pause")
#####################
pygame.display.flip()
#####################
timeToReturn = int(time.time()) - timeBeforePause
return timeToReturn
def makeTimetZone(beginingOfGame):
timeZoneInformation = surfaceInformations()
timeZoneBackground = surfaceInformations()
timeZoneInformation.left = 2
timeZoneInformation.right = 2
xSize, ySize = screen.get_size()
myfont = pygame.font.SysFont("monospace", 14)
secondSinceBegining = int(time.time()) - beginingOfGame
m, s = divmod(secondSinceBegining, 60)
h, m = divmod(m, 60)
timePassed = "%02d:%02d" % (m, s)
heighTextZonePosition = ySize - textZoneHeigh
timeZoneText = myfont.render(timePassed, 1, (0, 0, 0))
timeZoneInformation.width, timeZoneInformation.height = myfont.size(
timePassed)
timeZoneInformation.x = xSize - timeZoneInformation.width - timeZoneInformation.left
timeZoneInformation.y = ySize - textZoneHeigh
timeZoneBackground.width = timeZoneInformation.width + \
(timeZoneInformation.left + timeZoneInformation.right)
timeZoneBackground.height = textZoneHeigh
timeZoneBackground.y = heighTextZonePosition
timeZoneBackground.x = timeZoneInformation.x - 2
timeZoneBackgroundSurface = pygame.Surface(
(timeZoneBackground.width, timeZoneBackground.height))
timeZoneBackgroundSurface.fill(creme_colour)
screen.blit(timeZoneBackgroundSurface,
(timeZoneBackground.x, timeZoneBackground.y))
screen.blit(timeZoneText, (timeZoneInformation.x, timeZoneInformation.y))
timeZoneBorder = pygame.draw.polygon(screen, yellow_colour, [[timeZoneBackground.x, timeZoneBackground.y], [timeZoneBackground.x, timeZoneBackground.y + timeZoneBackground.height - 2], [
timeZoneBackground.x + timeZoneBackground.width - 2, timeZoneBackground.y + timeZoneBackground.height - 2], [timeZoneBackground.x + timeZoneBackground.width - 2, timeZoneBackground.y]], 2)
return timeZoneBackground.width
normalUserInput = []
def aboutScreen(screen):
global programHaveToContinue
global textUserInput
global normalUserInput
global exMode
global normalMode
global textToAnalyse
global normalTextToAnalyse
functionHaveToContinue = True
keyboardInput = dict()
keyboardInput["mode"] = "normal"
keyboardInput["content"] = ""
while functionHaveToContinue and programHaveToContinue:
functionHaveToContinue, textToanalyse = analyseTyping(None, None, None)
if textToanalyse["mode"] == "escape":
functionHaveToContinue = False
# Appling variables
screen.fill(background_colour)
xSize, ySize = screen.get_size()
# Illustartion deffinition
illustrationInformation = surfaceInformations()
illustration = pygame.image.load(
mainDir + "/" + "about-illustration.png").convert_alpha()
illustrationInformation.width, illustrationInformation.height = illustration.get_size()
illustrationInformationRatio = illustrationInformation.width / \
illustrationInformation.height
if illustrationInformation.width > xSize:
illustrationInformation.width = xSize * (3 / 4)
illustrationInformation.height = illustrationInformation.width / \
illustrationInformationRatio
if illustrationInformation.height > ySize:
illustrationInformation.height = ySize * (3 / 4)
illustrationInformation.width = illustrationInformation.height * \
illustrationInformationRatio
illustrationInformation.y = (
ySize - illustrationInformation.height) / 2
illustrationInformation.x = (xSize - illustrationInformation.width) / 2
illustration = pygame.transform.scale(illustration, (int(
illustrationInformation.width), int(illustrationInformation.height)))
screen.blit(illustration, (illustrationInformation.x,
illustrationInformation.y))
makeTextZone("About", None)
#####################
pygame.display.flip()
#####################
def representsInt(s):
try:
| layTrivial(currentMatchNumber,wtw):
if wtw == "ttl":
modulator = 0
elif wtw == "ltl":
modulator = 1
if currentMatchNumber != 0:
if ((currentMatchNumber - 1) % 4) == modulator:
answer = 1
elif ((currentMatchNumber - 2) % 4) == modulator:
answer = 2
elif ((currentMatchNumber - 3) % 4) == modulator:
answer = 3
else:
answer = random.randint(1, 3)
else:
answer = 0
return answer
def trivialAnalysis(currentMatchNumber, initialMatchNumber, wtw, userInput):
if currentMatchNumber != 0:
numberOfMatchToDel = 0
if currentMatchNumber >= 3:
authorisedNumbers = [3, 2, 1]
elif currentMatchNumber == 2:
authorisedNumbers = [2, 1]
elif currentMatchNumber == 1:
authorisedNumbers = [1]
if list(userInput)[0] == "=":
action = "application"
stringToEvaluate = userInput[1:]
elif list(userInput)[0] == "-":
action = "soustraction"
stringToEvaluate = userInput[1:]
else:
action = "soustraction"
stringToEvaluate = userInput
if representsInt(stringToEvaluate):
if action == "soustraction":
numberOfMatchToDel = int(stringToEvaluate)
elif action == "application":
numberOfMatchToDel = currentMatchNumber - int(stringToEvaluate)
else:
answer = [False, "“" + userInput + "” is not a valid syntax."]
if numberOfMatchToDel != 0:
if numberOfMatchToDel in authorisedNumbers:
numberLetByUser = initialMatchNumber - numberOfMatchToDel
answer = [True, numberLetByUser, numberOfMatchToDel]
else:
answer = [False, "“" +
str(numberOfMatchToDel) + "” is too big."]
elif (numberOfMatchToDel == 0):
answer = [False, "“0” is not a valid answer."]
else:
answer = [True, 0, 0]
return answer
def winingFallingScreenMatchExplosion(winer, variant, numberOfInitialMatch, time):
xSize, ySize = screen.get_size()
if winer == True:
matchInformation = surfaceInformations()
matchS = []
match = 0
while match < 1000:
matchS.append(pygame.image.load(
mainDir + "/" + "match-animation.png").convert_alpha())
matchInformation.heigh = random.randint(0, ySize)
matchInformation.weight = random.randint(0, xSize)
rotation = random.randint(0, 360)
matchS[match] = pygame.transform.rotate(matchS[match], rotation)
screen.blit(
matchS[match], (matchInformation.weight, matchInformation.heigh))
match = match + 1
elif winer == False:
print("machin")
def formateSecondToDotedTime(seconds):
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
if h == 0:
formatedTime = "%02d:%02d" % (m, s)
else:
formatedTime = "%02d:%02d:%02d" % (h, m, s)
return formatedTime
def winingFallingScreen(winer, variant, numberOfInitialMatch, time):
global indicator_colour
global winingMainText_colour
global purple_colour
lineSeparationColor = (205, 153, 29)
helpText_color = (163, 143, 125)
fallingMainText_colour = winingMainText_colour
xSize, ySize = screen.get_size()
time = formateSecondToDotedTime(time)
if winer == True:
winingTextInfo = surfaceInformations()
winingTimeTextInfo = surfaceInformations()
winingHelpTextInfo = surfaceInformations()
screen.fill(indicator_colour)
# Bliting the text "You win"
winingFont = pygame.font.SysFont("CMU Typewriter Text", 44, bold=True)
winingText = winingFont.render("You win!", 1, winingMainText_colour)
winingTextInfo.width, winingTextInfo.height = winingFont.size("You win!")
winingTextInfo.x = (xSize - winingTextInfo.width) / 2
winingTextInfo.y = 40
screen.blit(winingText, (winingTextInfo.x, winingTextInfo.y))
# Bliting the time passed
winingTimeFont = pygame.font.SysFont("CMU Typewriter Text", 137, bold=True)
winingTimeText = winingTimeFont.render(time, 1, lineSeparationColor)
winingTimeTextInfo.width, winingTimeTextInfo.height = winingTimeFont.size(time)
winingTimeTextInfo.x = (xSize - winingTimeTextInfo.width) / 2
winingTimeTextInfo.y = 90
screen.blit(winingTimeText, (winingTimeTextInfo.x, winingTimeTextInfo.y))
# Bliting help text
helpText = "Type :new to begin new game or :help for more options."
winingHelpFont = pygame.font.SysFont("CMU Typewriter Text", 23, bold=True)
winingHelpText = winingHelpFont.render(helpText, 1, helpText_color)
winingHelpTextInfo.width, winingHelpTextInfo.height = winingHelpFont.size(helpText)
winingHelpTextInfo.x = (xSize - winingHelpTextInfo.width) / 2
winingHelpTextInfo.y = ySize-90
screen.blit(winingHelpText, (winingHelpTextInfo.x, winingHelpTextInfo.y))
elif winer == False:
fallingTextInfo = surfaceInformations()
fallingTimeTextInfo = surfaceInformations()
fallingHelpTextInfo = surfaceInformations()
screen.fill(purple_colour)
# Bliting the text "You win"
fallingTextContent = "You loose!"
fallingFont = pygame.font.SysFont("CMU Typewriter Text", 52, bold=True)
fallingText = fallingFont.render(fallingTextContent, 1, fallingMainText_colour)
fallingTextInfo.width, fallingTextInfo.height = fallingFont.size(fallingTextContent)
fallingTextInfo.x = (xSize - fallingTextInfo.width) / 2
fallingTextInfo.y = (ySize/2) - fallingTextInfo.height
screen.blit(fallingText, (fallingTextInfo.x, fallingTextInfo.y))
# Bliting help text
helpText = "Type :new to begin new game or :help for more options."
fallingHelpFont = pygame.font.SysFont("CMU Typewriter Text", 23, bold=True)
fallingHelpText = fallingHelpFont.render(helpText, 1, helpText_color)
fallingHelpTextInfo.width, fallingHelpTextInfo.height = fallingHelpFont.size(helpText)
fallingHelpTextInfo.x = (xSize - fallingHelpTextInfo.width) / 2
fallingHelpTextInfo.y = ySize-90
screen.blit(fallingHelpText, (fallingHelpTextInfo.x, fallingHelpTextInfo.y))
def printMarienbadListOfTry(screen, listOfTry):
global historyAreaWidth
historyFont = pygame.font.SysFont("monospace", 14, bold=True)
pageUpDownFont = pygame.font.SysFont("monospace", 18, bold=True)
pageUpDownColor = (220, 36, 4)
lineSeparationColor = (205, 153, 29)
realLineSeparationPlayed = (54,46,38)
xSize, ySize = screen.get_size()
arrowBackground = []
row = 0
arrowPosX = 40
delledNumberPosX = 53
scroowlingHistory = 0
rightHistoryAreaWidth = 0
for aTryGame in listOfTry:
tempSizeWidth, tempSizeHeigh = historyFont.size(aTryGame)
if tempSizeWidth > rightHistoryAreaWidth:
rightHistoryAreaWidth=tempSizeWidth
rightHistoryAreaWidth=rightHistoryAreaWidth+2
historyAreaWidth = rightHistoryAreaWidth + 35 + 20
historyZone = pygame.Surface((historyAreaWidth, ySize))
historyZone.fill(history_area_colour)
screen.blit(historyZone, (0, 0))
while row < len(listOfTry):
if (row % 2 == 0): # even
row_coulour = (234, 226, 215)
arrowSign = "←"
else: # odd
row_coulour = (207, 194, 184)
arrowSign = "→"
arrowBackground.append(pygame.Surface(
(historyAreaWidth, textZoneHeigh)))
arrowBackground[row].fill(row_coulour)
rowPosY = ySize - textZoneHeigh - \
(len(listOfTry) - row) * textZoneHeigh
historyNumberText = historyFont.render(str(row), 1, (0, 0, 0))
historyArrowText = historyFont.render(arrowSign, 1, (0, 0, 0))
numberDelledText = historyFont.render(
str(listOfTry[row]), 1, (0, 0, 0))
screen.blit(arrowBackground[row], (0, rowPosY))
screen.blit(historyNumberText, (2, rowPosY + 2))
screen.blit(historyArrowText, (arrowPosX, rowPosY + 2))
screen.blit(numberDelledText, (delledNumberPosX, rowPosY + 2))
row = row + 1
realHistoryHeigh = (len(listOfTry) + 1) * textZoneHeigh
lineHistorySeparation = pygame.Surface((1, ySize))
lineHistorySeparation.fill(lineSeparationColor)
screen.blit(lineHistorySeparation, (35, 0))
realLineHistorySeparation = pygame.Surface((1, realHistoryHeigh))
realLineHistorySeparation.fill(realLineSeparationPlayed)
screen.blit(realLineHistorySeparation, (35, ySize-realHistoryHeigh))
if realHistoryHeigh > ySize:
pageUpText = pageUpDownFont.render("⇈", 1, pageUpDownColor)
screen.blit(pageUpText, (historyAreaWidth + 8, 4))
shadowTop = pygame.image.load(mainDir + "/" + "history-top-shadow.png").convert_alpha()
shadowTop = pygame.transform.scale(shadowTop, (historyAreaWidth, 8))
screen.blit(shadowTop, (0, 0))
def printListOfTry(screen, listOfTry):
historyFont = pygame.font.SysFont("monospace", 14, bold=True)
pageUpDownFont = pygame.font.SysFont("monospace", 18, bold=True)
pageUpDownColor = (220, 36, 4)
lineSeparationColor = (205, 153, 29)
realLineSeparationPlayed = (54,46,38)
xSize, ySize = screen.get_size()
arrowBackground = []
row = 0
arrowPosX = 40
delledNumberPosX = 53
historyZone = pygame.Surface((historyAreaWidth, ySize))
historyZone.fill(history_area_colour)
screen.blit(historyZone, (0, 0))
scroowlingHistory = 0
while row < len(listOfTry):
if (row % 2 == 0): # even
row_coulour = (234, 226, 215)
arrowSign = "←"
else: # odd
row_coulour = (207, 194, 184)
arrowSign = "→"
if listOfTry[row] == 1:
numberToDelColor = (0, 126, 223)
if listOfTry[row] == 2:
numberToDelColor = (40, 149, 0)
if listOfTry[row] == 3:
numberToDelColor = (215, 0, 95)
print("This row: " + str(row))
arrowBackground.append(pygame.Surface(
(historyAreaWidth, textZoneHeigh)))
print(len(arrowBackground))
arrowBackground[row].fill(row_coulour)
rowPosY = ySize - textZoneHeigh - \
(len(listOfTry) - row) * textZoneHeigh
historyNumberText = historyFont.render(str(row), 1, (0, 0, 0))
historyArrowText = historyFont.render(arrowSign, 1, (0, 0, 0))
numberDelledText = historyFont.render(
str(listOfTry[row]), 1, numberToDelColor)
screen.blit(arrowBackground[row], (0, rowPosY))
screen.blit(historyNumberText, (2, rowPosY + 2))
screen.blit(historyArrowText, (arrowPosX, rowPosY + 2))
screen.blit(numberDelledText, (delledNumberPosX, rowPosY + 2))
row = row + 1
print("It success")
realHistoryHeigh = (len(listOfTry) + 1) * textZoneHeigh
lineHistorySeparation = pygame.Surface((1, ySize))
lineHistorySeparation.fill(lineSeparationColor)
screen.blit(lineHistorySeparation, (35, 0))
realLineHistorySeparation = pygame.Surface((1, realHistoryHeigh))
realLineHistorySeparation.fill(realLineSeparationPlayed)
screen.blit(realLineHistorySeparation, (35, ySize-realHistoryHeigh))
if realHistoryHeigh > ySize:
pageUpText = pageUpDownFont.render("⇈", 1, pageUpDownColor)
screen.blit(pageUpText, (historyAreaWidth + 8, 4))
shadowTop = pygame.image.load(mainDir + "/" + "history-top-shadow.png").convert_alpha()
shadowTop = pygame.transform.scale(shadowTop, (historyAreaWidth, 8))
screen.blit(shadowTop, (0, 0))
def showVariant(screen, wtw, posX):
yellow_colour = (205, 153, 29)
xSize, ySize = screen.get_size()
variantFont = pygame.font.SysFont("monospace", 14, bold=True)
wtwText = variantFont.render(wtw, 1, (225, 225, 225))
# Size deffinition
variantBackgroundInformation = surfaceInformations()
variantBackgroundInformation.left = 2
variantBackgroundInformation.right = 2
variantBackgroundInformation.height = textZoneHeigh
variantBackgroundInformation.y = ySize - textZoneHeigh
variantTextInformation = surfaceInformations()
variantTextInformation.width, variantTextInformation.height = variantFont.size(wtw)
variantBackgroundInformation.width = variantTextInformation.width
variantBackgroundInformation.width = variantBackgroundInformation.width + variantBackgroundInformation.left + variantBackgroundInformation.right
variantBackgroundInformation.x = xSize - variantBackgroundInformation.width - posX
variantTextInformation.x = variantBackgroundInformation.x + 1 + variantBackgroundInformation.left
variantTextInformation.y = variantBackgroundInformation.y + 1
#creation
variantBackground = pygame.Surface(
(variantBackgroundInformation.width, variantBackgroundInformation.height))
variantBackground.fill(yellow_colour)
#Blitting
screen.blit(variantBackground, (variantBackgroundInformation.x, variantBackgroundInformation.y))
screen.blit(wtwText, (variantTextInformation.x, variantTextInformation.y))
#Ending
return variantBackgroundInformation.width + variantBackgroundInformation.left + variantBackgroundInformation.right
def trivial(numberOfInitialMatch, wtw, screen):
global programHaveToContinue
global textUserInput
global normalUserInput
global exMode
global normalMode
global textToAnalyse
global normalTextToAnalyse
global finalNormalUserInput
allowedEntry = ["1", "2", "3"]
beginingOfGame = int(time.time())
currentNumberOfMatch = numberOfInitialMatch
normalTextInformation = surfaceInformations()
indicatorTextInformation = surfaceInformations()
listOfTry = []
functionHaveToContinue = True
myfont = pygame.font.SysFont("monospace", 14)
errorToDisplay = False
weHaveAWiner = False
winer = None
while functionHaveToContinue and programHaveToContinue and (weHaveAWiner == False):
userPlayed = 0
computerPlayed = 0
functionHaveToContinue, textToanalyse = analyseTyping(
"trivial", numberOfInitialMatch, wtw)
if textToanalyse["mode"] == "pause":
print("In pause")
beginingOfGame = makeAPause("Trivial", numberOfInitialMatch, wtw, beginingOfGame)
# Redifining variables
xSize, ySize = screen.get_size()
gameAreaDim[0] = xSize - historyAreaWidth
# indicator area variables
indicatorPosition = ((historyAreaWidth + ((xSize - historyAreaWidth) -
indicatorDim[0]) / 2), ySize - textZoneHeigh - indicatorDim[1])
indicatorArea = pygame.Surface((indicatorDim[0], indicatorDim[1]))
# Appling variables
screen.fill(background_colour)
if weHaveAWiner == False:
printListOfTry(screen, listOfTry)
# Indicator area deffinition
indicatorArea.fill(indicator_colour)
screen.blit(indicatorArea, (indicatorPosition[
0], indicatorPosition[1]))
indicatorBorderPositionLeft = (
int(indicatorPosition[0] + circleRadius), int(indicatorPosition[1]))
pygame.draw.circle(screen, indicator_colour, (indicatorBorderPositionLeft[
0], indicatorBorderPositionLeft[1]), circleRadius)
indicatorBorderPositionRight = (int(
indicatorPosition[0] + indicatorDim[0] - circleRadius), int(indicatorPosition[1]))
pygame.draw.circle(screen, indicator_colour, (indicatorBorderPositionRight[
0], indicatorBorderPositionRight[1]), circleRadius)
indicatorRadiusCompleterPosition = (
indicatorPosition[0] + circleRadius, indicatorPosition[1] - circleRadius)
indicatorRadiusCompleterDim = (
indicatorDim[0] - 2 * circleRadius, circleRadius)
indicatorRadiusCompleterArea = pygame.Surface(
(indicatorRadiusCompleterDim[0], indicatorRadiusCompleterDim[1]))
indicatorRadiusCompleterArea.fill(indicator_colour)
screen.blit(indicatorRadiusCompleterArea, (indicatorRadiusCompleterPosition[
0], indicatorRadiusCompleterPosition[1]))
# Matchs deffinition
maxMatchAreaDim = [xSize - historyAreaWidth - (2 * matchAreaBorder.right), ySize - textZoneHeigh - indicatorDim[
1] - matchAreaBorder.top - matchAreaBorder.bottom]
maxMatchDim = [0, 0]
maxMatchDim[0] = maxMatchAreaDim[0] / (numberOfInitialMatch * 1.5)
maxMatchDim[1] = maxMatchDim[0] * matchPicRatio
if maxMatchDim[1] > maxMatchAreaDim[1]:
matchDim = [int(maxMatchAreaDim[1] / matchPicRatio),
int(maxMatchAreaDim[1])]
else:
matchDim = [int(maxMatchDim[0]), int(
maxMatchDim[0] * matchPicRatio)]
tempImageMatch = pygame.image.load(mainDir + "/" + "match.png").convert_alpha()
matchMaxWidth, matchMaxHeight = tempImageMatch.get_rect().size
if matchDim[0] > matchMaxWidth:
matchDim[0] = matchMaxWidth
matchDim[1] = matchMaxHeight
matchAreaDim = [matchDim[0] * numberOfInitialMatch, matchDim[1]]
matchAreaPos = [historyAreaWidth + matchAreaBorder.left + (
(maxMatchAreaDim[0] - matchAreaDim[0]) / 2), (ySize - indicatorDim[1] - matchDim[1]) / 2]
secondMatchAreaPos = [matchAreaPos[
0] + (matchAreaDim[0] - (numberOfInitialMatch * 1.5) * matchDim[0]) / 2, matchAreaPos[1]]
matchRessizing = matchMaxWidth/matchDim[0]
if wtw == "ttl":
lastBurnedMatch = [1, 2, 3]
elif wtw == "ltl":
lastBurnedMatch = [2, 3, 4]
i = 0
matchS = []
while i < numberOfInitialMatch:
if i < currentNumberOfMatch:
if currentNumberOfMatch in lastBurnedMatch:
initialSignDistanceToMatch = matchDim[1]/7
if i+1 in lastBurnedMatch:
matchS.append(pygame.image.load(
mainDir + "/" + "match-burned.png").convert_alpha())
else:
matchS.append(pygame.image.load(
mainDir + "/" + "match.png").convert_alpha())
else:
initialSignDistanceToMatch = matchDim[1]/24
if i >= (currentNumberOfMatch - 3):
matchS.append(pygame.image.load(
mainDir + "/" + "match-allowed.png").convert_alpha())
else:
matchS.append(pygame.image.load(
mainDir + "/" + "match.png").convert_alpha())
else:
matchS.append(pygame.image.load(
mainDir + "/" + "match-void.png").convert_alpha())
matchLeftVoid = 0
if i != 0:
matchLeftVoid = matchDim[0] / 2
currentMatchPos = [secondMatchAreaPos[
0] + i * (matchLeftVoid + matchDim[0]), secondMatchAreaPos[1]]
matchS[i] = pygame.transform.scale(
matchS[i], (matchDim[0], matchDim[1]))
screen.blit(
matchS[i], (currentMatchPos[0], currentMatchPos[1]))
if i == 0:
#adding crown or warning sign
initialSignPos = [0,0]
initialSignPos[1] = currentMatchPos[1] - initialSignDistanceToMatch
if wtw == "ttl":
initialSign = pygame.image.load(mainDir + "/" + "crown.png").convert_alpha()
if wtw == "ltl":
initialSign = pygame.image.load(mainDir + "/" + "skull.png").convert_alpha()
initialSignSize = initialSign.get_rect().size
initialSignSize = [int(initialSignSize[0]/matchRessizing),int(initialSignSize[1]/matchRessizing)]
initialSign = pygame.transform.scale(initialSign, (initialSignSize[0], initialSignSize[1]))
initialSignPos[0] = (currentMatchPos[0]+(matchDim[0]/2)) - (initialSignSize[0]/2)
screen.blit(initialSign, (initialSignPos[0], initialSignPos[1]))
i = i + 1
indicatorFont = pygame.font.SysFont("monospace", 34)
indicatorTextContent = str(
currentNumberOfMatch) + "/" + str(numberOfInitialMatch)
indicatorText = indicatorFont.render(
indicatorTextContent, 1, (255, 255, 255))
indicatorTextInformation.width, indicatorTextInformation.height = indicatorFont.size(
indicatorTextContent)
indicatorTextInformation.x = indicatorPosition[
0] + (indicatorDim[0] - indicatorTextInformation.width) / 2
indicatorTextInformation.y = indicatorPosition[1] + 5
screen.blit(indicatorText, (indicatorTextInformation.x,
indicatorTextInformation.y))
if finalNormalUserInput:
getFromAnalysis = trivialAnalysis(
currentNumberOfMatch, numberOfInitialMatch, wtw, finalNormalUserInput)
finalNormalUserInput = False
if getFromAnalysis[0] == True:
userPlayed = getFromAnalysis[2]
listOfTry.append(userPlayed)
else:
errorToDisplay = getFromAnalysis[1]
if getFromAnalysis[0] == True:
computerPlayed = playTrivial(
currentNumberOfMatch - userPlayed,wtw)
listOfTry.append(computerPlayed)
currentNumberOfMatch = currentNumberOfMatch - userPlayed
if ((currentNumberOfMatch == 0) and (wtw == "ttl")) or ((currentNumberOfMatch == 1) and (wtw == "ltl")):
winer = True
else:
currentNumberOfMatch = currentNumberOfMatch - computerPlayed
if (currentNumberOfMatch == 0 and (wtw == "ttl")) or ((currentNumberOfMatch == 1) and (wtw == "ltl")):
winer = False
numberOfMatchDelled = numberOfInitialMatch - currentNumberOfMatch
if (currentNumberOfMatch == 0 and (wtw == "ttl")) or ((currentNumberOfMatch == 1) and (wtw == "ltl")):
weHaveAWiner = True
timeOfEndOfGame = int(time.time()) - beginingOfGame
else:
print("we have a winer")
timeOfEndOfGame = int(time.time()) - beginingOfGame
if textToanalyse in allowedEntry:
normalTextZone = myfont.render(
"".join(textToanalyse), 1, (255, 255, 255))
screen.blit(normalTextZone, (100, 100))
makeTextZone("Trivial", None)
timeZoneWidth = makeTimetZone(beginingOfGame)
wtwZoneWidth = showVariant(screen, wtw, timeZoneWidth)
if textToanalyse["mode"] == "normal":
errorToDisplay = False
normalText = myfont.render(
"".join(textToanalyse["content"]), 1, (255, 255, 255))
normalTextInformation.width, normalTextInformation.height = normalText.get_size()
normalTextInformation.x = xSize - normalTextInformation.width - 5 - wtwZoneWidth - timeZoneWidth
normalTextInformation.y = ySize - textZoneHeigh
screen.blit(normalText, (normalTextInformation.x,
normalTextInformation.y))
if errorToDisplay != False:
normalText = myfont.render(errorToDisplay, 1, red)
normalTextInformation.width, normalTextInformation.height = normalText.get_size()
normalTextInformation.x = xSize - normalTextInformation.width - 5 - wtwZoneWidth - timeZoneWidth
normalTextInformation.y = ySize - textZoneHeigh
screen.blit(normalText, (normalTextInformation.x,
normalTextInformation.y))
# testSurface = pygame.Surface((indicatorTextInformation.width, indicatorTextInformation.height))
# testSurface.fill(red)
# screen.blit(testSurface, (indicatorTextInformation.x,indicatorTextInformation.y))
#####################
pygame.display.flip()
#####################
while functionHaveToContinue and programHaveToContinue:
winingFallingScreen(
winer, wtw, numberOfInitialMatch, timeOfEndOfGame)
functionHaveToContinue, textToanalyse = analyseTyping(
"trivial", numberOfInitialMatch, wtw)
makeTextZone("Trivial", None)
#####################
pygame.display.flip()
#####################
return False
def marienbadInitialColumns(numberOfLines):
matchMatrix = []
columns = (numberOfLines*2)-1
number = 0
i = 1
while i <= columns:
if i <= (columns/2)+1:
number=number+1
else:
number=number-1
matchMatrix.append(number)
i=i+1
return matchMatrix
def marienbadIsItAWinerSituation(matchMatrix, wtw):
columnWithMatch = []
i=0
for row in matchMatrix:
if row != 0:
columnWithMatch.append(i)
i=i+1
if wtw == "ttl":
if len(columnWithMatch)==1:
winingColumn=columnWithMatch
else:
winingColumn=False
elif wtw == "ltl":
if (len(columnWithMatch)==1) and (matchMatrix[columnWithMatch[0]] > 1):
winingColumn=columnWithMatch
elif (len(columnWithMatch) == 2 ) and (matchMatrix[columnWithMatch[0]] == 1) and (matchMatrix[columnWithMatch[1]] == 1):
winingColumn=columnWithMatch
else:
winingColumn=False
else:
winingColumn=False
return winingColumn
def getNimSum(matchMatrix):
columns = len(matchMatrix)
numberOfLines = int((columns+1)/2)
lineSums = [0] * numberOfLines
i=0
for column in matchMatrix:
j=0
while j < column:
lineSums[j]=lineSums[j]+1
j=j+1
i=i+1
return lineSums
def playMarienbad(matchMatrix,wtw):
columns = len(matchMatrix)
numberOfLines = int((columns+1)/2)
lineSums = getNimSum(matchMatrix)
allowdedColumnToPlay = []
i=0
for column in matchMatrix:
if column > 0:
allowdedColumnToPlay.append(i)
i=i+1
lineSumsBinari = calculateLineSumsBinari(lineSums)
print(lineSumsBinari)
finalSum = sum(lineSumsBinari)
listOfDigits=list(str(finalSum))
print(listOfDigits)
itIsPossibleToWin = False
for aDigit in listOfDigits:
if (int(aDigit)%2 == 1):
itIsPossibleToWin = True
matchLineContainingOdd = None
if itIsPossibleToWin == False:
columnToPlay = random.sample(allowdedColumnToPlay, 1)[0]
maxNumberInTheColumn=matchMatrix[columnToPlay]
numberOfMatchToPlay = random.randint(1,maxNumberInTheColumn)
whatComputerWillPlay = [columnToPlay,numberOfMatchToPlay]
columnToPlay = whatComputerWillPlay
else:
theSumColumnContainingTheOddDigit = marienbadWitchColumnIsOdd(listOfDigits)
matchLineContainingOdd = marienbadWitchMatchLineContainOdd(matchMatrix)
columnToPlay = matchLineContainingOdd
return columnToPlay
def marienbadWitchColumnIsOdd(listOfDigits):
for i in range(len(listOfDigits)):
aDigit = listOfDigits[i]
if (int(aDigit)%2 == 1):
return i
def calculateLineSumsBinari(lineSums):
lineSumsBinari = []
i = 0
for decimalNum in lineSums:
lineSumsBinari.append(int("{0:b}".format(decimalNum)))
return lineSumsBinari
def marienbadWitchMatchLineContainOdd(matchMatrix):
lineSums = getNimSum(matchMatrix)
lineSumsBinari = calculateLineSumsBinari(lineSums)
finalSum = sum(lineSumsBinari)
listOfDigits=list(str(finalSum))
theSumColumnContainingTheOddDigit = marienbadWitchColumnIsOdd(listOfDigits)
# Convert LineSums to Binary representation
lineSumsBinari = []
i = 0
for decimalNum in lineSums:
lineSumsBinari.append(int("{0:b}".format(decimalNum)))
# Normalise non-sinificative zeros
i = 0
maxLen = 0
for binaryNum in lineSumsBinari:
tempLen = len(str(binaryNum))
if tempLen > maxLen:
maxLen = tempLen
i=i+1
i = 0
for binaryNum in lineSumsBinari:
tempLen = len(str(binaryNum))
howZeroToAdd = maxLen - tempLen
if howZeroToAdd > 0:
for j in range(1,howZeroToAdd+1):
lineSumsBinari[i] = "0" + str(lineSumsBinari[i])
else:
lineSumsBinari[i] = str(lineSumsBinari[i])
i=i+1
#Only let the theSumColumnContainingTheOddDigitNTH digit in each binaryNum
octetsOfDesiredColumn = []
i = 0
for binaryNum in lineSumsBinari:
extractedOctet = list(str(binaryNum))[theSumColumnContainingTheOddDigit]
octetsOfDesiredColumn.append(extractedOctet)
i=i+1
# Search the lines containing 1
i = 0
linesImpliyingOdd = []
for i in range(0,len(octetsOfDesiredColumn)):
if octetsOfDesiredColumn[i] == "1":
linesImpliyingOdd.append(i)
i=i+1
higherMatchLine = linesImpliyingOdd[-1]
# Search the column matching the lines.
i = 0
for match in matchMatrix:
if match == higherMatchLine:
theColumn=i
i=i+1
print("matchMatrix: " + str(matchMatrix))
print("lineSums: " + str(lineSums))
print("higherMatchLine: " + str(higherMatchLine))
print("Là ↓")
print(theColumn)
return(theColumn)
def marienbadAnalysis(matchMatrix, userInput):
# Constant for all the folowing operations
columns = len(matchMatrix)
numberOfLines = 2 * (columns+1)
allowedColumns = range(columns)
maximumMatchMatrix = marienbadInitialColumns(numberOfLines)
# Test if it is possible to play
continueFunction = False
for column in matchMatrix:
if (column != 0) and (continueFunction == False) :
continueFunction = True
if (continueFunction == True):
numberOfMatchsToDel = 0
syntaxToTestImputValidity = "^ *([0-9]+) *(=|-) *([0-9]+) *$"
if re.match(syntaxToTestImputValidity, userInput) is not None:
print("True")
syntaxToExtractOptions = "^ *(?P<column>[0-9]+) *(?P<operator>(=|-)) *(?P<numberOfMatchUsed>[0-9]+) *$"
deletingMatchOparation = re.match(syntaxToExtractOptions,userInput)
columnToDelOnIt = int(deletingMatchOparation.group("column"))
numberOfMatchUsed = int(deletingMatchOparation.group("numberOfMatchUsed"))
delletingOperator = deletingMatchOparation.group("operator")
if (columnToDelOnIt in allowedColumns) :
if (numberOfMatchUsed != 0) or (delletingOperator != "-"):
if (delletingOperator == "=") :
if (numberOfMatchUsed <= matchMatrix[columnToDelOnIt]):
numberOfMatchsToDel = matchMatrix[columnToDelOnIt]-numberOfMatchUsed
matchMatrix[columnToDelOnIt] = matchMatrix[columnToDelOnIt]-numberOfMatchsToDel
answer = [True, matchMatrix, str(columnToDelOnIt) + "-" + str(numberOfMatchsToDel)]
else:
answer = [False, "You can not set a number higher than content."]
elif (delletingOperator == "-") :
if (numberOfMatchUsed <= matchMatrix[columnToDelOnIt]):
numberOfMatchsToDel = numberOfMatchUsed
matchMatrix[columnToDelOnIt] = matchMatrix[columnToDelOnIt]-numberOfMatchsToDel
answer = [True, matchMatrix, str(columnToDelOnIt) + "-" + str(numberOfMatchsToDel)]
else:
answer = [False, "You can not use a number higher than content."]
else:
answer = [False, "You can not del no match!"]
else:
answer = [False, "“" + str(deletingMatchOparation.group("column")) + "” is not in valid range."]
else:
answer = [False, "“" + userInput + "” is not a valid syntax."]
else:
answer = [False, 0]
return answer
def marienbad(numberOfLines, wtw, screen):
global programHaveToContinue
global textUserInput
global normalUserInput
global exMode
global normalMode
global textToAnalyse
global normalTextToAnalyse
global finalNormalUserInput
global historyAreaWidth
maximumMatchMatrix = marienbadInitialColumns(numberOfLines)
currentMatchMatrix = copy.deepcopy(maximumMatchMatrix)
numberOfColumns = numberOfLines*2 - 1
# Initialisation
beginingOfGame = int(time.time())
listOfTry = []
functionHaveToContinue = True
errorToDisplay = False
weHaveAWiner = False
winer = None
while functionHaveToContinue and programHaveToContinue and (weHaveAWiner == False):
userPlayed = 0
computerPlayed = 0
if weHaveAWiner == False:
functionHaveToContinue, textToanalyse = analyseTyping("marienbad", numberOfLines, wtw)
if textToanalyse["mode"] == "pause":
print("In pause")
beginingOfGame = makeAPause("Marienbad", numberOfInitialMatch, wtw, beginingOfGame)
# Redifining variables
xSize, ySize = screen.get_size()
gameAreaDim[0] = xSize - historyAreaWidth
# loading images
tempImageMatch = pygame.image.load(mainDir + "/" + "match.png").convert_alpha()
# Creatiing surface information
gameAreaInfo = surfaceInformations()
realGameAreaInfo = surfaceInformations()
matchInfo = surfaceInformations()
maxMatchInfo = surfaceInformations()
matchAreaInfo = surfaceInformations()
normalTextInformation = surfaceInformations()
wtwZoneInfo = surfaceInformations()
columnNumberInfo = surfaceInformations()
matchHorizontalSeparation = 0
# Fixing constants
matchInfo.top = 10
realGameAreaInfo.top = 20
realGameAreaInfo.bottom = 30
realGameAreaInfo.left = 30
realGameAreaInfo.right = 30
# Calculatiing element’s size
realGameAreaInfo.height = ySize - textZoneHeigh - realGameAreaInfo.top - realGameAreaInfo.bottom
realGameAreaInfo.width = xSize - historyAreaWidth - realGameAreaInfo.left - realGameAreaInfo.right
maxMatchInfo.width, maxMatchInfo.height = tempImageMatch.get_rect().size
matchInfo.height = realGameAreaInfo.height / (numberOfLines*1.2)
matchInfo.top = matchInfo.height*0.2
if matchInfo.height >= maxMatchInfo.height:
matchInfo.height = maxMatchInfo.height
matchInfo.width = maxMatchInfo.width
else:
matchInfo.width = matchInfo.height / matchPicRatio
matchHorizontalSeparation = (realGameAreaInfo.width - (matchInfo.width*numberOfColumns)) / (numberOfColumns-1)
if matchHorizontalSeparation > matchInfo.height*0.66:
matchHorizontalSeparation = matchInfo.height*0.66
# calculating positions
matchAreaInfo.width = matchInfo.width*numberOfColumns + (numberOfColumns-1)*matchHorizontalSeparation
realGameAreaInfo.x = historyAreaWidth + realGameAreaInfo.left + (realGameAreaInfo.width-matchAreaInfo.width)/2
matchAreaInfo.height = matchInfo.height*numberOfLines + (numberOfLines-1)*matchInfo.top
realGameAreaInfo.y = realGameAreaInfo.top + (realGameAreaInfo.height-matchAreaInfo.height)/2
matchPositions = []
i = 0
for numberOfMatchInAColumn in maximumMatchMatrix:
j = 0
matchPositions.append([])
cumuledX = matchInfo.width + matchHorizontalSeparation
while j < numberOfMatchInAColumn:
matchPositions[i].append(surfaceInformations())
cumuledY = matchInfo.height + matchInfo.top
matchPositions[i][j].x = realGameAreaInfo.x + i*cumuledX
matchPositions[i][j].y = ySize-textZoneHeigh - realGameAreaInfo.y - (j+1)*cumuledY
j=j+1
i = i+1
# Bliting first interface
screen.fill(background_colour)
printMarienbadListOfTry(screen, listOfTry)
# Treating normal imput
if finalNormalUserInput:
getFromAnalysis = marienbadAnalysis(currentMatchMatrix, finalNormalUserInput)
finalNormalUserInput = False
if getFromAnalysis[0] == True:
currentMatchMatrix = getFromAnalysis[1]
listOfTry.append(getFromAnalysis[2])
else:
errorToDisplay = getFromAnalysis[1]
if getFromAnalysis[0] == True:
computerPlayed = playMarienbad(currentMatchMatrix,wtw)
listOfTry.append(str(computerPlayed) + "-" + "1")
currentMatchMatrix[computerPlayed] = currentMatchMatrix[computerPlayed]-1
# Defining if we are in wining position
winingColumn = marienbadIsItAWinerSituation(currentMatchMatrix, wtw)
# Bliting the game
columnNumberFont = pygame.font.SysFont("monospace", 18, bold=True)
i = 0
for column in matchPositions:
j = 0
for match in column:
if (currentMatchMatrix[i] < maximumMatchMatrix[i]) and (j+1 > currentMatchMatrix[i]):
visualMatch = pygame.image.load(mainDir + "/" + "match-void.png").convert_alpha()
else:
if winingColumn:
visualMatch = pygame.image.load(mainDir + "/" + "match-burned.png").convert_alpha()
else:
visualMatch = pygame.image.load(mainDir + "/" + "match.png").convert_alpha()
visualMatch = pygame.transform.scale(visualMatch, (int(matchInfo.width), int(matchInfo.height)))
screen.blit(visualMatch, (match.x, match.y))
j=j+1
columnNumberImage = columnNumberFont.render(str(i), 1, (0, 0,0))
columnNumberInfo.width, columnNumberInfo.height = columnNumberImage.get_size()
columnNumberInfo.x = column[0].x + (column[0].width/2) - (columnNumberInfo.width/2)
screen.blit(columnNumberImage, (columnNumberInfo.x, column[0].y+matchInfo.height+12))
i = i+1
# Bliting second interface
makeTextZone("Marienbad", None)
timeZoneWidth = makeTimetZone(beginingOfGame)
wtwZoneWidth = showVariant(screen, wtw, timeZoneWidth)
# Display normal mode text
normalFont = pygame.font.SysFont("monospace", 14)
if textToanalyse["mode"] == "normal":
errorToDisplay = False
normalText = normalFont.render(
"".join(textToanalyse["content"]), 1, (255, 255, 255))
normalTextInformation.width, normalTextInformation.height = normalText.get_size()
normalTextInformation.x = xSize - normalTextInformation.width - 5 - wtwZoneWidth - timeZoneWidth
normalTextInformation.y = ySize - textZoneHeigh
screen.blit(normalText, (normalTextInformation.x,
normalTextInformation.y))
if errorToDisplay != False:
normalText = normalFont.render(errorToDisplay, 1, red)
normalTextInformation.width, normalTextInformation.height = normalText.get_size()
normalTextInformation.x = xSize - normalTextInformation.width - 5 - wtwZoneWidth - timeZoneWidth
normalTextInformation.y = ySize - textZoneHeigh
screen.blit(normalText, (normalTextInformation.x,
normalTextInformation.y))
#####################
pygame.display.flip()
#####################
else:
print("we have a winer")
timeOfEndOfGame = int(time.time()) - beginingOfGame
while functionHaveToContinue and programHaveToContinue:
winingFallingScreen(
winer, wtw, numberOfInitialMatch, timeOfEndOfGame)
functionHaveToContinue, textToanalyse = analyseTyping(
"marienbad", numberOfInitialMatch, wtw)
makeTextZone("Marienbad", None)
#####################
pygame.display.flip()
#####################
return False
programHaveToContinue = True
variant = None
generalState = whatToDo()
def main(variant="trivial", number=numberOfInitialMatch, wtw="ttl"):
global generalState
global programHaveToContinue
while programHaveToContinue:
if variant not in [0, None, ""]:
variant = generalState.variant
if number not in [0, None, ""]:
number = generalState.number
if wtw not in [0, None, ""]:
wtw = generalState.wtw
if variant == "trivial":
trivial(number, wtw, screen)
elif variant == "marienbad":
marienbad(number, wtw, screen)
main("trivial", numberOfInitialMatch, "ttl")
| int(s)
return True
except ValueError:
return False
def p |
fwd.go | // Package forward implements http handler that forwards requests to remote server
// and serves back the response
// websocket proxying support based on https://github.com/yhat/wsutil
package forward
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"os"
"reflect"
"strings"
"time"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"github.com/vulcand/oxy/utils"
)
// OxyLogger interface of the internal
type OxyLogger interface {
log.FieldLogger
GetLevel() log.Level
}
type internalLogger struct {
*log.Logger
}
func (i *internalLogger) GetLevel() log.Level {
return i.Level
}
// ReqRewriter can alter request headers and body
type ReqRewriter interface {
Rewrite(r *http.Request)
}
type optSetter func(f *Forwarder) error
// PassHostHeader specifies if a client's Host header field should be delegated
func PassHostHeader(b bool) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.passHost = b
return nil
}
}
// RoundTripper sets a new http.RoundTripper
// Forwarder will use http.DefaultTransport as a default round tripper
func RoundTripper(r http.RoundTripper) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.roundTripper = r
return nil
}
}
// Rewriter defines a request rewriter for the HTTP forwarder
func Rewriter(r ReqRewriter) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.rewriter = r
return nil
}
}
// WebsocketTLSClientConfig define the websocker client TLS configuration
func WebsocketTLSClientConfig(tcc *tls.Config) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.tlsClientConfig = tcc
return nil
}
}
// ErrorHandler is a functional argument that sets error handler of the server
func ErrorHandler(h utils.ErrorHandler) optSetter {
return func(f *Forwarder) error {
f.errHandler = h
return nil
}
}
// BufferPool specifies a buffer pool for httputil.ReverseProxy.
func BufferPool(pool httputil.BufferPool) optSetter {
return func(f *Forwarder) error {
f.bufferPool = pool
return nil
}
}
// Stream specifies if HTTP responses should be streamed.
func Stream(stream bool) optSetter {
return func(f *Forwarder) error {
f.stream = stream
return nil
}
}
// Logger defines the logger the forwarder will use.
//
// It defaults to logrus.StandardLogger(), the global logger used by logrus.
func Logger(l log.FieldLogger) optSetter {
return func(f *Forwarder) error {
if logger, ok := l.(OxyLogger); ok {
f.log = logger
return nil
}
if logger, ok := l.(*log.Logger); ok {
f.log = &internalLogger{Logger: logger}
return nil
}
return errors.New("the type of the logger must be OxyLogger or logrus.Logger")
}
}
// StateListener defines a state listener for the HTTP forwarder
func StateListener(stateListener UrlForwardingStateListener) optSetter {
return func(f *Forwarder) error {
f.stateListener = stateListener
return nil
}
}
// WebsocketConnectionClosedHook defines a hook called when websocket connection is closed
func WebsocketConnectionClosedHook(hook func(req *http.Request, conn net.Conn)) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.websocketConnectionClosedHook = hook
return nil
}
}
// ResponseModifier defines a response modifier for the HTTP forwarder
func ResponseModifier(responseModifier func(*http.Response) error) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.modifyResponse = responseModifier
return nil
}
}
// StreamingFlushInterval defines a streaming flush interval for the HTTP forwarder
func StreamingFlushInterval(flushInterval time.Duration) optSetter {
return func(f *Forwarder) error {
f.httpForwarder.flushInterval = flushInterval
return nil
}
}
// ErrorHandlingRoundTripper a error handling round tripper
type ErrorHandlingRoundTripper struct {
http.RoundTripper
errorHandler utils.ErrorHandler
}
// RoundTrip executes the round trip
func (rt ErrorHandlingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
res, err := rt.RoundTripper.RoundTrip(req)
if err != nil {
// We use the recorder from httptest because there isn't another `public` implementation of a recorder.
recorder := httptest.NewRecorder()
rt.errorHandler.ServeHTTP(recorder, req, err)
res = recorder.Result()
err = nil
}
return res, err
}
// Forwarder wraps two traffic forwarding implementations: HTTP and websockets.
// It decides based on the specified request which implementation to use
type Forwarder struct {
*httpForwarder
*handlerContext
stateListener UrlForwardingStateListener
stream bool
}
// handlerContext defines a handler context for error reporting and logging
type handlerContext struct {
errHandler utils.ErrorHandler
}
// httpForwarder is a handler that can reverse proxy
// HTTP traffic
type httpForwarder struct {
roundTripper http.RoundTripper
rewriter ReqRewriter
passHost bool
flushInterval time.Duration
modifyResponse func(*http.Response) error
tlsClientConfig *tls.Config
log OxyLogger
bufferPool httputil.BufferPool
websocketConnectionClosedHook func(req *http.Request, conn net.Conn)
}
const defaultFlushInterval = time.Duration(100) * time.Millisecond
// Connection states
const (
StateConnected = iota
StateDisconnected
)
// UrlForwardingStateListener URL forwarding state listener
type UrlForwardingStateListener func(*url.URL, int)
// New creates an instance of Forwarder based on the provided list of configuration options
func New(setters ...optSetter) (*Forwarder, error) |
// ServeHTTP decides which forwarder to use based on the specified
// request and delegates to the proper implementation
func (f *Forwarder) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if f.log.GetLevel() >= log.DebugLevel {
logEntry := f.log.WithField("Request", utils.DumpHttpRequest(req))
logEntry.Debug("vulcand/oxy/forward: begin ServeHttp on request")
defer logEntry.Debug("vulcand/oxy/forward: completed ServeHttp on request")
}
if f.stateListener != nil {
f.stateListener(req.URL, StateConnected)
defer f.stateListener(req.URL, StateDisconnected)
}
if IsWebsocketRequest(req) {
f.httpForwarder.serveWebSocket(w, req, f.handlerContext)
} else {
f.httpForwarder.serveHTTP(w, req, f.handlerContext)
}
}
func (f *httpForwarder) getUrlFromRequest(req *http.Request) *url.URL {
// If the Request was created by Go via a real HTTP request, RequestURI will
// contain the original query string. If the Request was created in code, RequestURI
// will be empty, and we will use the URL object instead
u := req.URL
if req.RequestURI != "" {
parsedURL, err := url.ParseRequestURI(req.RequestURI)
if err == nil {
u = parsedURL
} else {
f.log.Warnf("vulcand/oxy/forward: error when parsing RequestURI: %s", err)
}
}
return u
}
// Modify the request to handle the target URL
func (f *httpForwarder) modifyRequest(outReq *http.Request, target *url.URL) {
outReq.URL = utils.CopyURL(outReq.URL)
outReq.URL.Scheme = target.Scheme
outReq.URL.Host = target.Host
u := f.getUrlFromRequest(outReq)
outReq.URL.Path = u.Path
outReq.URL.RawPath = u.RawPath
outReq.URL.RawQuery = u.RawQuery
outReq.RequestURI = "" // Outgoing request should not have RequestURI
outReq.Proto = "HTTP/1.1"
outReq.ProtoMajor = 1
outReq.ProtoMinor = 1
if f.rewriter != nil {
f.rewriter.Rewrite(outReq)
}
// Do not pass client Host header unless optsetter PassHostHeader is set.
if !f.passHost {
outReq.Host = target.Host
}
}
// serveHTTP forwards websocket traffic
func (f *httpForwarder) serveWebSocket(w http.ResponseWriter, req *http.Request, ctx *handlerContext) {
if f.log.GetLevel() >= log.DebugLevel {
logEntry := f.log.WithField("Request", utils.DumpHttpRequest(req))
logEntry.Debug("vulcand/oxy/forward/websocket: begin ServeHttp on request")
defer logEntry.Debug("vulcand/oxy/forward/websocket: completed ServeHttp on request")
}
outReq := f.copyWebSocketRequest(req)
dialer := websocket.DefaultDialer
if outReq.URL.Scheme == "wss" && f.tlsClientConfig != nil {
dialer.TLSClientConfig = f.tlsClientConfig.Clone()
// WebSocket is only in http/1.1
dialer.TLSClientConfig.NextProtos = []string{"http/1.1"}
}
targetConn, resp, err := dialer.DialContext(outReq.Context(), outReq.URL.String(), outReq.Header)
if err != nil {
if resp == nil {
ctx.errHandler.ServeHTTP(w, req, err)
} else {
f.log.Errorf("vulcand/oxy/forward/websocket: Error dialing %q: %v with resp: %d %s", outReq.Host, err, resp.StatusCode, resp.Status)
hijacker, ok := w.(http.Hijacker)
if !ok {
f.log.Errorf("vulcand/oxy/forward/websocket: %s can not be hijack", reflect.TypeOf(w))
ctx.errHandler.ServeHTTP(w, req, err)
return
}
conn, _, errHijack := hijacker.Hijack()
if errHijack != nil {
f.log.Errorf("vulcand/oxy/forward/websocket: Failed to hijack responseWriter")
ctx.errHandler.ServeHTTP(w, req, errHijack)
return
}
defer conn.Close()
errWrite := resp.Write(conn)
if errWrite != nil {
f.log.Errorf("vulcand/oxy/forward/websocket: Failed to forward response")
ctx.errHandler.ServeHTTP(w, req, errWrite)
return
}
}
return
}
// Only the targetConn choose to CheckOrigin or not
upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
return true
}}
utils.RemoveHeaders(resp.Header, WebsocketUpgradeHeaders...)
utils.CopyHeaders(resp.Header, w.Header())
underlyingConn, err := upgrader.Upgrade(w, req, resp.Header)
if err != nil {
f.log.Errorf("vulcand/oxy/forward/websocket: Error while upgrading connection : %v", err)
return
}
defer func() {
underlyingConn.Close()
targetConn.Close()
if f.websocketConnectionClosedHook != nil {
f.websocketConnectionClosedHook(req, underlyingConn.UnderlyingConn())
}
}()
errClient := make(chan error, 1)
errBackend := make(chan error, 1)
replicateWebsocketConn := func(dst, src *websocket.Conn, errc chan error) {
forward := func(messageType int, reader io.Reader) error {
writer, err := dst.NextWriter(messageType)
if err != nil {
return err
}
_, err = io.Copy(writer, reader)
if err != nil {
return err
}
return writer.Close()
}
src.SetPingHandler(func(data string) error {
return forward(websocket.PingMessage, bytes.NewReader([]byte(data)))
})
src.SetPongHandler(func(data string) error {
return forward(websocket.PongMessage, bytes.NewReader([]byte(data)))
})
for {
msgType, reader, err := src.NextReader()
if err != nil {
m := websocket.FormatCloseMessage(websocket.CloseNormalClosure, fmt.Sprintf("%v", err))
if e, ok := err.(*websocket.CloseError); ok {
if e.Code != websocket.CloseNoStatusReceived {
m = nil
// Following codes are not valid on the wire so just close the
// underlying TCP connection without sending a close frame.
if e.Code != websocket.CloseAbnormalClosure &&
e.Code != websocket.CloseTLSHandshake {
m = websocket.FormatCloseMessage(e.Code, e.Text)
}
}
}
errc <- err
if m != nil {
forward(websocket.CloseMessage, bytes.NewReader([]byte(m)))
}
break
}
err = forward(msgType, reader)
if err != nil {
errc <- err
break
}
}
}
go replicateWebsocketConn(underlyingConn, targetConn, errClient)
go replicateWebsocketConn(targetConn, underlyingConn, errBackend)
var message string
select {
case err = <-errClient:
message = "vulcand/oxy/forward/websocket: Error when copying from backend to client: %v"
case err = <-errBackend:
message = "vulcand/oxy/forward/websocket: Error when copying from client to backend: %v"
}
if e, ok := err.(*websocket.CloseError); !ok || e.Code == websocket.CloseAbnormalClosure {
f.log.Errorf(message, err)
}
}
// copyWebsocketRequest makes a copy of the specified request.
func (f *httpForwarder) copyWebSocketRequest(req *http.Request) (outReq *http.Request) {
outReq = new(http.Request)
*outReq = *req // includes shallow copies of maps, but we handle this below
outReq.URL = utils.CopyURL(req.URL)
outReq.URL.Scheme = req.URL.Scheme
// sometimes backends might be registered as HTTP/HTTPS servers so translate URLs to websocket URLs.
switch req.URL.Scheme {
case "https":
outReq.URL.Scheme = "wss"
case "http":
outReq.URL.Scheme = "ws"
}
u := f.getUrlFromRequest(outReq)
outReq.URL.Path = u.Path
outReq.URL.RawPath = u.RawPath
outReq.URL.RawQuery = u.RawQuery
outReq.RequestURI = "" // Outgoing request should not have RequestURI
outReq.URL.Host = req.URL.Host
if !f.passHost {
outReq.Host = req.URL.Host
}
outReq.Header = make(http.Header)
// gorilla websocket use this header to set the request.Host tested in checkSameOrigin
outReq.Header.Set("Host", outReq.Host)
utils.CopyHeaders(outReq.Header, req.Header)
utils.RemoveHeaders(outReq.Header, WebsocketDialHeaders...)
if f.rewriter != nil {
f.rewriter.Rewrite(outReq)
}
return outReq
}
// serveHTTP forwards HTTP traffic using the configured transport
func (f *httpForwarder) serveHTTP(w http.ResponseWriter, inReq *http.Request, ctx *handlerContext) {
if f.log.GetLevel() >= log.DebugLevel {
logEntry := f.log.WithField("Request", utils.DumpHttpRequest(inReq))
logEntry.Debug("vulcand/oxy/forward/http: begin ServeHttp on request")
defer logEntry.Debug("vulcand/oxy/forward/http: completed ServeHttp on request")
}
start := time.Now().UTC()
outReq := new(http.Request)
*outReq = *inReq // includes shallow copies of maps, but we handle this in Director
revproxy := httputil.ReverseProxy{
Director: func(req *http.Request) {
f.modifyRequest(req, inReq.URL)
},
Transport: f.roundTripper,
FlushInterval: f.flushInterval,
ModifyResponse: f.modifyResponse,
BufferPool: f.bufferPool,
}
if f.log.GetLevel() >= log.DebugLevel {
pw := utils.NewProxyWriter(w)
revproxy.ServeHTTP(pw, outReq)
if inReq.TLS != nil {
f.log.Debugf("vulcand/oxy/forward/http: Round trip: %v, code: %v, Length: %v, duration: %v tls:version: %x, tls:resume:%t, tls:csuite:%x, tls:server:%v",
inReq.URL, pw.StatusCode(), pw.GetLength(), time.Now().UTC().Sub(start),
inReq.TLS.Version,
inReq.TLS.DidResume,
inReq.TLS.CipherSuite,
inReq.TLS.ServerName)
} else {
f.log.Debugf("vulcand/oxy/forward/http: Round trip: %v, code: %v, Length: %v, duration: %v",
inReq.URL, pw.StatusCode(), pw.GetLength(), time.Now().UTC().Sub(start))
}
} else {
revproxy.ServeHTTP(w, outReq)
}
for key := range w.Header() {
if strings.HasPrefix(key, http.TrailerPrefix) {
if fl, ok := w.(http.Flusher); ok {
fl.Flush()
}
break
}
}
}
// IsWebsocketRequest determines if the specified HTTP request is a
// websocket handshake request
func IsWebsocketRequest(req *http.Request) bool {
containsHeader := func(name, value string) bool {
items := strings.Split(req.Header.Get(name), ",")
for _, item := range items {
if value == strings.ToLower(strings.TrimSpace(item)) {
return true
}
}
return false
}
return containsHeader(Connection, "upgrade") && containsHeader(Upgrade, "websocket")
}
| {
f := &Forwarder{
httpForwarder: &httpForwarder{log: &internalLogger{Logger: log.StandardLogger()}},
handlerContext: &handlerContext{},
}
for _, s := range setters {
if err := s(f); err != nil {
return nil, err
}
}
if !f.stream {
f.flushInterval = 0
} else if f.flushInterval == 0 {
f.flushInterval = defaultFlushInterval
}
if f.httpForwarder.rewriter == nil {
h, err := os.Hostname()
if err != nil {
h = "localhost"
}
f.httpForwarder.rewriter = &HeaderRewriter{TrustForwardHeader: true, Hostname: h}
}
if f.httpForwarder.roundTripper == nil {
f.httpForwarder.roundTripper = http.DefaultTransport
}
if f.errHandler == nil {
f.errHandler = utils.DefaultHandler
}
if f.tlsClientConfig == nil {
if ht, ok := f.httpForwarder.roundTripper.(*http.Transport); ok {
f.tlsClientConfig = ht.TLSClientConfig
}
}
f.httpForwarder.roundTripper = ErrorHandlingRoundTripper{
RoundTripper: f.httpForwarder.roundTripper,
errorHandler: f.errHandler,
}
f.postConfig()
return f, nil
} |
UserResponseModel.ts | import {IBaseModelOptions} from '../../../src/IBaseModelOptions';
import {InfoModel} from './InfoModel';
import {UserModel} from './UserModel';
import {BaseModel} from '../../../src';
export class UserResponseModel extends BaseModel {
public info: InfoModel = InfoModel as any;
public results: UserModel[] = [UserModel as any];
public resultsAny: any[] = [];
public singleStringToArray: string[] = [];
public nullToArray: any[] = [];
public zeroToArray: number[] = [];
public falseToArray: boolean[] = [];
constructor(data: Partial<UserResponseModel> = {}, opts: IBaseModelOptions = {}) {
super(opts); |
public update(data: Partial<UserResponseModel>): void {
super.update(data);
}
} |
this.update(data);
} |
models.rs | use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::error::Error;
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub struct ChitonDensityMap {
map: Vec<usize>,
width: usize,
height: usize
}
impl ChitonDensityMap {
pub fn parse_string(content: String) -> Result<ChitonDensityMap, Box<dyn Error>> {
let mut density_map = ChitonDensityMap::default();
let lines = content.lines().collect::<Vec<_>>();
density_map.width = lines[0].len();
density_map.height = lines.len();
density_map.map = lines
.iter()
.flat_map(|&line| {
line
.chars()
.map(|c| (c as u8 - '0' as u8) as usize)
}).collect::<Vec<_>>();
Ok(density_map)
}
pub fn shortest_path_score(&self) -> usize {
let mut costs = vec![usize::MAX; self.width * self.height];
costs[0] = 0;
let mut queue = Vec::with_capacity(100);
queue.push((0, 0));
while queue.len() > 0 {
let (x, y) = queue.pop().unwrap();
let current_cost = costs[y * self.width + x];
// Left
if x > 0 {
let target_cost = costs[y * self.width + x - 1];
if target_cost == usize::MAX || current_cost + self.map[y * self.width + x - 1] < target_cost {
costs[y * self.width + x - 1] = current_cost + self.map[y * self.width + x - 1];
queue.push((x - 1, y));
}
}
// Right
if x < self.width - 1 {
let target_cost = costs[y * self.width + x + 1];
if target_cost == usize::MAX || current_cost + self.map[y * self.width + x + 1] < target_cost {
costs[y * self.width + x + 1] = current_cost + self.map[y * self.width + x + 1];
queue.push((x + 1, y));
}
}
// Top
if y > 0 {
let target_cost = costs[(y - 1) * self.width + x];
if target_cost == usize::MAX || current_cost + self.map[(y - 1) * self.width + x] < target_cost {
costs[(y - 1) * self.width + x] = current_cost + self.map[(y - 1) * self.width + x];
queue.push((x, y - 1));
}
}
// Bottom
if y < self.height - 1 {
let target_cost = costs[(y + 1) * self.width + x];
if target_cost == usize::MAX || current_cost + self.map[(y + 1) * self.width + x] < target_cost {
costs[(y + 1) * self.width + x] = current_cost + self.map[(y + 1) * self.width + x];
queue.push((x, y + 1));
}
}
}
costs[costs.len() - 1]
}
pub fn shortest_path_score_5x(&self) -> usize {
let mut costs = vec![usize::MAX; (5 * self.width) * (5 * self.height)];
costs[0] = 0;
let mut queue = BinaryHeap::new();
queue.push(State {
x: 0,
y: 0,
cost: 0
});
while queue.len() > 0 {
let state = queue.pop().unwrap();
let x = state.x;
let y = state.y;
let current_cost = costs[y * 5 * self.width + x];
if x == 5 * self.width - 1 && y == 5 * self.height - 1 {
break;
}
// Left
if x > 0 {
let target_cost = costs[y * 5 * self.width + x - 1];
let cell_cost = self.get_5x_cost(x - 1, y);
if target_cost == usize::MAX || current_cost + cell_cost < target_cost {
costs[y * 5 * self.width + x - 1] = current_cost + cell_cost;
queue.push(State {
x: x - 1,
y: y,
cost: current_cost + cell_cost
});
}
}
// Right
if x < 5 * self.width - 1 {
let target_cost = costs[y * 5 * self.width + x + 1];
let cell_cost = self.get_5x_cost(x + 1, y);
if target_cost == usize::MAX || current_cost + cell_cost < target_cost {
costs[y * 5 * self.width + x + 1] = current_cost + cell_cost;
queue.push(State {
x: x + 1,
y: y,
cost: current_cost + cell_cost
});
}
}
// Top
if y > 0 {
let target_cost = costs[(y - 1) * 5 * self.width + x];
let cell_cost = self.get_5x_cost(x, y - 1);
if target_cost == usize::MAX || current_cost + cell_cost < target_cost {
costs[(y - 1) * 5 * self.width + x] = current_cost + cell_cost;
queue.push(State {
x: x,
y: y - 1,
cost: current_cost + cell_cost
});
}
}
// Bottom
if y < 5 * self.height - 1 {
let target_cost = costs[(y + 1) * 5 * self.width + x];
let cell_cost = self.get_5x_cost(x, y + 1);
if target_cost == usize::MAX || current_cost + cell_cost < target_cost {
costs[(y + 1) * 5 * self.width + x] = current_cost + cell_cost;
queue.push(State {
x: x,
y: y + 1,
cost: current_cost + cell_cost
});
}
}
}
costs[costs.len() - 1]
}
fn get_5x_cost(&self, x: usize, y: usize) -> usize {
let (xq, xm) = (x / self.width, x % self.width);
let (yq, ym) = (y / self.height, y % self.height);
let cost = self.map[ym * self.width + xm] + xq + yq;
if cost > 9 {
cost % 10 + 1
}
else {
cost
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
struct State {
x: usize,
y: usize,
cost: usize,
}
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
.then_with(|| self.y.cmp(&other.y))
.then_with(|| self.x.cmp(&other.x))
}
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(test)]
mod tests {
use crate::ChitonDensityMap;
| 1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
"
.to_string();
let input = ChitonDensityMap::parse_string(content).unwrap();
assert_eq!(input, ChitonDensityMap {
map: vec![
1,1,6,3,7,5,1,7,4,2,
1,3,8,1,3,7,3,6,7,2,
2,1,3,6,5,1,1,3,2,8,
3,6,9,4,9,3,1,5,6,9,
7,4,6,3,4,1,7,1,1,1,
1,3,1,9,1,2,8,1,3,7,
1,3,5,9,9,1,2,4,2,1,
3,1,2,5,4,2,1,6,3,9,
1,2,9,3,1,3,8,5,2,1,
2,3,1,1,9,4,4,5,8,1,
],
width: 10,
height: 10
});
}
#[test]
fn part_1_example_case() {
let input = ChitonDensityMap {
map: vec![
1,1,6,3,7,5,1,7,4,2,
1,3,8,1,3,7,3,6,7,2,
2,1,3,6,5,1,1,3,2,8,
3,6,9,4,9,3,1,5,6,9,
7,4,6,3,4,1,7,1,1,1,
1,3,1,9,1,2,8,1,3,7,
1,3,5,9,9,1,2,4,2,1,
3,1,2,5,4,2,1,6,3,9,
1,2,9,3,1,3,8,5,2,1,
2,3,1,1,9,4,4,5,8,1,
],
width: 10,
height: 10
};
assert_eq!(input.shortest_path_score(), 40);
}
#[test]
fn part_2_example_case() {
let input = ChitonDensityMap {
map: vec![
1,1,6,3,7,5,1,7,4,2,
1,3,8,1,3,7,3,6,7,2,
2,1,3,6,5,1,1,3,2,8,
3,6,9,4,9,3,1,5,6,9,
7,4,6,3,4,1,7,1,1,1,
1,3,1,9,1,2,8,1,3,7,
1,3,5,9,9,1,2,4,2,1,
3,1,2,5,4,2,1,6,3,9,
1,2,9,3,1,3,8,5,2,1,
2,3,1,1,9,4,4,5,8,1,
],
width: 10,
height: 10
};
assert_eq!(input.shortest_path_score_5x(), 315);
}
} | #[test]
fn parse_example_case() {
let content = "1163751742 |
requests_test.go | package testing
import (
"fmt"
"net/http"
"testing"
"github.com/gophercloud/gophercloud"
fake "github.com/gophercloud/gophercloud/openstack/networking/v2/common"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas/monitors"
"github.com/gophercloud/gophercloud/pagination"
th "github.com/gophercloud/gophercloud/testhelper"
)
func TestList(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/lb/health_monitors", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
{
"health_monitors":[
{
"admin_state_up":true,
"tenant_id":"83657cfcdfe44cd5920adaf26c48ceea",
"delay":10,
"max_retries":1,
"timeout":1,
"type":"PING",
"id":"466c8345-28d8-4f84-a246-e04380b0461d"
},
{
"admin_state_up":true,
"tenant_id":"83657cfcdfe44cd5920adaf26c48ceea",
"delay":5,
"expected_codes":"200",
"max_retries":2,
"http_method":"GET",
"timeout":2,
"url_path":"/",
"type":"HTTP",
"id":"5d4b5228-33b0-4e60-b225-9b727c1a20e7"
}
]
}
`)
})
count := 0
monitors.List(fake.ServiceClient(), monitors.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
count++
actual, err := monitors.ExtractMonitors(page)
if err != nil {
t.Errorf("Failed to extract monitors: %v", err)
return false, err
}
expected := []monitors.Monitor{
{
AdminStateUp: true,
TenantID: "83657cfcdfe44cd5920adaf26c48ceea",
Delay: 10,
MaxRetries: 1,
Timeout: 1,
Type: "PING",
ID: "466c8345-28d8-4f84-a246-e04380b0461d",
},
{
AdminStateUp: true,
TenantID: "83657cfcdfe44cd5920adaf26c48ceea",
Delay: 5,
ExpectedCodes: "200",
MaxRetries: 2,
Timeout: 2,
URLPath: "/",
Type: "HTTP",
HTTPMethod: "GET",
ID: "5d4b5228-33b0-4e60-b225-9b727c1a20e7",
},
}
th.CheckDeepEquals(t, expected, actual)
return true, nil
})
if count != 1 {
t.Errorf("Expected 1 page, got %d", count)
}
}
func TestDelayMustBeGreaterOrEqualThanTimeout(t *testing.T) {
_, err := monitors.Create(fake.ServiceClient(), monitors.CreateOpts{
Type: "HTTP",
Delay: 1,
Timeout: 10,
MaxRetries: 5,
URLPath: "/check",
ExpectedCodes: "200-299",
}).Extract()
if err == nil {
t.Fatalf("Expected error, got none")
}
_, err = monitors.Update(fake.ServiceClient(), "453105b9-1754-413f-aab1-55f1af620750", monitors.UpdateOpts{
Delay: 1,
Timeout: 10,
}).Extract()
if err == nil {
t.Fatalf("Expected error, got none")
}
}
func TestCreate(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/lb/health_monitors", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "POST")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
th.TestHeader(t, r, "Content-Type", "application/json")
th.TestHeader(t, r, "Accept", "application/json")
th.TestJSONRequest(t, r, `
{
"health_monitor":{
"type":"HTTP",
"tenant_id":"453105b9-1754-413f-aab1-55f1af620750",
"delay":20,
"timeout":10,
"max_retries":5,
"url_path":"/check",
"expected_codes":"200-299"
}
}
`)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `
{
"health_monitor":{
"id":"f3eeab00-8367-4524-b662-55e64d4cacb5",
"tenant_id":"453105b9-1754-413f-aab1-55f1af620750",
"type":"HTTP",
"delay":20,
"timeout":10,
"max_retries":5,
"http_method":"GET",
"url_path":"/check",
"expected_codes":"200-299",
"admin_state_up":true,
"status":"ACTIVE"
}
}
`)
})
_, err := monitors.Create(fake.ServiceClient(), monitors.CreateOpts{
Type: "HTTP",
TenantID: "453105b9-1754-413f-aab1-55f1af620750",
Delay: 20,
Timeout: 10,
MaxRetries: 5,
URLPath: "/check",
ExpectedCodes: "200-299",
}).Extract()
th.AssertNoErr(t, err)
}
func TestRequiredCreateOpts(t *testing.T) {
res := monitors.Create(fake.ServiceClient(), monitors.CreateOpts{})
if res.Err == nil {
t.Fatalf("Expected error, got none")
}
res = monitors.Create(fake.ServiceClient(), monitors.CreateOpts{Type: monitors.TypeHTTP})
if res.Err == nil {
t.Fatalf("Expected error, got none")
}
}
func TestGet(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/lb/health_monitors/f3eeab00-8367-4524-b662-55e64d4cacb5", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "GET")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
{
"health_monitor":{
"id":"f3eeab00-8367-4524-b662-55e64d4cacb5",
"tenant_id":"453105b9-1754-413f-aab1-55f1af620750",
"type":"HTTP",
"delay":20,
"timeout":10,
"max_retries":5,
"http_method":"GET",
"url_path":"/check",
"expected_codes":"200-299",
"admin_state_up":true,
"status":"ACTIVE"
}
}
`)
})
hm, err := monitors.Get(fake.ServiceClient(), "f3eeab00-8367-4524-b662-55e64d4cacb5").Extract()
th.AssertNoErr(t, err)
th.AssertEquals(t, "f3eeab00-8367-4524-b662-55e64d4cacb5", hm.ID)
th.AssertEquals(t, "453105b9-1754-413f-aab1-55f1af620750", hm.TenantID)
th.AssertEquals(t, "HTTP", hm.Type)
th.AssertEquals(t, 20, hm.Delay)
th.AssertEquals(t, 10, hm.Timeout)
th.AssertEquals(t, 5, hm.MaxRetries)
th.AssertEquals(t, "GET", hm.HTTPMethod)
th.AssertEquals(t, "/check", hm.URLPath)
th.AssertEquals(t, "200-299", hm.ExpectedCodes)
th.AssertEquals(t, true, hm.AdminStateUp)
th.AssertEquals(t, "ACTIVE", hm.Status)
}
func TestUpdate(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/lb/health_monitors/b05e44b5-81f9-4551-b474-711a722698f7", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "PUT")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
th.TestHeader(t, r, "Content-Type", "application/json")
th.TestHeader(t, r, "Accept", "application/json")
th.TestJSONRequest(t, r, `
{
"health_monitor":{
"delay": 30,
"timeout": 20,
"max_retries": 10,
"url_path": "/another_check",
"expected_codes": "301",
"admin_state_up": true
}
}
`)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, `
{
"health_monitor": {
"admin_state_up": true,
"tenant_id": "4fd44f30292945e481c7b8a0c8908869",
"delay": 30,
"max_retries": 10,
"http_method": "GET",
"timeout": 20,
"pools": [
{
"status": "PENDING_CREATE",
"status_description": null,
"pool_id": "6e55751f-6ad4-4e53-b8d4-02e442cd21df"
}
],
"type": "PING",
"id": "b05e44b5-81f9-4551-b474-711a722698f7"
}
}
`)
})
_, err := monitors.Update(fake.ServiceClient(), "b05e44b5-81f9-4551-b474-711a722698f7", monitors.UpdateOpts{
Delay: 30,
Timeout: 20,
MaxRetries: 10,
URLPath: "/another_check",
ExpectedCodes: "301",
AdminStateUp: gophercloud.Enabled,
}).Extract()
th.AssertNoErr(t, err)
}
func | (t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/v2.0/lb/health_monitors/b05e44b5-81f9-4551-b474-711a722698f7", func(w http.ResponseWriter, r *http.Request) {
th.TestMethod(t, r, "DELETE")
th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
w.WriteHeader(http.StatusNoContent)
})
res := monitors.Delete(fake.ServiceClient(), "b05e44b5-81f9-4551-b474-711a722698f7")
th.AssertNoErr(t, res.Err)
}
| TestDelete |
_4_2_textures_combined.rs | #![allow(non_upper_case_globals)]
extern crate glfw;
use self::glfw::{Context, Key, Action};
extern crate gl;
use self::gl::types::*;
use std::sync::mpsc::Receiver;
use std::ptr;
use std::mem;
use std::os::raw::c_void;
use std::path::Path;
use std::ffi::CStr;
use shader::Shader;
use image;
use image::GenericImage;
use image::GenericImageView;
// settings
const SCR_WIDTH: u32 = 800;
const SCR_HEIGHT: u32 = 600;
#[allow(non_snake_case)]
pub fn main_1_4_2() |
fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) {
for (_, event) in glfw::flush_messages(events) {
match event {
glfw::WindowEvent::FramebufferSize(width, height) => {
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
unsafe { gl::Viewport(0, 0, width, height) }
}
glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => window.set_should_close(true),
_ => {}
}
}
}
| {
// glfw: initialize and configure
// ------------------------------
let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3));
glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
#[cfg(target_os = "macos")]
glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
// glfw window creation
// --------------------
let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed)
.expect("Failed to create GLFW window");
window.make_current();
window.set_key_polling(true);
window.set_framebuffer_size_polling(true);
// gl: load all OpenGL function pointers
// ---------------------------------------
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
let (ourShader, VBO, VAO, EBO, texture1, texture2) = unsafe {
// build and compile our shader program
// ------------------------------------
let ourShader = Shader::new(
"src/_1_getting_started/shaders/4.2.texture.vs",
"src/_1_getting_started/shaders/4.2.texture.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
// HINT: type annotation is crucial since default for float literals is f64
let vertices: [f32; 32] = [
// positions // colors // texture coords
0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
-0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 // top left
];
let indices = [
0, 1, 3, // first Triangle
1, 2, 3 // second Triangle
];
let (mut VBO, mut VAO, mut EBO) = (0, 0, 0);
gl::GenVertexArrays(1, &mut VAO);
gl::GenBuffers(1, &mut VBO);
gl::GenBuffers(1, &mut EBO);
gl::BindVertexArray(VAO);
gl::BindBuffer(gl::ARRAY_BUFFER, VBO);
gl::BufferData(gl::ARRAY_BUFFER,
(vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,
&vertices[0] as *const f32 as *const c_void,
gl::STATIC_DRAW);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, EBO);
gl::BufferData(gl::ELEMENT_ARRAY_BUFFER,
(indices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,
&indices[0] as *const i32 as *const c_void,
gl::STATIC_DRAW);
let stride = 8 * mem::size_of::<GLfloat>() as GLsizei;
// position attribute
gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null());
gl::EnableVertexAttribArray(0);
// color attribute
gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void);
gl::EnableVertexAttribArray(1);
// texture coord attribute
gl::VertexAttribPointer(2, 2, gl::FLOAT, gl::FALSE, stride, (6 * mem::size_of::<GLfloat>()) as *const c_void);
gl::EnableVertexAttribArray(2);
// load and create a texture
// -------------------------
let (mut texture1, mut texture2) = (0, 0);
// texture 1
// ---------
gl::GenTextures(1, &mut texture1);
gl::BindTexture(gl::TEXTURE_2D, texture1);
// set the texture wrapping parameters
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method)
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
// set texture filtering parameters
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
// load image, create texture and generate mipmaps
let img = image::open(&Path::new("resources/textures/container.jpg")).expect("Failed to load texture");
let data = img.raw_pixels();
gl::TexImage2D(gl::TEXTURE_2D,
0,
gl::RGB as i32,
img.width() as i32,
img.height() as i32,
0,
gl::RGB,
gl::UNSIGNED_BYTE,
&data[0] as *const u8 as *const c_void);
gl::GenerateMipmap(gl::TEXTURE_2D);
// texture 2
// ---------
gl::GenTextures(1, &mut texture2);
gl::BindTexture(gl::TEXTURE_2D, texture2);
// set the texture wrapping parameters
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); // set texture wrapping to gl::REPEAT (default wrapping method)
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32);
// set texture filtering parameters
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
// load image, create texture and generate mipmaps
let img = image::open(&Path::new("resources/textures/awesomeface.png")).expect("Failed to load texture");
let img = img.flipv(); // flip loaded texture on the y-axis.
let data = img.raw_pixels();
// note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
gl::TexImage2D(gl::TEXTURE_2D,
0,
gl::RGB as i32,
img.width() as i32,
img.height() as i32,
0,
gl::RGBA,
gl::UNSIGNED_BYTE,
&data[0] as *const u8 as *const c_void);
gl::GenerateMipmap(gl::TEXTURE_2D);
// tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
// -------------------------------------------------------------------------------------------
ourShader.useProgram(); // don't forget to activate/use the shader before setting uniforms!
// either set it manually like so:
gl::Uniform1i(gl::GetUniformLocation(ourShader.ID, c_str!("texture1").as_ptr()), 0); // using c_str! macro to avoid runtime overhead
// or set it via the texture class
ourShader.setInt(c_str!("texture2"), 1);
(ourShader, VBO, VAO, EBO, texture1, texture2)
};
// render loop
// -----------
while !window.should_close() {
// events
// -----
process_events(&mut window, &events);
// render
// ------
unsafe {
gl::ClearColor(0.2, 0.3, 0.3, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT);
// bind textures on corresponding texture units
gl::ActiveTexture(gl::TEXTURE0);
gl::BindTexture(gl::TEXTURE_2D, texture1);
gl::ActiveTexture(gl::TEXTURE1);
gl::BindTexture(gl::TEXTURE_2D, texture2);
// render container
ourShader.useProgram();
gl::BindVertexArray(VAO);
gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null());
}
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
window.swap_buffers();
glfw.poll_events();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
unsafe {
gl::DeleteVertexArrays(1, &VAO);
gl::DeleteBuffers(1, &VBO);
gl::DeleteBuffers(1, &EBO);
}
} |
pubg.py | from datetime import datetime, timedelta
class Pubg(object):
| def __init__(self):
self.top_history = []
def _last_top(self, players=None):
if not players:
if self.top_history:
return self.top_history[-1]
else:
return None
for top in self.top_history:
print(top['players'] == players)
if top['players'] == players:
return top
def get_last(self, players=None):
now = datetime.now()
if players:
top = self._last_top(players)
else:
top = self._last_top()
if top:
msg = 'Last top for team ' + ' '.join(top['players'].split(',')) + ' was ' + str(now - top['time']) + ' ago'
else:
msg = 'No last top'
if players:
msg += ' for this team'
self._remove_old()
return msg
def new_top(self, players):
top = {
'time': datetime.now(),
'players': players
}
self.top_history.append(top)
print(self.top_history)
self._remove_old()
def _remove_old(self):
now = datetime.now()
for top in self.top_history:
if top['time'] < now - timedelta(days=30):
self.top_history.remove(top) |
|
main.go | package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/theghostwhocodes/mocker-go/internal/handlers"
"golang.org/x/sys/unix"
)
var version string
var showVersion bool
var dataPath string
var port int
var host string
var proxyFor string
func init() {
const (
dataPathDefault = "./data"
dataPathHelpText = "The data path"
portDefault = 8000
portHelpText = "The TCP port to listen"
hostDefault = "127.0.0.1"
hostHelpText = "The host to listen"
proxyForDefault = ""
proxyForHelpText = "The real API endpoint"
)
flag.BoolVar(&showVersion, "version", false, "Mocker version")
flag.StringVar(&dataPath, "d", dataPathDefault, dataPathHelpText+" (shorthand)")
flag.StringVar(&dataPath, "data", dataPathDefault, dataPathHelpText)
flag.IntVar(&port, "p", portDefault, portHelpText+" (shorthand)")
flag.IntVar(&port, "port", portDefault, portHelpText)
flag.StringVar(&host, "h", hostDefault, hostHelpText+" (shorthand)")
flag.StringVar(&host, "host", hostDefault, hostHelpText)
flag.StringVar(&proxyFor, "pf", proxyForDefault, proxyForHelpText+" (shorthand)")
flag.StringVar(&proxyFor, "proxy-for", proxyForDefault, proxyForHelpText)
}
func cleanup() {
fmt.Printf("Exiting mocker...\n")
}
func main() {
flag.Parse()
if showVersion {
fmt.Printf("Mocker version %s", version)
return
}
basePath, _ := filepath.Abs(dataPath) | err := unix.Access(basePath, unix.R_OK+unix.W_OK)
if err != nil {
log.Printf("I can't access your data folder, please check folder permissions")
os.Exit(1)
}
http.HandleFunc("/", handlers.HandlerFactory(basePath, proxyFor))
log.Printf("Loading data from %s", basePath)
log.Printf("Mocker listening on %s:%d...", host, port)
if proxyFor != "" {
log.Printf("Mocker acting as a proxy for %s...", proxyFor)
}
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
cleanup()
os.Exit(1)
}()
address := fmt.Sprintf("%s:%d", host, port)
log.Fatal(http.ListenAndServe(address, nil))
} | |
exportData.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import os from 'os';
import path from 'path';
import electron from 'electron';
import {getInstance as getLogger} from '../fb-stubs/Logger';
import {Store, State as ReduxState, MiddlewareAPI} from '../reducers';
import {DeviceExport} from '../devices/BaseDevice';
import {State as PluginStatesState} from '../reducers/pluginStates';
import {State as PluginsState} from '../reducers/plugins';
import {PluginNotification} from '../reducers/notifications';
import Client, {ClientExport, ClientQuery} from '../Client';
import {getAppVersion} from './info';
import {pluginKey} from '../reducers/pluginStates';
import {
callClient,
supportsMethod,
PluginDefinition,
DevicePluginMap,
ClientPluginMap,
isSandyPlugin,
} from '../plugin';
import {default as BaseDevice} from '../devices/BaseDevice';
import {default as ArchivedDevice} from '../devices/ArchivedDevice';
import fs from 'fs';
import {v4 as uuidv4} from 'uuid';
import {remote, OpenDialogOptions} from 'electron';
import {readCurrentRevision} from './packageMetadata';
import {tryCatchReportPlatformFailures} from './metrics';
import {promisify} from 'util';
import promiseTimeout from './promiseTimeout';
import {TestIdler} from './Idler';
import {setStaticView} from '../reducers/connections';
import {
resetSupportFormV2State,
SupportFormRequestDetailsState,
} from '../reducers/supportForm';
import {setSelectPluginsToExportActiveSheet} from '../reducers/application';
import {deconstructClientId, deconstructPluginKey} from '../utils/clientUtils';
import {performance} from 'perf_hooks';
import {processMessageQueue} from './messageQueue';
import {getPluginTitle} from './pluginUtils';
import {capture} from './screenshot';
import {uploadFlipperMedia} from '../fb-stubs/user';
import {Idler} from 'flipper-plugin';
import {deserializeObject, makeObjectSerializable} from './serialization';
export const IMPORT_FLIPPER_TRACE_EVENT = 'import-flipper-trace';
export const EXPORT_FLIPPER_TRACE_EVENT = 'export-flipper-trace';
export const EXPORT_FLIPPER_TRACE_TIME_SERIALIZATION_EVENT = `${EXPORT_FLIPPER_TRACE_EVENT}:serialization`;
// maps clientId -> pluginId -> persistence key -> state
export type SandyPluginStates = Record<
string,
Record<string, Record<string, any>>
>;
export type PluginStatesExportState = {
[pluginKey: string]: string;
};
export type ExportType = {
fileVersion: string;
flipperReleaseRevision: string | undefined;
clients: Array<ClientExport>;
device: DeviceExport | null;
deviceScreenshot: string | null;
store: {
pluginStates: PluginStatesExportState;
activeNotifications: Array<PluginNotification>;
};
pluginStates2: SandyPluginStates;
supportRequestDetails?: SupportFormRequestDetailsState;
};
type ProcessPluginStatesOptions = {
clients: Array<ClientExport>;
serial: string;
allPluginStates: PluginStatesState;
devicePlugins: DevicePluginMap;
selectedPlugins: Array<string>;
statusUpdate?: (msg: string) => void;
};
type ProcessNotificationStatesOptions = {
clients: Array<ClientExport>;
serial: string;
allActiveNotifications: Array<PluginNotification>;
devicePlugins: DevicePluginMap;
statusUpdate?: (msg: string) => void;
};
type PluginsToProcess = {
pluginKey: string;
pluginId: string;
pluginName: string;
pluginClass: PluginDefinition;
client: Client;
}[];
type AddSaltToDeviceSerialOptions = {
salt: string;
device: BaseDevice;
deviceScreenshot: string | null;
clients: Array<ClientExport>;
pluginStates: PluginStatesExportState;
pluginStates2: SandyPluginStates;
devicePluginStates: Record<string, any>;
pluginNotification: Array<PluginNotification>;
selectedPlugins: Array<string>;
statusUpdate: (msg: string) => void;
idler: Idler;
};
export function displayFetchMetadataErrors(
fetchMetaDataErrors: {
[plugin: string]: Error;
} | null,
): {title: string; errorArray: Array<Error>} {
const errors = fetchMetaDataErrors ? Object.values(fetchMetaDataErrors) : [];
const pluginsWithFetchMetadataErrors = fetchMetaDataErrors
? Object.keys(fetchMetaDataErrors)
: [];
const title =
fetchMetaDataErrors && pluginsWithFetchMetadataErrors.length > 0
? `Export was successfull, but plugin${
pluginsWithFetchMetadataErrors.length > 1 ? 's' : ''
} ${pluginsWithFetchMetadataErrors.join(
', ',
)} might be ignored because of the following errors.`
: '';
return {title, errorArray: errors};
}
export function processClients(
clients: Array<ClientExport>,
serial: string,
statusUpdate?: (msg: string) => void,
): Array<ClientExport> {
statusUpdate &&
statusUpdate(`Filtering Clients for the device id ${serial}...`);
const filteredClients = clients.filter(
(client) => client.query.device_id === serial,
);
return filteredClients;
}
export function processPluginStates(
options: ProcessPluginStatesOptions,
): PluginStatesState {
const {
clients,
serial,
allPluginStates,
devicePlugins,
selectedPlugins,
statusUpdate,
} = options;
let pluginStates: PluginStatesState = {};
statusUpdate &&
statusUpdate('Filtering the plugin states for the filtered Clients...');
for (const key in allPluginStates) {
const plugin = deconstructPluginKey(key);
const pluginName = plugin.pluginName;
if (
pluginName &&
selectedPlugins.length > 0 &&
!selectedPlugins.includes(pluginName)
) {
continue;
}
if (plugin.type === 'client') {
if (!clients.some((c) => c.id.includes(plugin.client))) {
continue;
}
}
if (plugin.type === 'device') {
if (
!pluginName ||
!devicePlugins.has(pluginName) ||
serial !== plugin.client
) {
continue;
}
}
pluginStates = {...pluginStates, [key]: allPluginStates[key]};
}
return pluginStates;
}
export function processNotificationStates(
options: ProcessNotificationStatesOptions,
): Array<PluginNotification> {
const {
clients,
serial,
allActiveNotifications,
devicePlugins,
statusUpdate,
} = options;
statusUpdate &&
statusUpdate('Filtering the notifications for the filtered Clients...');
const activeNotifications = allActiveNotifications.filter((notif) => {
const filteredClients = clients.filter((client) =>
notif.client ? client.id.includes(notif.client) : false,
);
return (
filteredClients.length > 0 ||
(devicePlugins.has(notif.pluginId) && serial === notif.client)
); // There need not be any client for device Plugins
});
return activeNotifications;
}
const serializePluginStates = async (
pluginStates: PluginStatesState,
clientPlugins: ClientPluginMap,
devicePlugins: DevicePluginMap,
statusUpdate?: (msg: string) => void,
idler?: Idler,
): Promise<PluginStatesExportState> => {
const pluginsMap = new Map<string, PluginDefinition>([
...clientPlugins.entries(),
...devicePlugins.entries(),
]);
const pluginExportState: PluginStatesExportState = {};
for (const key in pluginStates) {
const pluginName = deconstructPluginKey(key).pluginName;
statusUpdate && statusUpdate(`Serialising ${pluginName}...`);
const serializationMarker = `${EXPORT_FLIPPER_TRACE_EVENT}:serialization-per-plugin`;
performance.mark(serializationMarker);
const pluginClass = pluginName ? pluginsMap.get(pluginName) : null;
if (isSandyPlugin(pluginClass)) {
continue; // Those are already processed by `exportSandyPluginStates`
} else if (pluginClass) {
pluginExportState[key] = await pluginClass.serializePersistedState(
pluginStates[key],
statusUpdate,
idler,
pluginName,
);
getLogger().trackTimeSince(serializationMarker, serializationMarker, {
plugin: pluginName,
});
}
}
return pluginExportState;
};
async function exportSandyPluginStates(
pluginsToProcess: PluginsToProcess,
idler: Idler,
statusUpdate: (msg: string) => void,
): Promise<SandyPluginStates> {
const res: SandyPluginStates = {};
for (const key in pluginsToProcess) {
const {pluginId, client, pluginClass} = pluginsToProcess[key];
if (isSandyPlugin(pluginClass) && client.sandyPluginStates.has(pluginId)) {
if (!res[client.id]) {
res[client.id] = {};
}
res[client.id][pluginId] = await makeObjectSerializable(
await client.sandyPluginStates
.get(pluginId)!
.exportState(idler, statusUpdate),
idler,
statusUpdate,
'Serializing plugin: ' + pluginId,
);
}
}
return res;
}
const deserializePluginStates = (
pluginStatesExportState: PluginStatesExportState,
clientPlugins: ClientPluginMap,
devicePlugins: DevicePluginMap,
): PluginStatesState => {
const pluginsMap = new Map<string, PluginDefinition>([
...clientPlugins.entries(),
...devicePlugins.entries(),
]);
const pluginsState: PluginStatesState = {};
for (const key in pluginStatesExportState) {
const pluginName = deconstructPluginKey(key).pluginName;
if (!pluginName || !pluginsMap.get(pluginName)) {
continue;
}
const pluginClass = pluginsMap.get(pluginName);
if (isSandyPlugin(pluginClass)) {
pluginsState[key] = pluginStatesExportState[key];
} else if (pluginClass) {
pluginsState[key] = pluginClass.deserializePersistedState(
pluginStatesExportState[key],
);
}
}
return pluginsState;
};
function replaceSerialsInKeys<T extends Record<string, any>>(
collection: T,
baseSerial: string,
newSerial: string,
): T {
const result: Record<string, any> = {};
for (const key in collection) {
if (!key.includes(baseSerial)) { | }
result[key.replace(baseSerial, newSerial)] = collection[key];
}
return result as T;
}
async function addSaltToDeviceSerial({
salt,
device,
deviceScreenshot,
clients,
pluginStates,
pluginNotification,
statusUpdate,
pluginStates2,
devicePluginStates,
}: AddSaltToDeviceSerialOptions): Promise<ExportType> {
const {serial} = device;
const newSerial = salt + '-' + serial;
const newDevice = new ArchivedDevice({
serial: newSerial,
deviceType: device.deviceType,
title: device.title,
os: device.os,
screenshotHandle: deviceScreenshot,
});
statusUpdate &&
statusUpdate('Adding salt to the selected device id in the client data...');
const updatedClients = clients.map((client: ClientExport) => {
return {
...client,
id: client.id.replace(serial, newSerial),
query: {...client.query, device_id: newSerial},
};
});
statusUpdate &&
statusUpdate(
'Adding salt to the selected device id in the plugin states...',
);
const updatedPluginStates = replaceSerialsInKeys(
pluginStates,
serial,
newSerial,
);
const updatedPluginStates2 = replaceSerialsInKeys(
pluginStates2,
serial,
newSerial,
);
statusUpdate &&
statusUpdate(
'Adding salt to the selected device id in the notification data...',
);
const updatedPluginNotifications = pluginNotification.map((notif) => {
if (!notif.client || !notif.client.includes(serial)) {
throw new Error(
`Error while exporting, plugin state (${notif.pluginId}) does not have ${serial} in it`,
);
}
return {...notif, client: notif.client.replace(serial, newSerial)};
});
const revision: string | undefined = await readCurrentRevision();
return {
fileVersion: getAppVersion() || 'unknown',
flipperReleaseRevision: revision,
clients: updatedClients,
device: {...newDevice.toJSON(), pluginStates: devicePluginStates},
deviceScreenshot: deviceScreenshot,
store: {
pluginStates: updatedPluginStates,
activeNotifications: updatedPluginNotifications,
},
pluginStates2: updatedPluginStates2,
};
}
type ProcessStoreOptions = {
activeNotifications: Array<PluginNotification>;
device: BaseDevice | null;
pluginStates: PluginStatesState;
pluginStates2: SandyPluginStates;
clients: Array<ClientExport>;
devicePlugins: DevicePluginMap;
clientPlugins: ClientPluginMap;
salt: string;
selectedPlugins: Array<string>;
statusUpdate?: (msg: string) => void;
};
export async function processStore(
{
activeNotifications,
device,
pluginStates,
pluginStates2,
clients,
devicePlugins,
clientPlugins,
salt,
selectedPlugins,
statusUpdate,
}: ProcessStoreOptions,
idler: Idler = new TestIdler(true),
): Promise<ExportType> {
if (device) {
const {serial} = device;
if (!statusUpdate) {
statusUpdate = () => {};
}
statusUpdate('Capturing screenshot...');
const deviceScreenshot = device.connected.get()
? await capture(device).catch((e) => {
console.warn(
'Failed to capture device screenshot when exporting. ' + e,
);
return null;
})
: null;
const processedClients = processClients(clients, serial, statusUpdate);
const processedPluginStates = processPluginStates({
clients: processedClients,
serial,
allPluginStates: pluginStates,
devicePlugins,
selectedPlugins,
statusUpdate,
});
const processedActiveNotifications = processNotificationStates({
clients: processedClients,
serial,
allActiveNotifications: activeNotifications,
devicePlugins,
statusUpdate,
});
const exportPluginState = await serializePluginStates(
processedPluginStates,
clientPlugins,
devicePlugins,
statusUpdate,
idler,
);
const devicePluginStates = await makeObjectSerializable(
await device.exportState(idler, statusUpdate, selectedPlugins),
idler,
statusUpdate,
'Serializing device plugins',
);
statusUpdate('Uploading screenshot...');
const deviceScreenshotLink =
deviceScreenshot &&
(await uploadFlipperMedia(deviceScreenshot, 'Image').catch((e) => {
console.warn('Failed to upload device screenshot when exporting. ' + e);
return null;
}));
// Adding salt to the device id, so that the device_id in the device list is unique.
const exportFlipperData = await addSaltToDeviceSerial({
salt,
device,
deviceScreenshot: deviceScreenshotLink,
clients: processedClients,
pluginStates: exportPluginState,
pluginNotification: processedActiveNotifications,
statusUpdate,
selectedPlugins,
pluginStates2,
devicePluginStates,
idler,
});
return exportFlipperData;
}
throw new Error('Selected device is null, please select a device');
}
export async function fetchMetadata(
pluginsToProcess: PluginsToProcess,
pluginStates: PluginStatesState,
state: ReduxState,
statusUpdate: (msg: string) => void,
idler: Idler,
): Promise<{
pluginStates: PluginStatesState;
errors: {[plugin: string]: Error} | null;
}> {
const newPluginState = {...pluginStates};
let errorObject: {[plugin: string]: Error} | null = null;
for (const {
pluginName,
pluginId,
pluginClass,
client,
pluginKey,
} of pluginsToProcess) {
const exportState =
pluginClass && !isSandyPlugin(pluginClass)
? pluginClass.exportPersistedState
: null;
if (exportState) {
const fetchMetaDataMarker = `${EXPORT_FLIPPER_TRACE_EVENT}:fetch-meta-data-per-plugin`;
const isConnected = client.connected.get();
performance.mark(fetchMetaDataMarker);
try {
statusUpdate &&
statusUpdate(`Fetching metadata for plugin ${pluginName}...`);
const data = await promiseTimeout(
240000, // Fetching MobileConfig data takes ~ 3 mins, thus keeping timeout at 4 mins.
exportState(
isConnected ? callClient(client, pluginId) : undefined,
newPluginState[pluginKey],
state,
idler,
statusUpdate,
isConnected
? supportsMethod(client, pluginId)
: () => Promise.resolve(false),
),
`Timed out while collecting data for ${pluginName}`,
);
if (!data) {
throw new Error(
`Metadata returned by the ${pluginName} is undefined`,
);
}
getLogger().trackTimeSince(fetchMetaDataMarker, fetchMetaDataMarker, {
pluginId,
});
newPluginState[pluginKey] = data;
} catch (e) {
if (!errorObject) {
errorObject = {};
}
errorObject[pluginName] = e;
getLogger().trackTimeSince(fetchMetaDataMarker, fetchMetaDataMarker, {
pluginId,
error: e,
});
continue;
}
}
}
return {pluginStates: newPluginState, errors: errorObject};
}
async function processQueues(
store: MiddlewareAPI,
pluginsToProcess: PluginsToProcess,
statusUpdate?: (msg: string) => void,
idler?: Idler,
) {
for (const {
pluginName,
pluginId,
pluginKey,
pluginClass,
client,
} of pluginsToProcess) {
if (isSandyPlugin(pluginClass) || pluginClass.persistedStateReducer) {
client.flushMessageBuffer();
const processQueueMarker = `${EXPORT_FLIPPER_TRACE_EVENT}:process-queue-per-plugin`;
performance.mark(processQueueMarker);
const plugin = isSandyPlugin(pluginClass)
? client.sandyPluginStates.get(pluginId)
: pluginClass;
if (!plugin) continue;
await processMessageQueue(
plugin,
pluginKey,
store,
({current, total}) => {
statusUpdate?.(
`Processing event ${current} / ${total} (${Math.round(
(current / total) * 100,
)}%) for plugin ${pluginName}`,
);
},
idler,
);
getLogger().trackTimeSince(processQueueMarker, processQueueMarker, {
pluginId,
});
}
}
}
export function determinePluginsToProcess(
clients: Array<Client>,
selectedDevice: null | BaseDevice,
plugins: PluginsState,
): PluginsToProcess {
const pluginsToProcess: PluginsToProcess = [];
const selectedPlugins = plugins.selectedPlugins;
for (const client of clients) {
if (!selectedDevice || client.query.device_id !== selectedDevice.serial) {
continue;
}
const selectedFilteredPlugins = client
? selectedPlugins.length > 0
? client.plugins.filter((plugin) => selectedPlugins.includes(plugin))
: client.plugins
: [];
for (const plugin of selectedFilteredPlugins) {
if (!client.plugins.includes(plugin)) {
// Ignore clients which doesn't support the selected plugins.
continue;
}
const pluginClass =
plugins.clientPlugins.get(plugin) || plugins.devicePlugins.get(plugin);
if (pluginClass) {
const key = pluginKey(client.id, plugin);
pluginsToProcess.push({
pluginKey: key,
client,
pluginId: plugin,
pluginName: getPluginTitle(pluginClass),
pluginClass,
});
}
}
}
return pluginsToProcess;
}
async function getStoreExport(
store: MiddlewareAPI,
statusUpdate: (msg: string) => void = () => {},
idler: Idler,
): Promise<{
exportData: ExportType;
fetchMetaDataErrors: {[plugin: string]: Error} | null;
}> {
let state = store.getState();
const {clients, selectedApp, selectedDevice} = state.connections;
const pluginsToProcess = determinePluginsToProcess(
clients,
selectedDevice,
state.plugins,
);
statusUpdate?.('Preparing to process data queues for plugins...');
await processQueues(store, pluginsToProcess, statusUpdate, idler);
state = store.getState();
statusUpdate && statusUpdate('Preparing to fetch metadata from client...');
const fetchMetaDataMarker = `${EXPORT_FLIPPER_TRACE_EVENT}:fetch-meta-data`;
performance.mark(fetchMetaDataMarker);
const client = clients.find((client) => client.id === selectedApp);
const metadata = await fetchMetadata(
pluginsToProcess,
state.pluginStates,
state,
statusUpdate,
idler,
);
const newPluginState = metadata.pluginStates;
const pluginStates2 = pluginsToProcess
? await exportSandyPluginStates(pluginsToProcess, idler, statusUpdate)
: {};
getLogger().trackTimeSince(fetchMetaDataMarker, fetchMetaDataMarker, {
plugins: state.plugins.selectedPlugins,
});
const {errors} = metadata;
const {activeNotifications} = state.notifications;
const {devicePlugins, clientPlugins} = state.plugins;
const exportData = await processStore(
{
activeNotifications,
device: selectedDevice,
pluginStates: newPluginState,
pluginStates2,
clients: client ? [client.toJSON()] : [],
devicePlugins,
clientPlugins,
salt: uuidv4(),
selectedPlugins: state.plugins.selectedPlugins,
statusUpdate,
},
idler,
);
return {exportData, fetchMetaDataErrors: errors};
}
export async function exportStore(
store: MiddlewareAPI,
includeSupportDetails?: boolean,
idler: Idler = new TestIdler(true),
statusUpdate: (msg: string) => void = () => {},
): Promise<{
serializedString: string;
fetchMetaDataErrors: {
[plugin: string]: Error;
} | null;
exportStoreData: ExportType;
}> {
getLogger().track('usage', EXPORT_FLIPPER_TRACE_EVENT);
performance.mark(EXPORT_FLIPPER_TRACE_TIME_SERIALIZATION_EVENT);
statusUpdate && statusUpdate('Preparing to export Flipper data...');
const state = store.getState();
const {exportData, fetchMetaDataErrors} = await getStoreExport(
store,
statusUpdate,
idler,
);
if (includeSupportDetails) {
exportData.supportRequestDetails = {
...state.supportForm?.supportFormV2,
appName:
state.connections.selectedApp == null
? ''
: deconstructClientId(state.connections.selectedApp).app,
};
}
statusUpdate && statusUpdate('Serializing Flipper data...');
const serializedString = JSON.stringify(exportData);
if (serializedString.length <= 0) {
throw new Error('Serialize function returned empty string');
}
getLogger().trackTimeSince(
EXPORT_FLIPPER_TRACE_TIME_SERIALIZATION_EVENT,
EXPORT_FLIPPER_TRACE_TIME_SERIALIZATION_EVENT,
{
plugins: state.plugins.selectedPlugins,
},
);
return {serializedString, fetchMetaDataErrors, exportStoreData: exportData};
}
export const exportStoreToFile = (
exportFilePath: string,
store: MiddlewareAPI,
includeSupportDetails: boolean,
idler?: Idler,
statusUpdate?: (msg: string) => void,
): Promise<{
fetchMetaDataErrors: {
[plugin: string]: Error;
} | null;
}> => {
return exportStore(store, includeSupportDetails, idler, statusUpdate).then(
({serializedString, fetchMetaDataErrors}) => {
return promisify(fs.writeFile)(exportFilePath, serializedString).then(
() => {
store.dispatch(resetSupportFormV2State());
return {fetchMetaDataErrors};
},
);
},
);
};
export function importDataToStore(source: string, data: string, store: Store) {
getLogger().track('usage', IMPORT_FLIPPER_TRACE_EVENT);
const json: ExportType = JSON.parse(data);
const {device, clients, supportRequestDetails, deviceScreenshot} = json;
if (device == null) {
return;
}
const {serial, deviceType, title, os} = device;
const archivedDevice = new ArchivedDevice({
serial,
deviceType,
title,
os,
screenshotHandle: deviceScreenshot,
source,
supportRequestDetails,
});
archivedDevice.loadDevicePlugins(
store.getState().plugins.devicePlugins,
deserializeObject(device.pluginStates),
);
store.dispatch({
type: 'REGISTER_DEVICE',
payload: archivedDevice,
});
store.dispatch({
type: 'SELECT_DEVICE',
payload: archivedDevice,
});
const {pluginStates} = json.store;
const processedPluginStates: PluginStatesState = deserializePluginStates(
pluginStates,
store.getState().plugins.clientPlugins,
store.getState().plugins.devicePlugins,
);
const keys = Object.keys(processedPluginStates);
keys.forEach((key) => {
store.dispatch({
type: 'SET_PLUGIN_STATE',
payload: {
pluginKey: key,
state: processedPluginStates[key],
},
});
});
clients.forEach((client: {id: string; query: ClientQuery}) => {
const sandyPluginStates = deserializeObject(
json.pluginStates2[client.id] || {},
);
const clientPlugins: Array<string> = [
...keys
.filter((key) => {
const plugin = deconstructPluginKey(key);
return plugin.type === 'client' && client.id === plugin.client;
})
.map((pluginKey) => deconstructPluginKey(pluginKey).pluginName),
...Object.keys(sandyPluginStates),
];
store.dispatch({
type: 'NEW_CLIENT',
payload: new Client(
client.id,
client.query,
null,
getLogger(),
store,
clientPlugins,
archivedDevice,
).initFromImport(sandyPluginStates),
});
});
if (supportRequestDetails) {
store.dispatch(
// Late require to avoid circular dependency issue
setStaticView(require('../fb-stubs/SupportRequestDetails').default),
);
}
}
export const importFileToStore = (file: string, store: Store) => {
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
importDataToStore(file, data, store);
});
};
export function showOpenDialog(store: Store) {
const options: OpenDialogOptions = {
properties: ['openFile'],
filters: [{extensions: ['flipper', 'json', 'txt'], name: 'Flipper files'}],
};
remote.dialog.showOpenDialog(options).then((result) => {
const filePaths = result.filePaths;
if (filePaths.length > 0) {
tryCatchReportPlatformFailures(() => {
importFileToStore(filePaths[0], store);
}, `${IMPORT_FLIPPER_TRACE_EVENT}:UI`);
}
});
}
export function startFileExport(dispatch: Store['dispatch']) {
electron.remote.dialog
.showSaveDialog(
// @ts-ignore This appears to work but isn't allowed by the types
null,
{
title: 'FlipperExport',
defaultPath: path.join(os.homedir(), 'FlipperExport.flipper'),
},
)
.then(async (result: electron.SaveDialogReturnValue) => {
const file = result.filePath;
if (!file) {
return;
}
dispatch(
setSelectPluginsToExportActiveSheet({
type: 'file',
file: file,
closeOnFinish: false,
}),
);
});
}
export function startLinkExport(dispatch: Store['dispatch']) {
dispatch(
setSelectPluginsToExportActiveSheet({
type: 'link',
closeOnFinish: false,
}),
);
} | throw new Error(
`Error while exporting, plugin state (${key}) does not have ${baseSerial} in its key`,
); |
1623159171726-ScenarioPlannigUnitInclusionEvents.ts | import { MigrationInterface, QueryRunner } from 'typeorm';
export class ScenarioPlanningUnitInclusionEvents1623159171726
implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
INSERT INTO api_event_kinds (id) values
('scenario.planningUnitsInclusion.submitted/v1alpha'),
('scenario.planningUnitsInclusion.failed/v1alpha'),
('scenario.planningUnitsInclusion.finished/v1alpha');
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`DELETE FROM api_event_kinds WHERE id like 'scenario.planningUnitsInclusion.%';`, | );
}
} | |
version.js | let version = '2.6.0-beta.0'; | export default version; |
|
mod.rs | //
// Copyright 2019 Hans W. Uhlig. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
mod args;
mod codec;
mod error;
mod frame;
mod options;
pub use self::args::TelnetArgument;
pub use self::codec::TelnetCodec;
pub use self::error::DecodeError;
pub use self::error::EncodeError;
pub use self::frame::TelnetFrame;
pub use self::options::TelnetOption;
#[cfg(test)]
mod tests {
use super::consts;
use super::{TelnetCodec, TelnetFrame};
use bytes::BytesMut;
use tokio_util::codec::{Decoder, Encoder};
#[test]
fn telnet_decode() {
let mut codec = TelnetCodec::default();
let mut encoded_input = BytesMut::from(&b"Terminated line\r\n"[..]);
let expected_output = vec![
TelnetFrame::Data(b'T'),
TelnetFrame::Data(b'e'),
TelnetFrame::Data(b'r'),
TelnetFrame::Data(b'm'),
TelnetFrame::Data(b'i'),
TelnetFrame::Data(b'n'),
TelnetFrame::Data(b'a'),
TelnetFrame::Data(b't'),
TelnetFrame::Data(b'e'),
TelnetFrame::Data(b'd'),
TelnetFrame::Data(b' '),
TelnetFrame::Data(b'l'),
TelnetFrame::Data(b'i'),
TelnetFrame::Data(b'n'),
TelnetFrame::Data(b'e'),
TelnetFrame::Data(b'\r'),
TelnetFrame::Data(b'\n'),
];
let mut actual_output = Vec::new();
while let Some(frame) = codec.decode(&mut encoded_input).unwrap() {
actual_output.push(frame)
}
assert_eq!(
expected_output, actual_output,
"telnet_decode didn't match"
);
}
#[test]
fn telnet_encode() |
#[test]
fn decode_iac_activation() {
let mut codec = TelnetCodec::default();
let mut encoded_input = BytesMut::from(
&[
// Data
b'L',
b'o',
b'g',
b'i',
b'n',
b':',
consts::CR,
consts::LF,
// Command Do Binary
consts::IAC,
consts::DO,
crate::terminal::consts::option::BINARY,
// Data
b'P',
b'a',
b's',
b's',
b'w',
b'o',
b'r',
b'd',
b':',
consts::CR,
consts::LF,
// Command Will Binary
consts::IAC,
consts::WILL,
crate::terminal::consts::option::BINARY,
// Data
b'H',
b'e',
b'l',
b'l',
b'o',
b'!',
consts::CR,
consts::LF,
][..],
);
let expected_output = vec![
// Normal Data
TelnetFrame::Data(b'L'),
TelnetFrame::Data(b'o'),
TelnetFrame::Data(b'g'),
TelnetFrame::Data(b'i'),
TelnetFrame::Data(b'n'),
TelnetFrame::Data(b':'),
TelnetFrame::Data(consts::CR),
TelnetFrame::Data(consts::LF),
// Command Do Binary
TelnetFrame::Do(crate::terminal::consts::option::BINARY),
// Data
TelnetFrame::Data(b'P'),
TelnetFrame::Data(b'a'),
TelnetFrame::Data(b's'),
TelnetFrame::Data(b's'),
TelnetFrame::Data(b'w'),
TelnetFrame::Data(b'o'),
TelnetFrame::Data(b'r'),
TelnetFrame::Data(b'd'),
TelnetFrame::Data(b':'),
TelnetFrame::Data(consts::CR),
TelnetFrame::Data(consts::LF),
// Command Will Binary
TelnetFrame::Will(crate::terminal::consts::option::BINARY),
// Data
TelnetFrame::Data(b'H'),
TelnetFrame::Data(b'e'),
TelnetFrame::Data(b'l'),
TelnetFrame::Data(b'l'),
TelnetFrame::Data(b'o'),
TelnetFrame::Data(b'!'),
TelnetFrame::Data(consts::CR),
TelnetFrame::Data(consts::LF),
];
let mut actual_output = Vec::new();
while let Some(frame) = codec.decode(&mut encoded_input).unwrap() {
actual_output.push(frame)
}
assert_eq!(expected_output, actual_output);
}
}
| {
let mut codec = TelnetCodec::default();
let input_frames = vec![
TelnetFrame::Data(b'R'),
TelnetFrame::Data(b'a'),
TelnetFrame::Data(b'w'),
TelnetFrame::Data(b' '),
TelnetFrame::Data(b'A'),
TelnetFrame::Data(b's'),
TelnetFrame::Data(b'c'),
TelnetFrame::Data(b'i'),
TelnetFrame::Data(b'i'),
TelnetFrame::Data(b' '),
TelnetFrame::Data(b'D'),
TelnetFrame::Data(b'a'),
TelnetFrame::Data(b't'),
TelnetFrame::Data(b'a'),
TelnetFrame::Data(b'\r'),
TelnetFrame::Data(b'\n'),
];
let expected_output = BytesMut::from(&b"Raw Ascii Data\r\n"[..]);
let mut actual_output = BytesMut::with_capacity(20);
for input_frame in input_frames {
codec.encode(input_frame, &mut actual_output).unwrap();
}
assert_eq!(
expected_output, actual_output,
"telnet_encode didn't match"
);
} |
models.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import shutil
import hmac
import hashlib
from django.db import models
from django.db.models.signals import post_save
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from .settings import DAV_ROOT, PROVIDER_NAME, BOILERPLATE_INITIALIZER, \
get_resource_model, get_resource_access_model, BOILERPLATE_FOLDER, \
import_from_path, SECRET_KEY
class ResourceAccessManager(models.Manager):
def filter_validated(self, *args, **kwargs):
return self.filter(resource_pointer__is_validated=True,
*args, **kwargs)
class ResourcePointer(models.Model):
resource = models.OneToOneField(get_resource_model())
is_validated = models.BooleanField(default=False)
class AbstractResourceAccess(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
resource_pointer = models.ForeignKey(ResourcePointer)
objects = ResourceAccessManager()
class Meta:
abstract = True
verbose_name = _('ResourceAccess')
verbose_name_plural = _('ResourceAccesses')
unique_together = ('user', 'resource_pointer')
def get_absolute_url(self):
"""Returns the WebDav path for this resource."""
return os.path.join('/' + PROVIDER_NAME,
str(self.resource_pointer.resource.id)) + '/'
def get_path(self, append=None):
if append and not append.endswith('/'):
append += '/'
return os.path.join(DAV_ROOT, str(self.resource_pointer.resource.id),
append)
def get_access_token(self):
return hmac.new(SECRET_KEY, str(self.resource_pointer.resource.id),
hashlib.sha1).hexdigest()
def validate_access_token(self, token):
return self.get_access_token() == token
class ResourceAccess(AbstractResourceAccess):
"""Resource Access Model."""
def copy_boilerplate_folder(user_dir):
|
def create_resource_access(sender, instance, created, **kwargs):
if created:
try:
user_dir = os.path.join(
DAV_ROOT, str(instance.resource_pointer.resource.id)
)
# create in case neither folder or initializer are defined.
os.makedirs(user_dir)
import_from_path(BOILERPLATE_INITIALIZER)(user_dir)
except OSError as e: # pragma no cover
if e.errno != 17:
raise
# When a custom ResourceAccess model is used, you also have to connect the
# signal with your custom model.
if not getattr(settings, 'TEMPLATION_RESOURCE_ACCESS_MODEL', False):
post_save.connect(create_resource_access,
sender=get_resource_access_model())
| """
Default behavior to initialize the webdav folder. copy the resources from
`settings.TEMPLATION_BOILERPLATE_FOLDER` to the newly created folder.
Overridable function with `settings.TEMPLATION_BOILERPLATE_INITIALIZER`.
"""
if os.path.isdir(BOILERPLATE_FOLDER):
shutil.rmtree(user_dir) # copytree needs to create the dir...
shutil.copytree(BOILERPLATE_FOLDER, user_dir)
elif BOILERPLATE_FOLDER: # pragma no cover
raise ValueError(
'{0} is not a valid directory'.format(BOILERPLATE_FOLDER)
) |
createPolylineGeometry.js | /**
* Cesium - https://github.com/AnalyticalGraphicsInc/cesium
*
* Copyright 2011-2017 Cesium Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Columbus View (Pat. Pend.)
*
* Portions licensed separately.
* See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
*/
/**
@license
mersenne-twister.js - https://gist.github.com/banksean/300494
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
!function(){define("Core/defined",[],function(){"use strict";function e(e){return void 0!==e&&null!==e}return e}),define("Core/DeveloperError",["./defined"],function(e){"use strict";function t(e){this.name="DeveloperError",this.message=e;var t;try{throw new Error}catch(r){t=r.stack}this.stack=t}return e(Object.create)&&(t.prototype=Object.create(Error.prototype),t.prototype.constructor=t),t.prototype.toString=function(){var t=this.name+": "+this.message;return e(this.stack)&&(t+="\n"+this.stack.toString()),t},t.throwInstantiationError=function(){throw new t("This function defines an interface and should not be called directly.")},t}),define("Core/Check",["./defined","./DeveloperError"],function(e,t){"use strict";function r(e){return e+" is required, actual value was undefined"}function n(e,t,r){return"Expected "+r+" to be typeof "+t+", actual typeof was "+e}var o={};return o.typeOf={},o.defined=function(n,o){if(!e(o))throw new t(r(n))},o.typeOf.func=function(e,r){if("function"!=typeof r)throw new t(n(typeof r,"function",e))},o.typeOf.string=function(e,r){if("string"!=typeof r)throw new t(n(typeof r,"string",e))},o.typeOf.number=function(e,r){if("number"!=typeof r)throw new t(n(typeof r,"number",e))},o.typeOf.number.lessThan=function(e,r,n){if(o.typeOf.number(e,r),r>=n)throw new t("Expected "+e+" to be less than "+n+", actual value was "+r)},o.typeOf.number.lessThanOrEquals=function(e,r,n){if(o.typeOf.number(e,r),r>n)throw new t("Expected "+e+" to be less than or equal to "+n+", actual value was "+r)},o.typeOf.number.greaterThan=function(e,r,n){if(o.typeOf.number(e,r),n>=r)throw new t("Expected "+e+" to be greater than "+n+", actual value was "+r)},o.typeOf.number.greaterThanOrEquals=function(e,r,n){if(o.typeOf.number(e,r),n>r)throw new t("Expected "+e+" to be greater than or equal to"+n+", actual value was "+r)},o.typeOf.object=function(e,r){if("object"!=typeof r)throw new t(n(typeof r,"object",e))},o.typeOf.bool=function(e,r){if("boolean"!=typeof r)throw new t(n(typeof r,"boolean",e))},o.typeOf.number.equals=function(e,r,n,i){if(o.typeOf.number(e,n),o.typeOf.number(r,i),n!==i)throw new t(e+" must be equal to "+r+", the actual values are "+n+" and "+i)},o}),define("Core/freezeObject",["./defined"],function(e){"use strict";var t=Object.freeze;return e(t)||(t=function(e){return e}),t}),define("Core/defaultValue",["./freezeObject"],function(e){"use strict";function t(e,t){return void 0!==e&&null!==e?e:t}return t.EMPTY_OBJECT=e({}),t}),define("ThirdParty/mersenne-twister",[],function(){var e=function(e){void 0==e&&(e=(new Date).getTime()),this.N=624,this.M=397,this.MATRIX_A=2567483615,this.UPPER_MASK=2147483648,this.LOWER_MASK=2147483647,this.mt=new Array(this.N),this.mti=this.N+1,this.init_genrand(e)};return e.prototype.init_genrand=function(e){for(this.mt[0]=e>>>0,this.mti=1;this.mti<this.N;this.mti++){var e=this.mt[this.mti-1]^this.mt[this.mti-1]>>>30;this.mt[this.mti]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+this.mti,this.mt[this.mti]>>>=0}},e.prototype.genrand_int32=function(){var e,t=new Array(0,this.MATRIX_A);if(this.mti>=this.N){var r;for(this.mti==this.N+1&&this.init_genrand(5489),r=0;r<this.N-this.M;r++)e=this.mt[r]&this.UPPER_MASK|this.mt[r+1]&this.LOWER_MASK,this.mt[r]=this.mt[r+this.M]^e>>>1^t[1&e];for(;r<this.N-1;r++)e=this.mt[r]&this.UPPER_MASK|this.mt[r+1]&this.LOWER_MASK,this.mt[r]=this.mt[r+(this.M-this.N)]^e>>>1^t[1&e];e=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK,this.mt[this.N-1]=this.mt[this.M-1]^e>>>1^t[1&e],this.mti=0}return e=this.mt[this.mti++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,e>>>0},e.prototype.random=function(){return this.genrand_int32()*(1/4294967296)},e}),define("Core/Math",["../ThirdParty/mersenne-twister","./defaultValue","./defined","./DeveloperError"],function(e,t,r,n){"use strict";var o={};o.Radious=6378137,o.EPSILON1=.1,o.EPSILON2=.01,o.EPSILON3=.001,o.EPSILON4=1e-4,o.EPSILON5=1e-5,o.EPSILON6=1e-6,o.EPSILON7=1e-7,o.EPSILON8=1e-8,o.EPSILON9=1e-9,o.EPSILON10=1e-10,o.EPSILON11=1e-11,o.EPSILON12=1e-12,o.EPSILON13=1e-13,o.EPSILON14=1e-14,o.EPSILON15=1e-15,o.EPSILON16=1e-16,o.EPSILON17=1e-17,o.EPSILON18=1e-18,o.EPSILON19=1e-19,o.EPSILON20=1e-20,o.GRAVITATIONALPARAMETER=3986004418e5,o.SOLAR_RADIUS=6955e5,o.LUNAR_RADIUS=1737400,o.SIXTY_FOUR_KILOBYTES=65536,o.sign=function(e){return e>0?1:0>e?-1:0},o.signNotZero=function(e){return 0>e?-1:1},o.toSNorm=function(e,r){return r=t(r,255),Math.round((.5*o.clamp(e,-1,1)+.5)*r)},o.fromSNorm=function(e,r){return r=t(r,255),o.clamp(e,0,r)/r*2-1},o.sinh=function(e){var t=Math.pow(Math.E,e),r=Math.pow(Math.E,-1*e);return.5*(t-r)},o.cosh=function(e){var t=Math.pow(Math.E,e),r=Math.pow(Math.E,-1*e);return.5*(t+r)},o.lerp=function(e,t,r){return(1-r)*e+r*t},o.PI=Math.PI,o.ONE_OVER_PI=1/Math.PI,o.PI_OVER_TWO=.5*Math.PI,o.PI_OVER_THREE=Math.PI/3,o.PI_OVER_FOUR=Math.PI/4,o.PI_OVER_SIX=Math.PI/6,o.THREE_PI_OVER_TWO=3*Math.PI*.5,o.TWO_PI=2*Math.PI,o.ONE_OVER_TWO_PI=1/(2*Math.PI),o.RADIANS_PER_DEGREE=Math.PI/180,o.DEGREES_PER_RADIAN=180/Math.PI,o.RADIANS_PER_ARCSECOND=o.RADIANS_PER_DEGREE/3600,o.toRadians=function(e){if(!r(e))throw new n("degrees is required.");return e*o.RADIANS_PER_DEGREE},o.toDegrees=function(e){if(!r(e))throw new n("radians is required.");return e*o.DEGREES_PER_RADIAN},o.convertLongitudeRange=function(e){if(!r(e))throw new n("angle is required.");var t=o.TWO_PI,i=e-Math.floor(e/t)*t;return i<-Math.PI?i+t:i>=Math.PI?i-t:i},o.clampToLatitudeRange=function(e){if(!r(e))throw new n("angle is required.");return o.clamp(e,-1*o.PI_OVER_TWO,o.PI_OVER_TWO)},o.negativePiToPi=function(e){if(!r(e))throw new n("angle is required.");return o.zeroToTwoPi(e+o.PI)-o.PI},o.zeroToTwoPi=function(e){if(!r(e))throw new n("angle is required.");var t=o.mod(e,o.TWO_PI);return Math.abs(t)<o.EPSILON14&&Math.abs(e)>o.EPSILON14?o.TWO_PI:t},o.mod=function(e,t){if(!r(e))throw new n("m is required.");if(!r(t))throw new n("n is required.");return(e%t+t)%t},o.equalsEpsilon=function(e,o,i,a){if(!r(e))throw new n("left is required.");if(!r(o))throw new n("right is required.");if(!r(i))throw new n("relativeEpsilon is required.");a=t(a,i);var u=Math.abs(e-o);return a>=u||u<=i*Math.max(Math.abs(e),Math.abs(o))};var i=[1];o.factorial=function(e){if("number"!=typeof e||0>e)throw new n("A number greater than or equal to 0 is required.");var t=i.length;if(e>=t)for(var r=i[t-1],o=t;e>=o;o++)i.push(r*o);return i[e]},o.incrementWrap=function(e,o,i){if(i=t(i,0),!r(e))throw new n("n is required.");if(i>=o)throw new n("maximumValue must be greater than minimumValue.");return++e,e>o&&(e=i),e},o.isPowerOfTwo=function(e){if("number"!=typeof e||0>e)throw new n("A number greater than or equal to 0 is required.");return 0!==e&&0===(e&e-1)},o.nextPowerOfTwo=function(e){if("number"!=typeof e||0>e)throw new n("A number greater than or equal to 0 is required.");return--e,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e,e},o.clamp=function(e,t,o){if(!r(e))throw new n("value is required");if(!r(t))throw new n("min is required.");if(!r(o))throw new n("max is required.");return t>e?t:e>o?o:e};var a=new e;return o.setRandomNumberSeed=function(t){if(!r(t))throw new n("seed is required.");a=new e(t)},o.nextRandomNumber=function(){return a.random()},o.randomBetween=function(e,t){return o.nextRandomNumber()*(t-e)+e},o.acosClamped=function(e){if(!r(e))throw new n("value is required.");return Math.acos(o.clamp(e,-1,1))},o.asinClamped=function(e){if(!r(e))throw new n("value is required.");return Math.asin(o.clamp(e,-1,1))},o.chordLength=function(e,t){if(!r(e))throw new n("angle is required.");if(!r(t))throw new n("radius is required.");return 2*t*Math.sin(.5*e)},o.logBase=function(e,t){if(!r(e))throw new n("number is required.");if(!r(t))throw new n("base is required.");return Math.log(e)/Math.log(t)},o.fog=function(e,t){var r=e*t;return 1-Math.exp(-(r*r))},o}),define("Core/Cartesian3",["./Check","./defaultValue","./defined","./DeveloperError","./freezeObject","./Math"],function(e,t,r,n,o,i){"use strict";function a(e,r,n){this.x=t(e,0),this.y=t(r,0),this.z=t(n,0)}a.fromSpherical=function(n,o){e.typeOf.object("spherical",n),r(o)||(o=new a);var i=n.clock,u=n.cone,s=t(n.magnitude,1),c=s*Math.sin(u);return o.x=c*Math.cos(i),o.y=c*Math.sin(i),o.z=s*Math.cos(u),o},a.fromElements=function(e,t,n,o){return r(o)?(o.x=e,o.y=t,o.z=n,o):new a(e,t,n)},a.clone=function(e,t){return r(e)?r(t)?(t.x=e.x,t.y=e.y,t.z=e.z,t):new a(e.x,e.y,e.z):void 0},a.fromCartesian4=a.clone,a.packedLength=3,a.pack=function(r,n,o){return e.typeOf.object("value",r),e.defined("array",n),o=t(o,0),n[o++]=r.x,n[o++]=r.y,n[o]=r.z,n},a.unpack=function(n,o,i){return e.defined("array",n),o=t(o,0),r(i)||(i=new a),i.x=n[o++],i.y=n[o++],i.z=n[o],i},a.packArray=function(t,n){e.defined("array",t);var o=t.length;r(n)?n.length=3*o:n=new Array(3*o);for(var i=0;o>i;++i)a.pack(t[i],n,3*i);return n},a.unpackArray=function(t,o){if(e.defined("array",t),e.typeOf.number.greaterThanOrEquals("array.length",t.length,3),t.length%3!==0)throw new n("array length must be a multiple of 3.");var i=t.length;r(o)?o.length=i/3:o=new Array(i/3);for(var u=0;i>u;u+=3){var s=u/3;o[s]=a.unpack(t,u,o[s])}return o},a.fromArray=a.unpack,a.maximumComponent=function(t){return e.typeOf.object("cartesian",t),Math.max(t.x,t.y,t.z)},a.minimumComponent=function(t){return e.typeOf.object("cartesian",t),Math.min(t.x,t.y,t.z)},a.minimumByComponent=function(t,r,n){return e.typeOf.object("first",t),e.typeOf.object("second",r),e.typeOf.object("result",n),n.x=Math.min(t.x,r.x),n.y=Math.min(t.y,r.y),n.z=Math.min(t.z,r.z),n},a.maximumByComponent=function(t,r,n){return e.typeOf.object("first",t),e.typeOf.object("second",r),e.typeOf.object("result",n),n.x=Math.max(t.x,r.x),n.y=Math.max(t.y,r.y),n.z=Math.max(t.z,r.z),n},a.magnitudeSquared=function(t){return e.typeOf.object("cartesian",t),t.x*t.x+t.y*t.y+t.z*t.z},a.magnitude=function(e){return Math.sqrt(a.magnitudeSquared(e))};var u=new a;a.distance=function(t,r){return e.typeOf.object("left",t),e.typeOf.object("right",r),a.subtract(t,r,u),a.magnitude(u)},a.distanceSquared=function(t,r){return e.typeOf.object("left",t),e.typeOf.object("right",r),a.subtract(t,r,u),a.magnitudeSquared(u)},a.normalize=function(t,r){e.typeOf.object("cartesian",t),e.typeOf.object("result",r);var o=a.magnitude(t);if(r.x=t.x/o,r.y=t.y/o,r.z=t.z/o,isNaN(r.x)||isNaN(r.y)||isNaN(r.z))throw new n("normalized result is not a number");return r},a.dot=function(t,r){return e.typeOf.object("left",t),e.typeOf.object("right",r),t.x*r.x+t.y*r.y+t.z*r.z},a.multiplyComponents=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x*r.x,n.y=t.y*r.y,n.z=t.z*r.z,n},a.divideComponents=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x/r.x,n.y=t.y/r.y,n.z=t.z/r.z,n},a.add=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x+r.x,n.y=t.y+r.y,n.z=t.z+r.z,n},a.subtract=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x-r.x,n.y=t.y-r.y,n.z=t.z-r.z,n},a.multiplyByScalar=function(t,r,n){return e.typeOf.object("cartesian",t),e.typeOf.number("scalar",r),e.typeOf.object("result",n),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},a.divideByScalar=function(t,r,n){return e.typeOf.object("cartesian",t),e.typeOf.number("scalar",r),e.typeOf.object("result",n),n.x=t.x/r,n.y=t.y/r,n.z=t.z/r,n},a.negate=function(t,r){return e.typeOf.object("cartesian",t),e.typeOf.object("result",r),r.x=-t.x,r.y=-t.y,r.z=-t.z,r},a.abs=function(t,r){return e.typeOf.object("cartesian",t),e.typeOf.object("result",r),r.x=Math.abs(t.x),r.y=Math.abs(t.y),r.z=Math.abs(t.z),r};var s=new a;a.lerp=function(t,r,n,o){return e.typeOf.object("start",t),e.typeOf.object("end",r),e.typeOf.number("t",n),e.typeOf.object("result",o),a.multiplyByScalar(r,n,s),o=a.multiplyByScalar(t,1-n,o),a.add(s,o,o)};var c=new a,l=new a;a.angleBetween=function(t,r){e.typeOf.object("left",t),e.typeOf.object("right",r),a.normalize(t,c),a.normalize(r,l);var n=a.dot(c,l),o=a.magnitude(a.cross(c,l,c));return Math.atan2(o,n)};var f=new a;a.mostOrthogonalAxis=function(t,r){e.typeOf.object("cartesian",t),e.typeOf.object("result",r);var n=a.normalize(t,f);return a.abs(n,n),r=n.x<=n.y?n.x<=n.z?a.clone(a.UNIT_X,r):a.clone(a.UNIT_Z,r):n.y<=n.z?a.clone(a.UNIT_Y,r):a.clone(a.UNIT_Z,r)},a.equals=function(e,t){return e===t||r(e)&&r(t)&&e.x===t.x&&e.y===t.y&&e.z===t.z},a.equalsArray=function(e,t,r){return e.x===t[r]&&e.y===t[r+1]&&e.z===t[r+2]},a.equalsEpsilon=function(e,t,n,o){return e===t||r(e)&&r(t)&&i.equalsEpsilon(e.x,t.x,n,o)&&i.equalsEpsilon(e.y,t.y,n,o)&&i.equalsEpsilon(e.z,t.z,n,o)},a.cross=function(t,r,n){e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n);var o=t.x,i=t.y,a=t.z,u=r.x,s=r.y,c=r.z,l=i*c-a*s,f=a*u-o*c,E=o*s-i*u;return n.x=l,n.y=f,n.z=E,n},a.fromDegrees=function(t,r,n,o,u){return e.typeOf.number("longitude",t),e.typeOf.number("latitude",r),t=i.toRadians(t),r=i.toRadians(r),a.fromRadians(t,r,n,o,u)};var E=new a,h=new a,d=(new a(40680631590769,40680631590769,40408299984661.445),new a(40680631590769,40680631590769,40680631590769));return a.fromRadians=function(n,o,i,u,s){e.typeOf.number("longitude",n),e.typeOf.number("latitude",o),i=t(i,0);var c=r(u)?u.radiiSquared:d,l=Math.cos(o);E.x=l*Math.cos(n),E.y=l*Math.sin(n),E.z=Math.sin(o),E=a.normalize(E,E),a.multiplyComponents(c,E,h);var f=Math.sqrt(a.dot(E,h));return h=a.divideByScalar(h,f,h),E=a.multiplyByScalar(E,i,E),r(s)||(s=new a),a.add(h,E,s)},a.fromDegreesArray=function(t,o,i){if(e.defined("coordinates",t),t.length<2||t.length%2!==0)throw new n("the number of coordinates must be a multiple of 2 and at least 2");var u=t.length;r(i)?i.length=u/2:i=new Array(u/2);for(var s=0;u>s;s+=2){var c=t[s],l=t[s+1],f=s/2;i[f]=a.fromDegrees(c,l,0,o,i[f])}return i},a.fromRadiansArray=function(t,o,i){if(e.defined("coordinates",t),t.length<2||t.length%2!==0)throw new n("the number of coordinates must be a multiple of 2 and at least 2");var u=t.length;r(i)?i.length=u/2:i=new Array(u/2);for(var s=0;u>s;s+=2){var c=t[s],l=t[s+1],f=s/2;i[f]=a.fromRadians(c,l,0,o,i[f])}return i},a.fromDegreesArrayHeights=function(t,o,i){if(e.defined("coordinates",t),t.length<3||t.length%3!==0)throw new n("the number of coordinates must be a multiple of 3 and at least 3");var u=t.length;r(i)?i.length=u/3:i=new Array(u/3);for(var s=0;u>s;s+=3){var c=t[s],l=t[s+1],f=t[s+2],E=s/3;i[E]=a.fromDegrees(c,l,f,o,i[E])}return i},a.fromRadiansArrayHeights=function(t,o,i){if(e.defined("coordinates",t),t.length<3||t.length%3!==0)throw new n("the number of coordinates must be a multiple of 3 and at least 3");var u=t.length;r(i)?i.length=u/3:i=new Array(u/3);for(var s=0;u>s;s+=3){var c=t[s],l=t[s+1],f=t[s+2],E=s/3;i[E]=a.fromRadians(c,l,f,o,i[E])}return i},a.ZERO=o(new a(0,0,0)),a.UNIT_X=o(new a(1,0,0)),a.UNIT_Y=o(new a(0,1,0)),a.UNIT_Z=o(new a(0,0,1)),a.prototype.clone=function(e){return a.clone(this,e)},a.prototype.equals=function(e){return a.equals(this,e)},a.prototype.equalsEpsilon=function(e,t,r){return a.equalsEpsilon(this,e,t,r)},a.prototype.toString=function(){return"("+this.x+", "+this.y+", "+this.z+")"},a}),define("Core/scaleToGeodeticSurface",["./Cartesian3","./defined","./DeveloperError","./Math"],function(e,t,r,n){"use strict";function o(o,u,s,c,l){if(!t(o))throw new r("cartesian is required.");if(!t(u))throw new r("oneOverRadii is required.");if(!t(s))throw new r("oneOverRadiiSquared is required.");if(!t(c))throw new r("centerToleranceSquared is required.");var f=o.x,E=o.y,h=o.z,d=u.x,p=u.y,_=u.z,m=f*f*d*d,O=E*E*p*p,R=h*h*_*_,y=m+O+R,T=Math.sqrt(1/y),A=e.multiplyByScalar(o,T,i);if(c>y)return isFinite(T)?e.clone(A,l):void 0;var S=s.x,N=s.y,C=s.z,g=a;g.x=A.x*S*2,g.y=A.y*N*2,g.z=A.z*C*2;var I,b,M,w,v,F,L,P,D,U,B,x=(1-T)*e.magnitude(o)/(.5*e.magnitude(g)),G=0;do{x-=G,M=1/(1+x*S),w=1/(1+x*N),v=1/(1+x*C),F=M*M,L=w*w,P=v*v,D=F*M,U=L*w,B=P*v,I=m*F+O*L+R*P-1,b=m*D*S+O*U*N+R*B*C;var q=-2*b;G=I/q}while(Math.abs(I)>n.EPSILON12);return t(l)?(l.x=f*M,l.y=E*w,l.z=h*v,l):new e(f*M,E*w,h*v)}var i=new e,a=new e;return o}),define("Core/Cartographic",["./Cartesian3","./Check","./defaultValue","./defined","./freezeObject","./Math","./scaleToGeodeticSurface"],function(e,t,r,n,o,i,a){"use strict";function u(e,t,n){this.longitude=r(e,0),this.latitude=r(t,0),this.height=r(n,0)}u.fromRadians=function(e,o,i,a){return t.typeOf.number("longitude",e),t.typeOf.number("latitude",o),i=r(i,0),n(a)?(a.longitude=e,a.latitude=o,a.height=i,a):new u(e,o,i)},u.fromDegrees=function(e,r,n,o){return t.typeOf.number("longitude",e),t.typeOf.number("latitude",r),e=i.toRadians(e),r=i.toRadians(r),u.fromRadians(e,r,n,o)};var s=new e,c=new e,l=new e,f=(new e(1/6378137,1/6378137,1/6356752.314245179),new e(1/6378137,1/6378137,1/6378137)),E=(new e(1/40680631590769,1/40680631590769,1/40408299984661.445),new e(1/40680631590769,1/40680631590769,1/40680631590769)),h=i.EPSILON1;return u.fromCartesian=function(t,r,o){var d=n(r)?r.oneOverRadii:f,p=n(r)?r.oneOverRadiiSquared:E,_=n(r)?r._centerToleranceSquared:h,m=a(t,d,p,_,c);if(n(m)){var O=e.multiplyComponents(m,p,s);O=e.normalize(O,O);var R=e.subtract(t,m,l),y=Math.atan2(O.y,O.x),T=Math.asin(O.z),A=i.sign(e.dot(R,t))*e.magnitude(R);return n(o)?(o.longitude=y,o.latitude=T,o.height=A,o):new u(y,T,A)}},u.clone=function(e,t){return n(e)?n(t)?(t.longitude=e.longitude,t.latitude=e.latitude,t.height=e.height,t):new u(e.longitude,e.latitude,e.height):void 0},u.equals=function(e,t){return e===t||n(e)&&n(t)&&e.longitude===t.longitude&&e.latitude===t.latitude&&e.height===t.height},u.equalsEpsilon=function(e,r,o){return t.typeOf.number("epsilon",o),e===r||n(e)&&n(r)&&Math.abs(e.longitude-r.longitude)<=o&&Math.abs(e.latitude-r.latitude)<=o&&Math.abs(e.height-r.height)<=o},u.ZERO=o(new u(0,0,0)),u.prototype.clone=function(e){return u.clone(this,e)},u.prototype.equals=function(e){return u.equals(this,e)},u.prototype.equalsEpsilon=function(e,t){return u.equalsEpsilon(this,e,t)},u.prototype.toString=function(){return"("+this.longitude+", "+this.latitude+", "+this.height+")"},u.sphericalDistance=function(e,t,r,o){if(!n(e)||!n(r))throw new DeveloperError("longitude is required.");if(!n(t)||!n(o))throw new DeveloperError("latitude is required.");if(e===r&&t===o)return 0;var a=i.toRadians(t),u=i.toRadians(o),s=i.toRadians(e),c=i.toRadians(r),l=s*s+a*a,f=c*c+u*u,E=(s-c)*(s-c)+(a-u)*(a-u),h=(l+f-E)/(2*Math.sqrt(l)*Math.sqrt(f));return h=i.clamp(h,-1,1),Math.acos(h)*i.Radious},u}),define("Core/defineProperties",["./defined"],function(e){"use strict";var t=function(){try{return"x"in Object.defineProperty({},"x",{})}catch(e){return!1}}(),r=Object.defineProperties;return t&&e(r)||(r=function(e){return e}),r}),define("Core/Ellipsoid",["./Cartesian3","./Cartographic","./Check","./defaultValue","./defined","./defineProperties","./DeveloperError","./freezeObject","./Math","./scaleToGeodeticSurface"],function(e,t,r,n,o,i,a,u,s,c){"use strict";function l(t,o,i,a){o=n(o,0),i=n(i,0),a=n(a,0),s.equalsEpsilon(a,6378137,s.EPSILON10)&&(s.Radious=a),r.typeOf.number.greaterThanOrEquals("x",o,0),r.typeOf.number.greaterThanOrEquals("y",i,0),r.typeOf.number.greaterThanOrEquals("z",a,0),t._radii=new e(o,i,a),t._radiiSquared=new e(o*o,i*i,a*a),t._radiiToTheFourth=new e(o*o*o*o,i*i*i*i,a*a*a*a),t._oneOverRadii=new e(0===o?0:1/o,0===i?0:1/i,0===a?0:1/a),t._oneOverRadiiSquared=new e(0===o?0:1/(o*o),0===i?0:1/(i*i),0===a?0:1/(a*a)),t._minimumRadius=Math.min(o,i,a),t._maximumRadius=Math.max(o,i,a),t._centerToleranceSquared=s.EPSILON1,0!==t._radiiSquared.z&&(t._squaredXOverSquaredZ=t._radiiSquared.x/t._radiiSquared.z)}function f(e,t,r){this._radii=void 0,this._radiiSquared=void 0,this._radiiToTheFourth=void 0,this._oneOverRadii=void 0,this._oneOverRadiiSquared=void 0,this._minimumRadius=void 0,this._maximumRadius=void 0,this._centerToleranceSquared=void 0,this._squaredXOverSquaredZ=void 0,l(this,e,t,r)}i(f.prototype,{radii:{get:function(){return this._radii}},radiiSquared:{get:function(){return this._radiiSquared}},radiiToTheFourth:{get:function(){return this._radiiToTheFourth}},oneOverRadii:{get:function(){return this._oneOverRadii}},oneOverRadiiSquared:{get:function(){return this._oneOverRadiiSquared}},minimumRadius:{get:function(){return this._minimumRadius}},maximumRadius:{get:function(){return this._maximumRadius}}}),f.clone=function(t,r){if(o(t)){var n=t._radii;return o(r)?(e.clone(n,r._radii),e.clone(t._radiiSquared,r._radiiSquared),e.clone(t._radiiToTheFourth,r._radiiToTheFourth),e.clone(t._oneOverRadii,r._oneOverRadii),e.clone(t._oneOverRadiiSquared,r._oneOverRadiiSquared),r._minimumRadius=t._minimumRadius,r._maximumRadius=t._maximumRadius,r._centerToleranceSquared=t._centerToleranceSquared,r):new f(n.x,n.y,n.z)}},f.fromCartesian3=function(e,t){return o(t)||(t=new f),o(e)?(l(t,e.x,e.y,e.z),t):t},f.WGS84=u(new f(6378137,6378137,s.Radious)),f.UNIT_SPHERE=u(new f(1,1,1)),f.MOON=u(new f(s.LUNAR_RADIUS,s.LUNAR_RADIUS,s.LUNAR_RADIUS)),f.prototype.clone=function(e){return f.clone(this,e)},f.packedLength=e.packedLength,f.pack=function(t,o,i){return r.typeOf.object("value",t),r.defined("array",o),i=n(i,0),e.pack(t._radii,o,i),o},f.unpack=function(t,o,i){r.defined("array",t),o=n(o,0);var a=e.unpack(t,o);return f.fromCartesian3(a,i)},f.prototype.geocentricSurfaceNormal=e.normalize,f.prototype.geodeticSurfaceNormalCartographic=function(t,n){r.typeOf.object("cartographic",t);var i=t.longitude,a=t.latitude,u=Math.cos(a),s=u*Math.cos(i),c=u*Math.sin(i),l=Math.sin(a);return o(n)||(n=new e),n.x=s,n.y=c,n.z=l,e.normalize(n,n)},f.prototype.geodeticSurfaceNormal=function(t,r){return o(r)||(r=new e),r=e.multiplyComponents(t,this._oneOverRadiiSquared,r),e.normalize(r,r)};var E=new e,h=new e;f.prototype.cartographicToCartesian=function(t,r){var n=E,i=h;this.geodeticSurfaceNormalCartographic(t,n),e.multiplyComponents(this._radiiSquared,n,i);var a=Math.sqrt(e.dot(n,i));return e.divideByScalar(i,a,i),e.multiplyByScalar(n,t.height,n),o(r)||(r=new e),e.add(i,n,r)},f.prototype.cartographicArrayToCartesianArray=function(e,t){r.defined("cartographics",e);var n=e.length;o(t)?t.length=n:t=new Array(n);for(var i=0;n>i;i++)t[i]=this.cartographicToCartesian(e[i],t[i]);return t};var d=new e,p=new e,_=new e;return f.prototype.cartesianToCartographic=function(r,n){var i=this.scaleToGeodeticSurface(r,p);if(o(i)){var a=this.geodeticSurfaceNormal(i,d),u=e.subtract(r,i,_),c=Math.atan2(a.y,a.x),l=Math.asin(a.z),f=s.sign(e.dot(u,r))*e.magnitude(u);return o(n)?(n.longitude=c,n.latitude=l,n.height=f,n):new t(c,l,f)}},f.prototype.cartesianArrayToCartographicArray=function(e,t){r.defined("cartesians",e);var n=e.length;o(t)?t.length=n:t=new Array(n);for(var i=0;n>i;++i)t[i]=this.cartesianToCartographic(e[i],t[i]);return t},f.prototype.scaleToGeodeticSurface=function(e,t){return c(e,this._oneOverRadii,this._oneOverRadiiSquared,this._centerToleranceSquared,t)},f.prototype.scaleToGeocentricSurface=function(t,n){r.typeOf.object("cartesian",t),o(n)||(n=new e);var i=t.x,a=t.y,u=t.z,s=this._oneOverRadiiSquared,c=1/Math.sqrt(i*i*s.x+a*a*s.y+u*u*s.z);return e.multiplyByScalar(t,c,n)},f.prototype.transformPositionToScaledSpace=function(t,r){return o(r)||(r=new e),e.multiplyComponents(t,this._oneOverRadii,r)},f.prototype.transformPositionFromScaledSpace=function(t,r){return o(r)||(r=new e),e.multiplyComponents(t,this._radii,r)},f.prototype.equals=function(t){return this===t||o(t)&&e.equals(this._radii,t._radii)},f.prototype.toString=function(){return this._radii.toString()},f.prototype.getSurfaceNormalIntersectionWithZAxis=function(t,i,u){if(r.typeOf.object("position",t),!s.equalsEpsilon(this._radii.x,this._radii.y,s.EPSILON15))throw new a("Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)");r.typeOf.number.greaterThan("Ellipsoid.radii.z",this._radii.z,0),i=n(i,0);var c=this._squaredXOverSquaredZ;return o(u)||(u=new e),u.x=0,u.y=0,u.z=t.z*(1-c),Math.abs(u.z)>=this._radii.z-i?void 0:u},f}),define("Core/arrayRemoveDuplicates",["./Check","./defaultValue","./defined","./Math"],function(e,t,r,n){"use strict";function o(n,o,a){if(e.defined("equalsEpsilon",o),r(n)){a=t(a,!1);var u=n.length;if(2>u)return n;var s,c,l;for(s=1;u>s&&(c=n[s-1],l=n[s],!o(c,l,i));++s);if(s===u)return a&&o(n[0],n[n.length-1],i)?n.slice(1):n;for(var f=n.slice(0,s);u>s;++s)l=n[s],o(c,l,i)||(f.push(l),c=l);return a&&f.length>1&&o(f[0],f[f.length-1],i)&&f.shift(),f}}var i=n.EPSILON10;return o}),define("Core/GeographicProjection",["./Cartesian3","./Cartographic","./defaultValue","./defined","./defineProperties","./DeveloperError","./Ellipsoid"],function(e,t,r,n,o,i,a){"use strict";function u(e){this._ellipsoid=r(e,a.WGS84),this._semimajorAxis=this._ellipsoid.maximumRadius,this._oneOverSemimajorAxis=1/this._semimajorAxis}return o(u.prototype,{ellipsoid:{get:function(){return this._ellipsoid}}}),u.prototype.project=function(t,r){var o=this._semimajorAxis,i=t.longitude*o,a=t.latitude*o,u=t.height;return n(r)?(r.x=i,r.y=a,r.z=u,r):new e(i,a,u)},u.prototype.unproject=function(e,r){if(!n(e))throw new i("cartesian is required");var o=this._oneOverSemimajorAxis,a=e.x*o,u=e.y*o,s=e.z;return n(r)?(r.longitude=a,r.latitude=u,r.height=s,r):new t(a,u,s)},u}),define("Core/Intersect",["./freezeObject"],function(e){"use strict";var t={OUTSIDE:-1,INTERSECTING:0,INSIDE:1};return e(t)}),define("Core/Interval",["./defaultValue"],function(e){"use strict";function t(t,r){this.start=e(t,0),this.stop=e(r,0)}return t}),define("Core/Matrix3",["./Cartesian3","./Check","./defaultValue","./defined","./defineProperties","./DeveloperError","./freezeObject","./Math"],function(e,t,r,n,o,i,a,u){"use strict";function s(e,t,n,o,i,a,u,s,c){this[0]=r(e,0),this[1]=r(o,0),this[2]=r(u,0),this[3]=r(t,0),this[4]=r(i,0),this[5]=r(s,0),this[6]=r(n,0),this[7]=r(a,0),this[8]=r(c,0)}function c(e){for(var t=0,r=0;9>r;++r){var n=e[r];t+=n*n}return Math.sqrt(t)}function l(e){for(var t=0,r=0;3>r;++r){var n=e[s.getElementIndex(p[r],d[r])];t+=2*n*n}return Math.sqrt(t)}function f(e,t){for(var r=u.EPSILON15,n=0,o=1,i=0;3>i;++i){var a=Math.abs(e[s.getElementIndex(p[i],d[i])]);a>n&&(o=i,n=a)}var c=1,l=0,f=d[o],E=p[o];if(Math.abs(e[s.getElementIndex(E,f)])>r){var h,_=e[s.getElementIndex(E,E)],m=e[s.getElementIndex(f,f)],O=e[s.getElementIndex(E,f)],R=(_-m)/2/O;h=0>R?-1/(-R+Math.sqrt(1+R*R)):1/(R+Math.sqrt(1+R*R)),c=1/Math.sqrt(1+h*h),l=h*c}return t=s.clone(s.IDENTITY,t),t[s.getElementIndex(f,f)]=t[s.getElementIndex(E,E)]=c,t[s.getElementIndex(E,f)]=l,t[s.getElementIndex(f,E)]=-l,t}s.packedLength=9,s.pack=function(e,n,o){return t.typeOf.object("value",e),t.defined("array",n),o=r(o,0),n[o++]=e[0],n[o++]=e[1],n[o++]=e[2],n[o++]=e[3],n[o++]=e[4],n[o++]=e[5],n[o++]=e[6],n[o++]=e[7],n[o++]=e[8],n},s.unpack=function(e,o,i){return t.defined("array",e),o=r(o,0),n(i)||(i=new s),i[0]=e[o++],i[1]=e[o++],i[2]=e[o++],i[3]=e[o++],i[4]=e[o++],i[5]=e[o++],i[6]=e[o++],i[7]=e[o++],i[8]=e[o++],i},s.clone=function(e,t){return n(e)?n(t)?(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t):new s(e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]):void 0},s.fromArray=function(e,o,i){return t.defined("array",e),o=r(o,0),n(i)||(i=new s),i[0]=e[o],i[1]=e[o+1],i[2]=e[o+2],i[3]=e[o+3],i[4]=e[o+4],i[5]=e[o+5],i[6]=e[o+6],i[7]=e[o+7],i[8]=e[o+8],i},s.fromColumnMajorArray=function(e,r){return t.defined("values",e),s.clone(e,r)},s.fromRowMajorArray=function(e,r){return t.defined("values",e),n(r)?(r[0]=e[0],r[1]=e[3],r[2]=e[6],r[3]=e[1],r[4]=e[4],r[5]=e[7],r[6]=e[2],r[7]=e[5],r[8]=e[8],r):new s(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])},s.fromQuaternion=function(e,r){t.typeOf.object("quaternion",e);var o=e.x*e.x,i=e.x*e.y,a=e.x*e.z,u=e.x*e.w,c=e.y*e.y,l=e.y*e.z,f=e.y*e.w,E=e.z*e.z,h=e.z*e.w,d=e.w*e.w,p=o-c-E+d,_=2*(i-h),m=2*(a+f),O=2*(i+h),R=-o+c-E+d,y=2*(l-u),T=2*(a-f),A=2*(l+u),S=-o-c+E+d;return n(r)?(r[0]=p,r[1]=O,r[2]=T,r[3]=_,r[4]=R,r[5]=A,r[6]=m,r[7]=y,r[8]=S,r):new s(p,_,m,O,R,y,T,A,S)},s.fromHeadingPitchRoll=function(e,r){t.typeOf.object("headingPitchRoll",e);var o=Math.cos(-e.pitch),i=Math.cos(-e.heading),a=Math.cos(e.roll),u=Math.sin(-e.pitch),c=Math.sin(-e.heading),l=Math.sin(e.roll),f=o*i,E=-a*c+l*u*i,h=l*c+a*u*i,d=o*c,p=a*i+l*u*c,_=-l*i+a*u*c,m=-u,O=l*o,R=a*o;return n(r)?(r[0]=f,r[1]=d,r[2]=m,r[3]=E,r[4]=p,r[5]=O,r[6]=h,r[7]=_,r[8]=R,r):new s(f,E,h,d,p,_,m,O,R)},s.fromScale=function(e,r){return t.typeOf.object("scale",e),n(r)?(r[0]=e.x,r[1]=0,r[2]=0,r[3]=0,r[4]=e.y,r[5]=0,r[6]=0,r[7]=0,r[8]=e.z,r):new s(e.x,0,0,0,e.y,0,0,0,e.z)},s.fromUniformScale=function(e,r){return t.typeOf.number("scale",e),n(r)?(r[0]=e,r[1]=0,r[2]=0,r[3]=0,r[4]=e,r[5]=0,r[6]=0,r[7]=0,r[8]=e,r):new s(e,0,0,0,e,0,0,0,e)},s.fromCrossProduct=function(e,r){return t.typeOf.object("vector",e),n(r)?(r[0]=0,r[1]=e.z,r[2]=-e.y,r[3]=-e.z,r[4]=0,r[5]=e.x,r[6]=e.y,r[7]=-e.x,r[8]=0,r):new s(0,-e.z,e.y,e.z,0,-e.x,-e.y,e.x,0)},s.fromRotationX=function(e,r){t.typeOf.number("angle",e);var o=Math.cos(e),i=Math.sin(e);return n(r)?(r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=o,r[5]=i,r[6]=0,r[7]=-i,r[8]=o,r):new s(1,0,0,0,o,-i,0,i,o)},s.fromRotationY=function(e,r){t.typeOf.number("angle",e);var o=Math.cos(e),i=Math.sin(e);return n(r)?(r[0]=o,r[1]=0,r[2]=-i,r[3]=0,r[4]=1,r[5]=0,r[6]=i,r[7]=0,r[8]=o,r):new s(o,0,i,0,1,0,-i,0,o)},s.fromRotationZ=function(e,r){t.typeOf.number("angle",e);var o=Math.cos(e),i=Math.sin(e);return n(r)?(r[0]=o,r[1]=i,r[2]=0,r[3]=-i,r[4]=o,r[5]=0,r[6]=0,r[7]=0,r[8]=1,r):new s(o,-i,0,i,o,0,0,0,1)},s.toArray=function(e,r){return t.typeOf.object("matrix",e),n(r)?(r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r[4]=e[4],r[5]=e[5],r[6]=e[6],r[7]=e[7],r[8]=e[8],r):[e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8]]},s.getElementIndex=function(e,r){return t.typeOf.number.greaterThanOrEquals("row",r,0),t.typeOf.number.lessThanOrEquals("row",r,2),t.typeOf.number.greaterThanOrEquals("column",e,0),t.typeOf.number.lessThanOrEquals("column",e,2),3*e+r},s.getColumn=function(e,r,n){t.typeOf.object("matrix",e),t.typeOf.number.greaterThanOrEquals("index",r,0),t.typeOf.number.lessThanOrEquals("index",r,2),t.typeOf.object("result",n);var o=3*r,i=e[o],a=e[o+1],u=e[o+2];return n.x=i,n.y=a,n.z=u,n},s.setColumn=function(e,r,n,o){t.typeOf.object("matrix",e),t.typeOf.number.greaterThanOrEquals("index",r,0),t.typeOf.number.lessThanOrEquals("index",r,2),t.typeOf.object("cartesian",n),t.typeOf.object("result",o),o=s.clone(e,o);var i=3*r;return o[i]=n.x,o[i+1]=n.y,o[i+2]=n.z,o},s.getRow=function(e,r,n){t.typeOf.object("matrix",e),t.typeOf.number.greaterThanOrEquals("index",r,0),t.typeOf.number.lessThanOrEquals("index",r,2),t.typeOf.object("result",n);var o=e[r],i=e[r+3],a=e[r+6];return n.x=o,n.y=i,n.z=a,n},s.setRow=function(e,r,n,o){return t.typeOf.object("matrix",e),t.typeOf.number.greaterThanOrEquals("index",r,0),t.typeOf.number.lessThanOrEquals("index",r,2),t.typeOf.object("cartesian",n),t.typeOf.object("result",o),o=s.clone(e,o),o[r]=n.x,o[r+3]=n.y,o[r+6]=n.z,o};var E=new e;s.getScale=function(r,n){return t.typeOf.object("matrix",r),t.typeOf.object("result",n),n.x=e.magnitude(e.fromElements(r[0],r[1],r[2],E)),n.y=e.magnitude(e.fromElements(r[3],r[4],r[5],E)),n.z=e.magnitude(e.fromElements(r[6],r[7],r[8],E)),n};var h=new e;s.getMaximumScale=function(t){return s.getScale(t,h),e.maximumComponent(h)},s.multiply=function(e,r,n){t.typeOf.object("left",e),t.typeOf.object("right",r),t.typeOf.object("result",n);var o=e[0]*r[0]+e[3]*r[1]+e[6]*r[2],i=e[1]*r[0]+e[4]*r[1]+e[7]*r[2],a=e[2]*r[0]+e[5]*r[1]+e[8]*r[2],u=e[0]*r[3]+e[3]*r[4]+e[6]*r[5],s=e[1]*r[3]+e[4]*r[4]+e[7]*r[5],c=e[2]*r[3]+e[5]*r[4]+e[8]*r[5],l=e[0]*r[6]+e[3]*r[7]+e[6]*r[8],f=e[1]*r[6]+e[4]*r[7]+e[7]*r[8],E=e[2]*r[6]+e[5]*r[7]+e[8]*r[8];return n[0]=o,n[1]=i,n[2]=a,n[3]=u,n[4]=s,n[5]=c,n[6]=l,n[7]=f,n[8]=E,n},s.add=function(e,r,n){return t.typeOf.object("left",e),t.typeOf.object("right",r),t.typeOf.object("result",n),n[0]=e[0]+r[0],n[1]=e[1]+r[1],n[2]=e[2]+r[2],n[3]=e[3]+r[3],n[4]=e[4]+r[4],n[5]=e[5]+r[5],n[6]=e[6]+r[6],
n[7]=e[7]+r[7],n[8]=e[8]+r[8],n},s.subtract=function(e,r,n){return t.typeOf.object("left",e),t.typeOf.object("right",r),t.typeOf.object("result",n),n[0]=e[0]-r[0],n[1]=e[1]-r[1],n[2]=e[2]-r[2],n[3]=e[3]-r[3],n[4]=e[4]-r[4],n[5]=e[5]-r[5],n[6]=e[6]-r[6],n[7]=e[7]-r[7],n[8]=e[8]-r[8],n},s.multiplyByVector=function(e,r,n){t.typeOf.object("matrix",e),t.typeOf.object("cartesian",r),t.typeOf.object("result",n);var o=r.x,i=r.y,a=r.z,u=e[0]*o+e[3]*i+e[6]*a,s=e[1]*o+e[4]*i+e[7]*a,c=e[2]*o+e[5]*i+e[8]*a;return n.x=u,n.y=s,n.z=c,n},s.multiplyByScalar=function(e,r,n){return t.typeOf.object("matrix",e),t.typeOf.number("scalar",r),t.typeOf.object("result",n),n[0]=e[0]*r,n[1]=e[1]*r,n[2]=e[2]*r,n[3]=e[3]*r,n[4]=e[4]*r,n[5]=e[5]*r,n[6]=e[6]*r,n[7]=e[7]*r,n[8]=e[8]*r,n},s.multiplyByScale=function(e,r,n){return t.typeOf.object("matrix",e),t.typeOf.object("scale",r),t.typeOf.object("result",n),n[0]=e[0]*r.x,n[1]=e[1]*r.x,n[2]=e[2]*r.x,n[3]=e[3]*r.y,n[4]=e[4]*r.y,n[5]=e[5]*r.y,n[6]=e[6]*r.z,n[7]=e[7]*r.z,n[8]=e[8]*r.z,n},s.negate=function(e,r){return t.typeOf.object("matrix",e),t.typeOf.object("result",r),r[0]=-e[0],r[1]=-e[1],r[2]=-e[2],r[3]=-e[3],r[4]=-e[4],r[5]=-e[5],r[6]=-e[6],r[7]=-e[7],r[8]=-e[8],r},s.transpose=function(e,r){t.typeOf.object("matrix",e),t.typeOf.object("result",r);var n=e[0],o=e[3],i=e[6],a=e[1],u=e[4],s=e[7],c=e[2],l=e[5],f=e[8];return r[0]=n,r[1]=o,r[2]=i,r[3]=a,r[4]=u,r[5]=s,r[6]=c,r[7]=l,r[8]=f,r};var d=[1,0,0],p=[2,2,1],_=new s,m=new s;return s.computeEigenDecomposition=function(e,r){t.typeOf.object("matrix",e);var o=u.EPSILON20,i=10,a=0,E=0;n(r)||(r={});for(var h=r.unitary=s.clone(s.IDENTITY,r.unitary),d=r.diagonal=s.clone(e,r.diagonal),p=o*c(d);i>E&&l(d)>p;)f(d,_),s.transpose(_,m),s.multiply(d,_,d),s.multiply(m,d,d),s.multiply(h,_,h),++a>2&&(++E,a=0);return r},s.abs=function(e,r){return t.typeOf.object("matrix",e),t.typeOf.object("result",r),r[0]=Math.abs(e[0]),r[1]=Math.abs(e[1]),r[2]=Math.abs(e[2]),r[3]=Math.abs(e[3]),r[4]=Math.abs(e[4]),r[5]=Math.abs(e[5]),r[6]=Math.abs(e[6]),r[7]=Math.abs(e[7]),r[8]=Math.abs(e[8]),r},s.determinant=function(e){t.typeOf.object("matrix",e);var r=e[0],n=e[3],o=e[6],i=e[1],a=e[4],u=e[7],s=e[2],c=e[5],l=e[8];return r*(a*l-c*u)+i*(c*o-n*l)+s*(n*u-a*o)},s.inverse=function(e,r){t.typeOf.object("matrix",e),t.typeOf.object("result",r);var n=e[0],o=e[1],a=e[2],c=e[3],l=e[4],f=e[5],E=e[6],h=e[7],d=e[8],p=s.determinant(e);if(Math.abs(p)<=u.EPSILON15)throw new i("matrix is not invertible");r[0]=l*d-h*f,r[1]=h*a-o*d,r[2]=o*f-l*a,r[3]=E*f-c*d,r[4]=n*d-E*a,r[5]=c*a-n*f,r[6]=c*h-E*l,r[7]=E*o-n*h,r[8]=n*l-c*o;var _=1/p;return s.multiplyByScalar(r,_,r)},s.equals=function(e,t){return e===t||n(e)&&n(t)&&e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]},s.equalsEpsilon=function(e,r,o){return t.typeOf.number("epsilon",o),e===r||n(e)&&n(r)&&Math.abs(e[0]-r[0])<=o&&Math.abs(e[1]-r[1])<=o&&Math.abs(e[2]-r[2])<=o&&Math.abs(e[3]-r[3])<=o&&Math.abs(e[4]-r[4])<=o&&Math.abs(e[5]-r[5])<=o&&Math.abs(e[6]-r[6])<=o&&Math.abs(e[7]-r[7])<=o&&Math.abs(e[8]-r[8])<=o},s.IDENTITY=a(new s(1,0,0,0,1,0,0,0,1)),s.ZERO=a(new s(0,0,0,0,0,0,0,0,0)),s.COLUMN0ROW0=0,s.COLUMN0ROW1=1,s.COLUMN0ROW2=2,s.COLUMN1ROW0=3,s.COLUMN1ROW1=4,s.COLUMN1ROW2=5,s.COLUMN2ROW0=6,s.COLUMN2ROW1=7,s.COLUMN2ROW2=8,o(s.prototype,{length:{get:function(){return s.packedLength}}}),s.prototype.clone=function(e){return s.clone(this,e)},s.prototype.equals=function(e){return s.equals(this,e)},s.equalsArray=function(e,t,r){return e[0]===t[r]&&e[1]===t[r+1]&&e[2]===t[r+2]&&e[3]===t[r+3]&&e[4]===t[r+4]&&e[5]===t[r+5]&&e[6]===t[r+6]&&e[7]===t[r+7]&&e[8]===t[r+8]},s.prototype.equalsEpsilon=function(e,t){return s.equalsEpsilon(this,e,t)},s.prototype.toString=function(){return"("+this[0]+", "+this[3]+", "+this[6]+")\n("+this[1]+", "+this[4]+", "+this[7]+")\n("+this[2]+", "+this[5]+", "+this[8]+")"},s}),define("Core/Cartesian4",["./Check","./defaultValue","./defined","./DeveloperError","./freezeObject","./Math"],function(e,t,r,n,o,i){"use strict";function a(e,r,n,o){this.x=t(e,0),this.y=t(r,0),this.z=t(n,0),this.w=t(o,0)}a.fromElements=function(e,t,n,o,i){return r(i)?(i.x=e,i.y=t,i.z=n,i.w=o,i):new a(e,t,n,o)},a.fromColor=function(t,n){return e.typeOf.object("color",t),r(n)?(n.x=t.red,n.y=t.green,n.z=t.blue,n.w=t.alpha,n):new a(t.red,t.green,t.blue,t.alpha)},a.clone=function(e,t){return r(e)?r(t)?(t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t):new a(e.x,e.y,e.z,e.w):void 0},a.packedLength=4,a.pack=function(r,n,o){return e.typeOf.object("value",r),e.defined("array",n),o=t(o,0),n[o++]=r.x,n[o++]=r.y,n[o++]=r.z,n[o]=r.w,n},a.unpack=function(n,o,i){return e.defined("array",n),o=t(o,0),r(i)||(i=new a),i.x=n[o++],i.y=n[o++],i.z=n[o++],i.w=n[o],i},a.packArray=function(t,n){e.defined("array",t);var o=t.length;r(n)?n.length=4*o:n=new Array(4*o);for(var i=0;o>i;++i)a.pack(t[i],n,4*i);return n},a.unpackArray=function(t,n){e.defined("array",t);var o=t.length;r(n)?n.length=o/4:n=new Array(o/4);for(var i=0;o>i;i+=4){var u=i/4;n[u]=a.unpack(t,i,n[u])}return n},a.fromArray=a.unpack,a.maximumComponent=function(t){return e.typeOf.object("cartesian",t),Math.max(t.x,t.y,t.z,t.w)},a.minimumComponent=function(t){return e.typeOf.object("cartesian",t),Math.min(t.x,t.y,t.z,t.w)},a.minimumByComponent=function(t,r,n){return e.typeOf.object("first",t),e.typeOf.object("second",r),e.typeOf.object("result",n),n.x=Math.min(t.x,r.x),n.y=Math.min(t.y,r.y),n.z=Math.min(t.z,r.z),n.w=Math.min(t.w,r.w),n},a.maximumByComponent=function(t,r,n){return e.typeOf.object("first",t),e.typeOf.object("second",r),e.typeOf.object("result",n),n.x=Math.max(t.x,r.x),n.y=Math.max(t.y,r.y),n.z=Math.max(t.z,r.z),n.w=Math.max(t.w,r.w),n},a.magnitudeSquared=function(t){return e.typeOf.object("cartesian",t),t.x*t.x+t.y*t.y+t.z*t.z+t.w*t.w},a.magnitude=function(e){return Math.sqrt(a.magnitudeSquared(e))};var u=new a;a.distance=function(t,r){return e.typeOf.object("left",t),e.typeOf.object("right",r),a.subtract(t,r,u),a.magnitude(u)},a.distanceSquared=function(t,r){return e.typeOf.object("left",t),e.typeOf.object("right",r),a.subtract(t,r,u),a.magnitudeSquared(u)},a.normalize=function(t,r){e.typeOf.object("cartesian",t),e.typeOf.object("result",r);var o=a.magnitude(t);if(r.x=t.x/o,r.y=t.y/o,r.z=t.z/o,r.w=t.w/o,isNaN(r.x)||isNaN(r.y)||isNaN(r.z)||isNaN(r.w))throw new n("normalized result is not a number");return r},a.dot=function(t,r){return e.typeOf.object("left",t),e.typeOf.object("right",r),t.x*r.x+t.y*r.y+t.z*r.z+t.w*r.w},a.multiplyComponents=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x*r.x,n.y=t.y*r.y,n.z=t.z*r.z,n.w=t.w*r.w,n},a.divideComponents=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x/r.x,n.y=t.y/r.y,n.z=t.z/r.z,n.w=t.w/r.w,n},a.add=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x+r.x,n.y=t.y+r.y,n.z=t.z+r.z,n.w=t.w+r.w,n},a.subtract=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.x=t.x-r.x,n.y=t.y-r.y,n.z=t.z-r.z,n.w=t.w-r.w,n},a.multiplyByScalar=function(t,r,n){return e.typeOf.object("cartesian",t),e.typeOf.number("scalar",r),e.typeOf.object("result",n),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n.w=t.w*r,n},a.divideByScalar=function(t,r,n){return e.typeOf.object("cartesian",t),e.typeOf.number("scalar",r),e.typeOf.object("result",n),n.x=t.x/r,n.y=t.y/r,n.z=t.z/r,n.w=t.w/r,n},a.negate=function(t,r){return e.typeOf.object("cartesian",t),e.typeOf.object("result",r),r.x=-t.x,r.y=-t.y,r.z=-t.z,r.w=-t.w,r},a.abs=function(t,r){return e.typeOf.object("cartesian",t),e.typeOf.object("result",r),r.x=Math.abs(t.x),r.y=Math.abs(t.y),r.z=Math.abs(t.z),r.w=Math.abs(t.w),r};var s=new a;a.lerp=function(t,r,n,o){return e.typeOf.object("start",t),e.typeOf.object("end",r),e.typeOf.number("t",n),e.typeOf.object("result",o),a.multiplyByScalar(r,n,s),o=a.multiplyByScalar(t,1-n,o),a.add(s,o,o)};var c=new a;return a.mostOrthogonalAxis=function(t,r){e.typeOf.object("cartesian",t),e.typeOf.object("result",r);var n=a.normalize(t,c);return a.abs(n,n),r=n.x<=n.y?n.x<=n.z?n.x<=n.w?a.clone(a.UNIT_X,r):a.clone(a.UNIT_W,r):n.z<=n.w?a.clone(a.UNIT_Z,r):a.clone(a.UNIT_W,r):n.y<=n.z?n.y<=n.w?a.clone(a.UNIT_Y,r):a.clone(a.UNIT_W,r):n.z<=n.w?a.clone(a.UNIT_Z,r):a.clone(a.UNIT_W,r)},a.equals=function(e,t){return e===t||r(e)&&r(t)&&e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w},a.equalsArray=function(e,t,r){return e.x===t[r]&&e.y===t[r+1]&&e.z===t[r+2]&&e.w===t[r+3]},a.equalsEpsilon=function(e,t,n,o){return e===t||r(e)&&r(t)&&i.equalsEpsilon(e.x,t.x,n,o)&&i.equalsEpsilon(e.y,t.y,n,o)&&i.equalsEpsilon(e.z,t.z,n,o)&&i.equalsEpsilon(e.w,t.w,n,o)},a.ZERO=o(new a(0,0,0,0)),a.UNIT_X=o(new a(1,0,0,0)),a.UNIT_Y=o(new a(0,1,0,0)),a.UNIT_Z=o(new a(0,0,1,0)),a.UNIT_W=o(new a(0,0,0,1)),a.prototype.clone=function(e){return a.clone(this,e)},a.prototype.equals=function(e){return a.equals(this,e)},a.prototype.equalsEpsilon=function(e,t,r){return a.equalsEpsilon(this,e,t,r)},a.prototype.toString=function(){return"("+this.x+", "+this.y+", "+this.z+", "+this.w+")"},a}),define("Core/RuntimeError",["./defined"],function(e){"use strict";function t(e){this.name="RuntimeError",this.message=e;var t;try{throw new Error}catch(r){t=r.stack}this.stack=t}return e(Object.create)&&(t.prototype=Object.create(Error.prototype),t.prototype.constructor=t),t.prototype.toString=function(){var t=this.name+": "+this.message;return e(this.stack)&&(t+="\n"+this.stack.toString()),t},t}),define("Core/Matrix4",["./Cartesian3","./Cartesian4","./Check","./defaultValue","./defined","./defineProperties","./freezeObject","./Math","./Matrix3","./RuntimeError"],function(e,t,r,n,o,i,a,u,s,c){"use strict";function l(e,t,r,o,i,a,u,s,c,l,f,E,h,d,p,_){this[0]=n(e,0),this[1]=n(i,0),this[2]=n(c,0),this[3]=n(h,0),this[4]=n(t,0),this[5]=n(a,0),this[6]=n(l,0),this[7]=n(d,0),this[8]=n(r,0),this[9]=n(u,0),this[10]=n(f,0),this[11]=n(p,0),this[12]=n(o,0),this[13]=n(s,0),this[14]=n(E,0),this[15]=n(_,0)}l.packedLength=16,l.pack=function(e,t,o){return r.typeOf.object("value",e),r.defined("array",t),o=n(o,0),t[o++]=e[0],t[o++]=e[1],t[o++]=e[2],t[o++]=e[3],t[o++]=e[4],t[o++]=e[5],t[o++]=e[6],t[o++]=e[7],t[o++]=e[8],t[o++]=e[9],t[o++]=e[10],t[o++]=e[11],t[o++]=e[12],t[o++]=e[13],t[o++]=e[14],t[o]=e[15],t},l.unpack=function(e,t,i){return r.defined("array",e),t=n(t,0),o(i)||(i=new l),i[0]=e[t++],i[1]=e[t++],i[2]=e[t++],i[3]=e[t++],i[4]=e[t++],i[5]=e[t++],i[6]=e[t++],i[7]=e[t++],i[8]=e[t++],i[9]=e[t++],i[10]=e[t++],i[11]=e[t++],i[12]=e[t++],i[13]=e[t++],i[14]=e[t++],i[15]=e[t],i},l.clone=function(e,t){return o(e)?o(t)?(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t):new l(e[0],e[4],e[8],e[12],e[1],e[5],e[9],e[13],e[2],e[6],e[10],e[14],e[3],e[7],e[11],e[15]):void 0},l.fromArray=l.unpack,l.fromColumnMajorArray=function(e,t){return r.defined("values",e),l.clone(e,t)},l.fromRowMajorArray=function(e,t){return r.defined("values",e),o(t)?(t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t):new l(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])},l.fromRotationTranslation=function(t,i,a){return r.typeOf.object("rotation",t),i=n(i,e.ZERO),o(a)?(a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=0,a[4]=t[3],a[5]=t[4],a[6]=t[5],a[7]=0,a[8]=t[6],a[9]=t[7],a[10]=t[8],a[11]=0,a[12]=i.x,a[13]=i.y,a[14]=i.z,a[15]=1,a):new l(t[0],t[3],t[6],i.x,t[1],t[4],t[7],i.y,t[2],t[5],t[8],i.z,0,0,0,1)},l.fromTranslationQuaternionRotationScale=function(e,t,n,i){r.typeOf.object("translation",e),r.typeOf.object("rotation",t),r.typeOf.object("scale",n),o(i)||(i=new l);var a=n.x,u=n.y,s=n.z,c=t.x*t.x,f=t.x*t.y,E=t.x*t.z,h=t.x*t.w,d=t.y*t.y,p=t.y*t.z,_=t.y*t.w,m=t.z*t.z,O=t.z*t.w,R=t.w*t.w,y=c-d-m+R,T=2*(f-O),A=2*(E+_),S=2*(f+O),N=-c+d-m+R,C=2*(p-h),g=2*(E-_),I=2*(p+h),b=-c-d+m+R;return i[0]=y*a,i[1]=S*a,i[2]=g*a,i[3]=0,i[4]=T*u,i[5]=N*u,i[6]=I*u,i[7]=0,i[8]=A*s,i[9]=C*s,i[10]=b*s,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,i},l.fromTranslationRotationScale=function(e,t){return r.typeOf.object("translationRotationScale",e),l.fromTranslationQuaternionRotationScale(e.translation,e.rotation,e.scale,t)},l.fromTranslation=function(e,t){return r.typeOf.object("translation",e),l.fromRotationTranslation(s.IDENTITY,e,t)},l.fromScale=function(e,t){return r.typeOf.object("scale",e),o(t)?(t[0]=e.x,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e.y,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e.z,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t):new l(e.x,0,0,0,0,e.y,0,0,0,0,e.z,0,0,0,0,1)},l.fromUniformScale=function(e,t){return r.typeOf.number("scale",e),o(t)?(t[0]=e,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t):new l(e,0,0,0,0,e,0,0,0,0,e,0,0,0,0,1)};var f=new e,E=new e,h=new e;l.fromCamera=function(t,n){r.typeOf.object("camera",t);var i=t.position,a=t.direction,u=t.up;r.typeOf.object("camera.position",i),r.typeOf.object("camera.direction",a),r.typeOf.object("camera.up",u),e.normalize(a,f),e.normalize(e.cross(f,u,E),E),e.normalize(e.cross(E,f,h),h);var s=E.x,c=E.y,d=E.z,p=f.x,_=f.y,m=f.z,O=h.x,R=h.y,y=h.z,T=i.x,A=i.y,S=i.z,N=s*-T+c*-A+d*-S,C=O*-T+R*-A+y*-S,g=p*T+_*A+m*S;return o(n)?(n[0]=s,n[1]=O,n[2]=-p,n[3]=0,n[4]=c,n[5]=R,n[6]=-_,n[7]=0,n[8]=d,n[9]=y,n[10]=-m,n[11]=0,n[12]=N,n[13]=C,n[14]=g,n[15]=1,n):new l(s,c,d,N,O,R,y,C,-p,-_,-m,g,0,0,0,1)},l.computePerspectiveFieldOfView=function(e,t,n,o,i){r.typeOf.number.greaterThan("fovY",e,0),r.typeOf.number.lessThan("fovY",e,Math.PI),r.typeOf.number.greaterThan("near",n,0),r.typeOf.number.greaterThan("far",o,0),r.typeOf.object("result",i);var a=Math.tan(.5*e),u=1/a,s=u/t,c=(o+n)/(n-o),l=2*o*n/(n-o);return i[0]=s,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=u,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=c,i[11]=-1,i[12]=0,i[13]=0,i[14]=l,i[15]=0,i},l.computeOrthographicOffCenter=function(e,t,n,o,i,a,u){r.typeOf.number("left",e),r.typeOf.number("right",t),r.typeOf.number("bottom",n),r.typeOf.number("top",o),r.typeOf.number("near",i),r.typeOf.number("far",a),r.typeOf.object("result",u);var s=1/(t-e),c=1/(o-n),l=1/(a-i),f=-(t+e)*s,E=-(o+n)*c,h=-(a+i)*l;return s*=2,c*=2,l*=-2,u[0]=s,u[1]=0,u[2]=0,u[3]=0,u[4]=0,u[5]=c,u[6]=0,u[7]=0,u[8]=0,u[9]=0,u[10]=l,u[11]=0,u[12]=f,u[13]=E,u[14]=h,u[15]=1,u},l.computePerspectiveOffCenter=function(e,t,n,o,i,a,u){r.typeOf.number("left",e),r.typeOf.number("right",t),r.typeOf.number("bottom",n),r.typeOf.number("top",o),r.typeOf.number("near",i),r.typeOf.number("far",a),r.typeOf.object("result",u);var s=2*i/(t-e),c=2*i/(o-n),l=(t+e)/(t-e),f=(o+n)/(o-n),E=-(a+i)/(a-i),h=-1,d=-2*a*i/(a-i);return u[0]=s,u[1]=0,u[2]=0,u[3]=0,u[4]=0,u[5]=c,u[6]=0,u[7]=0,u[8]=l,u[9]=f,u[10]=E,u[11]=h,u[12]=0,u[13]=0,u[14]=d,u[15]=0,u},l.computeInfinitePerspectiveOffCenter=function(e,t,n,o,i,a){r.typeOf.number("left",e),r.typeOf.number("right",t),r.typeOf.number("bottom",n),r.typeOf.number("top",o),r.typeOf.number("near",i),r.typeOf.object("result",a);var u=2*i/(t-e),s=2*i/(o-n),c=(t+e)/(t-e),l=(o+n)/(o-n),f=-1,E=-1,h=-2*i;return a[0]=u,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=s,a[6]=0,a[7]=0,a[8]=c,a[9]=l,a[10]=f,a[11]=E,a[12]=0,a[13]=0,a[14]=h,a[15]=0,a},l.computeViewportTransformation=function(e,t,o,i){r.typeOf.object("result",i),e=n(e,n.EMPTY_OBJECT);var a=n(e.x,0),u=n(e.y,0),s=n(e.width,0),c=n(e.height,0);t=n(t,0),o=n(o,1);var l=.5*s,f=.5*c,E=.5*(o-t),h=l,d=f,p=E,_=a+l,m=u+f,O=t+E,R=1;return i[0]=h,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=p,i[11]=0,i[12]=_,i[13]=m,i[14]=O,i[15]=R,i},l.computeView=function(t,n,o,i,a){return r.typeOf.object("position",t),r.typeOf.object("direction",n),r.typeOf.object("up",o),r.typeOf.object("right",i),r.typeOf.object("result",a),a[0]=i.x,a[1]=o.x,a[2]=-n.x,a[3]=0,a[4]=i.y,a[5]=o.y,a[6]=-n.y,a[7]=0,a[8]=i.z,a[9]=o.z,a[10]=-n.z,a[11]=0,a[12]=-e.dot(i,t),a[13]=-e.dot(o,t),a[14]=e.dot(n,t),a[15]=1,a},l.toArray=function(e,t){return r.typeOf.object("matrix",e),o(t)?(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t):[e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]]},l.getElementIndex=function(e,t){return r.typeOf.number.greaterThanOrEquals("row",t,0),r.typeOf.number.lessThanOrEquals("row",t,3),r.typeOf.number.greaterThanOrEquals("column",e,0),r.typeOf.number.lessThanOrEquals("column",e,3),4*e+t},l.getColumn=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.number.greaterThanOrEquals("index",t,0),r.typeOf.number.lessThanOrEquals("index",t,3),r.typeOf.object("result",n);var o=4*t,i=e[o],a=e[o+1],u=e[o+2],s=e[o+3];return n.x=i,n.y=a,n.z=u,n.w=s,n},l.setColumn=function(e,t,n,o){r.typeOf.object("matrix",e),r.typeOf.number.greaterThanOrEquals("index",t,0),r.typeOf.number.lessThanOrEquals("index",t,3),r.typeOf.object("cartesian",n),r.typeOf.object("result",o),o=l.clone(e,o);var i=4*t;return o[i]=n.x,o[i+1]=n.y,o[i+2]=n.z,o[i+3]=n.w,o},l.setTranslation=function(e,t,n){return r.typeOf.object("matrix",e),r.typeOf.object("translation",t),r.typeOf.object("result",n),n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],n[4]=e[4],n[5]=e[5],n[6]=e[6],n[7]=e[7],n[8]=e[8],n[9]=e[9],n[10]=e[10],n[11]=e[11],n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=e[15],n},l.getRow=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.number.greaterThanOrEquals("index",t,0),r.typeOf.number.lessThanOrEquals("index",t,3),r.typeOf.object("result",n);var o=e[t],i=e[t+4],a=e[t+8],u=e[t+12];return n.x=o,n.y=i,n.z=a,n.w=u,n},l.setRow=function(e,t,n,o){return r.typeOf.object("matrix",e),r.typeOf.number.greaterThanOrEquals("index",t,0),r.typeOf.number.lessThanOrEquals("index",t,3),r.typeOf.object("cartesian",n),r.typeOf.object("result",o),o=l.clone(e,o),o[t]=n.x,o[t+4]=n.y,o[t+8]=n.z,o[t+12]=n.w,o};var d=new e;l.getScale=function(t,n){return r.typeOf.object("matrix",t),r.typeOf.object("result",n),n.x=e.magnitude(e.fromElements(t[0],t[1],t[2],d)),n.y=e.magnitude(e.fromElements(t[4],t[5],t[6],d)),n.z=e.magnitude(e.fromElements(t[8],t[9],t[10],d)),n};var p=new e;l.getMaximumScale=function(t){return l.getScale(t,p),e.maximumComponent(p)},l.multiply=function(e,t,n){r.typeOf.object("left",e),r.typeOf.object("right",t),r.typeOf.object("result",n);var o=e[0],i=e[1],a=e[2],u=e[3],s=e[4],c=e[5],l=e[6],f=e[7],E=e[8],h=e[9],d=e[10],p=e[11],_=e[12],m=e[13],O=e[14],R=e[15],y=t[0],T=t[1],A=t[2],S=t[3],N=t[4],C=t[5],g=t[6],I=t[7],b=t[8],M=t[9],w=t[10],v=t[11],F=t[12],L=t[13],P=t[14],D=t[15],U=o*y+s*T+E*A+_*S,B=i*y+c*T+h*A+m*S,x=a*y+l*T+d*A+O*S,G=u*y+f*T+p*A+R*S,q=o*N+s*C+E*g+_*I,j=i*N+c*C+h*g+m*I,z=a*N+l*C+d*g+O*I,V=u*N+f*C+p*g+R*I,H=o*b+s*M+E*w+_*v,X=i*b+c*M+h*w+m*v,W=a*b+l*M+d*w+O*v,Y=u*b+f*M+p*w+R*v,K=o*F+s*L+E*P+_*D,k=i*F+c*L+h*P+m*D,Z=a*F+l*L+d*P+O*D,Q=u*F+f*L+p*P+R*D;return n[0]=U,n[1]=B,n[2]=x,n[3]=G,n[4]=q,n[5]=j,n[6]=z,n[7]=V,n[8]=H,n[9]=X,n[10]=W,n[11]=Y,n[12]=K,n[13]=k,n[14]=Z,n[15]=Q,n},l.add=function(e,t,n){return r.typeOf.object("left",e),r.typeOf.object("right",t),r.typeOf.object("result",n),n[0]=e[0]+t[0],n[1]=e[1]+t[1],n[2]=e[2]+t[2],n[3]=e[3]+t[3],n[4]=e[4]+t[4],n[5]=e[5]+t[5],n[6]=e[6]+t[6],n[7]=e[7]+t[7],n[8]=e[8]+t[8],n[9]=e[9]+t[9],n[10]=e[10]+t[10],n[11]=e[11]+t[11],n[12]=e[12]+t[12],n[13]=e[13]+t[13],n[14]=e[14]+t[14],n[15]=e[15]+t[15],n},l.subtract=function(e,t,n){return r.typeOf.object("left",e),r.typeOf.object("right",t),r.typeOf.object("result",n),n[0]=e[0]-t[0],n[1]=e[1]-t[1],n[2]=e[2]-t[2],n[3]=e[3]-t[3],n[4]=e[4]-t[4],n[5]=e[5]-t[5],n[6]=e[6]-t[6],n[7]=e[7]-t[7],n[8]=e[8]-t[8],n[9]=e[9]-t[9],n[10]=e[10]-t[10],n[11]=e[11]-t[11],n[12]=e[12]-t[12],n[13]=e[13]-t[13],n[14]=e[14]-t[14],n[15]=e[15]-t[15],n},l.multiplyTransformation=function(e,t,n){r.typeOf.object("left",e),r.typeOf.object("right",t),r.typeOf.object("result",n);var o=e[0],i=e[1],a=e[2],u=e[4],s=e[5],c=e[6],l=e[8],f=e[9],E=e[10],h=e[12],d=e[13],p=e[14],_=t[0],m=t[1],O=t[2],R=t[4],y=t[5],T=t[6],A=t[8],S=t[9],N=t[10],C=t[12],g=t[13],I=t[14],b=o*_+u*m+l*O,M=i*_+s*m+f*O,w=a*_+c*m+E*O,v=o*R+u*y+l*T,F=i*R+s*y+f*T,L=a*R+c*y+E*T,P=o*A+u*S+l*N,D=i*A+s*S+f*N,U=a*A+c*S+E*N,B=o*C+u*g+l*I+h,x=i*C+s*g+f*I+d,G=a*C+c*g+E*I+p;return n[0]=b,n[1]=M,n[2]=w,n[3]=0,n[4]=v,n[5]=F,n[6]=L,n[7]=0,n[8]=P,n[9]=D,n[10]=U,n[11]=0,n[12]=B,n[13]=x,n[14]=G,n[15]=1,n},l.multiplyByMatrix3=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.object("rotation",t),r.typeOf.object("result",n);var o=e[0],i=e[1],a=e[2],u=e[4],s=e[5],c=e[6],l=e[8],f=e[9],E=e[10],h=t[0],d=t[1],p=t[2],_=t[3],m=t[4],O=t[5],R=t[6],y=t[7],T=t[8],A=o*h+u*d+l*p,S=i*h+s*d+f*p,N=a*h+c*d+E*p,C=o*_+u*m+l*O,g=i*_+s*m+f*O,I=a*_+c*m+E*O,b=o*R+u*y+l*T,M=i*R+s*y+f*T,w=a*R+c*y+E*T;return n[0]=A,n[1]=S,n[2]=N,n[3]=0,n[4]=C,n[5]=g,n[6]=I,n[7]=0,n[8]=b,n[9]=M,n[10]=w,n[11]=0,n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=e[15],n},l.multiplyByTranslation=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.object("translation",t),r.typeOf.object("result",n);var o=t.x,i=t.y,a=t.z,u=o*e[0]+i*e[4]+a*e[8]+e[12],s=o*e[1]+i*e[5]+a*e[9]+e[13],c=o*e[2]+i*e[6]+a*e[10]+e[14];return n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],n[4]=e[4],n[5]=e[5],n[6]=e[6],n[7]=e[7],n[8]=e[8],n[9]=e[9],n[10]=e[10],n[11]=e[11],n[12]=u,n[13]=s,n[14]=c,n[15]=e[15],n};var _=new e;l.multiplyByUniformScale=function(e,t,n){return r.typeOf.object("matrix",e),r.typeOf.number("scale",t),r.typeOf.object("result",n),_.x=t,_.y=t,_.z=t,l.multiplyByScale(e,_,n)},l.multiplyByScale=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.object("scale",t),r.typeOf.object("result",n);var o=t.x,i=t.y,a=t.z;return 1===o&&1===i&&1===a?l.clone(e,n):(n[0]=o*e[0],n[1]=o*e[1],n[2]=o*e[2],n[3]=0,n[4]=i*e[4],n[5]=i*e[5],n[6]=i*e[6],n[7]=0,n[8]=a*e[8],n[9]=a*e[9],n[10]=a*e[10],n[11]=0,n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=1,n)},l.multiplyByVector=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.object("cartesian",t),r.typeOf.object("result",n);var o=t.x,i=t.y,a=t.z,u=t.w,s=e[0]*o+e[4]*i+e[8]*a+e[12]*u,c=e[1]*o+e[5]*i+e[9]*a+e[13]*u,l=e[2]*o+e[6]*i+e[10]*a+e[14]*u,f=e[3]*o+e[7]*i+e[11]*a+e[15]*u;return n.x=s,n.y=c,n.z=l,n.w=f,n},l.multiplyByPointAsVector=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.object("cartesian",t),r.typeOf.object("result",n);var o=t.x,i=t.y,a=t.z,u=e[0]*o+e[4]*i+e[8]*a,s=e[1]*o+e[5]*i+e[9]*a,c=e[2]*o+e[6]*i+e[10]*a;return n.x=u,n.y=s,n.z=c,n},l.multiplyByPoint=function(e,t,n){r.typeOf.object("matrix",e),r.typeOf.object("cartesian",t),r.typeOf.object("result",n);var o=t.x,i=t.y,a=t.z,u=e[0]*o+e[4]*i+e[8]*a+e[12],s=e[1]*o+e[5]*i+e[9]*a+e[13],c=e[2]*o+e[6]*i+e[10]*a+e[14];return n.x=u,n.y=s,n.z=c,n},l.multiplyByScalar=function(e,t,n){return r.typeOf.object("matrix",e),r.typeOf.number("scalar",t),r.typeOf.object("result",n),n[0]=e[0]*t,n[1]=e[1]*t,n[2]=e[2]*t,n[3]=e[3]*t,n[4]=e[4]*t,n[5]=e[5]*t,n[6]=e[6]*t,n[7]=e[7]*t,n[8]=e[8]*t,n[9]=e[9]*t,n[10]=e[10]*t,n[11]=e[11]*t,n[12]=e[12]*t,n[13]=e[13]*t,n[14]=e[14]*t,n[15]=e[15]*t,n},l.multiplyByPlane=function(n,o,i){r.typeOf.object("matrix",n),r.typeOf.object("plane",o),r.typeOf.object("result",i);var a=new l,u=new l;l.inverse(n,a),l.transpose(a,u);var s=new t(o.normal.x,o.normal.y,o.normal.z,o.distance);l.multiplyByVector(u,s,s),i.normal.x=s.x,i.normal.y=s.y,i.normal.z=s.z;var c=e.magnitude(i.normal);return e.normalize(i.normal,i.normal),i.distance=s.w/c,i},l.negate=function(e,t){return r.typeOf.object("matrix",e),r.typeOf.object("result",t),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t},l.transpose=function(e,t){r.typeOf.object("matrix",e),r.typeOf.object("result",t);var n=e[1],o=e[2],i=e[3],a=e[6],u=e[7],s=e[11];return t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=n,t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=o,t[9]=a,t[10]=e[10],t[11]=e[14],t[12]=i,t[13]=u,t[14]=s,t[15]=e[15],t},l.abs=function(e,t){return r.typeOf.object("matrix",e),r.typeOf.object("result",t),t[0]=Math.abs(e[0]),t[1]=Math.abs(e[1]),t[2]=Math.abs(e[2]),t[3]=Math.abs(e[3]),t[4]=Math.abs(e[4]),t[5]=Math.abs(e[5]),t[6]=Math.abs(e[6]),t[7]=Math.abs(e[7]),t[8]=Math.abs(e[8]),t[9]=Math.abs(e[9]),t[10]=Math.abs(e[10]),t[11]=Math.abs(e[11]),t[12]=Math.abs(e[12]),t[13]=Math.abs(e[13]),t[14]=Math.abs(e[14]),t[15]=Math.abs(e[15]),t},l.equals=function(e,t){return e===t||o(e)&&o(t)&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[3]===t[3]&&e[7]===t[7]&&e[11]===t[11]&&e[15]===t[15]},l.equalsEpsilon=function(e,t,n){return r.typeOf.number("epsilon",n),e===t||o(e)&&o(t)&&Math.abs(e[0]-t[0])<=n&&Math.abs(e[1]-t[1])<=n&&Math.abs(e[2]-t[2])<=n&&Math.abs(e[3]-t[3])<=n&&Math.abs(e[4]-t[4])<=n&&Math.abs(e[5]-t[5])<=n&&Math.abs(e[6]-t[6])<=n&&Math.abs(e[7]-t[7])<=n&&Math.abs(e[8]-t[8])<=n&&Math.abs(e[9]-t[9])<=n&&Math.abs(e[10]-t[10])<=n&&Math.abs(e[11]-t[11])<=n&&Math.abs(e[12]-t[12])<=n&&Math.abs(e[13]-t[13])<=n&&Math.abs(e[14]-t[14])<=n&&Math.abs(e[15]-t[15])<=n},l.getTranslation=function(e,t){return r.typeOf.object("matrix",e),r.typeOf.object("result",t),t.x=e[12],t.y=e[13],t.z=e[14],t},l.getRotation=function(e,t){return r.typeOf.object("matrix",e),r.typeOf.object("result",t),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t};var m=new s,O=new s,R=new t,y=new t(0,0,0,1);return l.inverse=function(e,n){if(r.typeOf.object("matrix",e),r.typeOf.object("result",n),s.equalsEpsilon(l.getRotation(e,m),O,u.EPSILON7)&&t.equals(l.getRow(e,3,R),y))return n[0]=0,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=0,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=0,n[11]=0,n[12]=-e[12],n[13]=-e[13],n[14]=-e[14],n[15]=1,n;var o=e[0],i=e[4],a=e[8],f=e[12],E=e[1],h=e[5],d=e[9],p=e[13],_=e[2],T=e[6],A=e[10],S=e[14],N=e[3],C=e[7],g=e[11],I=e[15],b=A*I,M=S*g,w=T*I,v=S*C,F=T*g,L=A*C,P=_*I,D=S*N,U=_*g,B=A*N,x=_*C,G=T*N,q=b*h+v*d+F*p-(M*h+w*d+L*p),j=M*E+P*d+B*p-(b*E+D*d+U*p),z=w*E+D*h+x*p-(v*E+P*h+G*p),V=L*E+U*h+G*d-(F*E+B*h+x*d),H=M*i+w*a+L*f-(b*i+v*a+F*f),X=b*o+D*a+U*f-(M*o+P*a+B*f),W=v*o+P*i+G*f-(w*o+D*i+x*f),Y=F*o+B*i+x*a-(L*o+U*i+G*a);b=a*p,M=f*d,w=i*p,v=f*h,F=i*d,L=a*h,P=o*p,D=f*E,U=o*d,B=a*E,x=o*h,G=i*E;var K=b*C+v*g+F*I-(M*C+w*g+L*I),k=M*N+P*g+B*I-(b*N+D*g+U*I),Z=w*N+D*C+x*I-(v*N+P*C+G*I),Q=L*N+U*C+G*g-(F*N+B*C+x*g),J=w*A+L*S+M*T-(F*S+b*T+v*A),$=U*S+b*_+D*A-(P*A+B*S+M*_),ee=P*T+G*S+v*_-(x*S+w*_+D*T),te=x*A+F*_+B*T-(U*T+G*A+L*_),re=o*q+i*j+a*z+f*V;if(Math.abs(re)<u.EPSILON20)throw new c("matrix is not invertible because its determinate is zero.");return re=1/re,n[0]=q*re,n[1]=j*re,n[2]=z*re,n[3]=V*re,n[4]=H*re,n[5]=X*re,n[6]=W*re,n[7]=Y*re,n[8]=K*re,n[9]=k*re,n[10]=Z*re,n[11]=Q*re,n[12]=J*re,n[13]=$*re,n[14]=ee*re,n[15]=te*re,n},l.inverseTransformation=function(e,t){r.typeOf.object("matrix",e),r.typeOf.object("result",t);var n=e[0],o=e[1],i=e[2],a=e[4],u=e[5],s=e[6],c=e[8],l=e[9],f=e[10],E=e[12],h=e[13],d=e[14],p=-n*E-o*h-i*d,_=-a*E-u*h-s*d,m=-c*E-l*h-f*d;return t[0]=n,t[1]=a,t[2]=c,t[3]=0,t[4]=o,t[5]=u,t[6]=l,t[7]=0,t[8]=i,t[9]=s,t[10]=f,t[11]=0,t[12]=p,t[13]=_,t[14]=m,t[15]=1,t},l.IDENTITY=a(new l(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)),l.ZERO=a(new l(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)),l.COLUMN0ROW0=0,l.COLUMN0ROW1=1,l.COLUMN0ROW2=2,l.COLUMN0ROW3=3,l.COLUMN1ROW0=4,l.COLUMN1ROW1=5,l.COLUMN1ROW2=6,l.COLUMN1ROW3=7,l.COLUMN2ROW0=8,l.COLUMN2ROW1=9,l.COLUMN2ROW2=10,l.COLUMN2ROW3=11,l.COLUMN3ROW0=12,l.COLUMN3ROW1=13,l.COLUMN3ROW2=14,l.COLUMN3ROW3=15,i(l.prototype,{length:{get:function(){return l.packedLength}}}),l.prototype.clone=function(e){return l.clone(this,e)},l.prototype.equals=function(e){return l.equals(this,e)},l.equalsArray=function(e,t,r){return e[0]===t[r]&&e[1]===t[r+1]&&e[2]===t[r+2]&&e[3]===t[r+3]&&e[4]===t[r+4]&&e[5]===t[r+5]&&e[6]===t[r+6]&&e[7]===t[r+7]&&e[8]===t[r+8]&&e[9]===t[r+9]&&e[10]===t[r+10]&&e[11]===t[r+11]&&e[12]===t[r+12]&&e[13]===t[r+13]&&e[14]===t[r+14]&&e[15]===t[r+15]},l.prototype.equalsEpsilon=function(e,t){return l.equalsEpsilon(this,e,t)},l.prototype.toString=function(){return"("+this[0]+", "+this[4]+", "+this[8]+", "+this[12]+")\n("+this[1]+", "+this[5]+", "+this[9]+", "+this[13]+")\n("+this[2]+", "+this[6]+", "+this[10]+", "+this[14]+")\n("+this[3]+", "+this[7]+", "+this[11]+", "+this[15]+")"},l}),define("Core/Rectangle",["./Cartographic","./Check","./defaultValue","./defined","./defineProperties","./Ellipsoid","./freezeObject","./Math"],function(e,t,r,n,o,i,a,u){"use strict";function s(e,t,n,o){this.west=r(e,0),this.south=r(t,0),this.east=r(n,0),this.north=r(o,0)}o(s.prototype,{width:{get:function(){return s.computeWidth(this)}},height:{get:function(){return s.computeHeight(this)}}}),s.packedLength=4,s.pack=function(e,n,o){return t.typeOf.object("value",e),t.defined("array",n),o=r(o,0),n[o++]=e.west,n[o++]=e.south,n[o++]=e.east,n[o]=e.north,n},s.unpack=function(e,o,i){return t.defined("array",e),o=r(o,0),n(i)||(i=new s),i.west=e[o++],i.south=e[o++],i.east=e[o++],i.north=e[o],i},s.computeWidth=function(e){t.typeOf.object("rectangle",e);var r=e.east,n=e.west;return n>r&&(r+=u.TWO_PI),r-n},s.computeHeight=function(e){return t.typeOf.object("rectangle",e),e.north-e.south},s.fromDegrees=function(e,t,o,i,a){return e=u.toRadians(r(e,0)),t=u.toRadians(r(t,0)),o=u.toRadians(r(o,0)),i=u.toRadians(r(i,0)),n(a)?(a.west=e,a.south=t,a.east=o,a.north=i,a):new s(e,t,o,i)},s.fromRadians=function(e,t,o,i,a){return n(a)?(a.west=r(e,0),a.south=r(t,0),a.east=r(o,0),a.north=r(i,0),a):new s(e,t,o,i)},s.fromCartographicArray=function(e,r){t.defined("cartographics",e);for(var o=Number.MAX_VALUE,i=-Number.MAX_VALUE,a=Number.MAX_VALUE,c=-Number.MAX_VALUE,l=Number.MAX_VALUE,f=-Number.MAX_VALUE,E=0,h=e.length;h>E;E++){var d=e[E];o=Math.min(o,d.longitude),i=Math.max(i,d.longitude),l=Math.min(l,d.latitude),f=Math.max(f,d.latitude);var p=d.longitude>=0?d.longitude:d.longitude+u.TWO_PI;a=Math.min(a,p),c=Math.max(c,p)}return i-o>c-a&&(o=a,i=c,i>u.PI&&(i-=u.TWO_PI),o>u.PI&&(o-=u.TWO_PI)),n(r)?(r.west=o,r.south=l,r.east=i,r.north=f,r):new s(o,l,i,f)},s.fromCartesianArray=function(e,o,a){t.defined("cartesians",e),o=r(o,i.WGS84);for(var c=Number.MAX_VALUE,l=-Number.MAX_VALUE,f=Number.MAX_VALUE,E=-Number.MAX_VALUE,h=Number.MAX_VALUE,d=-Number.MAX_VALUE,p=0,_=e.length;_>p;p++){var m=o.cartesianToCartographic(e[p]);c=Math.min(c,m.longitude),l=Math.max(l,m.longitude),h=Math.min(h,m.latitude),d=Math.max(d,m.latitude);var O=m.longitude>=0?m.longitude:m.longitude+u.TWO_PI;f=Math.min(f,O),E=Math.max(E,O)}return l-c>E-f&&(c=f,l=E,l>u.PI&&(l-=u.TWO_PI),c>u.PI&&(c-=u.TWO_PI)),n(a)?(a.west=c,a.south=h,a.east=l,a.north=d,a):new s(c,h,l,d)},s.clone=function(e,t){return n(e)?n(t)?(t.west=e.west,t.south=e.south,t.east=e.east,t.north=e.north,t):new s(e.west,e.south,e.east,e.north):void 0},s.prototype.clone=function(e){return s.clone(this,e)},s.prototype.equals=function(e){return s.equals(this,e)},s.equals=function(e,t){return e===t||n(e)&&n(t)&&e.west===t.west&&e.south===t.south&&e.east===t.east&&e.north===t.north},s.prototype.equalsEpsilon=function(e,r){return t.typeOf.number("epsilon",r),n(e)&&Math.abs(this.west-e.west)<=r&&Math.abs(this.south-e.south)<=r&&Math.abs(this.east-e.east)<=r&&Math.abs(this.north-e.north)<=r},s.validate=function(e){t.typeOf.object("rectangle",e);var r=e.north;t.typeOf.number.greaterThanOrEquals("north",r,-u.PI_OVER_TWO),t.typeOf.number.lessThanOrEquals("north",r,u.PI_OVER_TWO);var n=e.south;t.typeOf.number.greaterThanOrEquals("south",n,-u.PI_OVER_TWO),t.typeOf.number.lessThanOrEquals("south",n,u.PI_OVER_TWO);var o=e.west;t.typeOf.number.greaterThanOrEquals("west",o,-Math.PI),t.typeOf.number.lessThanOrEquals("west",o,Math.PI);var i=e.east;t.typeOf.number.greaterThanOrEquals("east",i,-Math.PI),t.typeOf.number.lessThanOrEquals("east",i,Math.PI)},s.southwest=function(r,o){ | return t.typeOf.object("rectangle",r),n(o)?(o.longitude=r.west,o.latitude=r.south,o.height=0,o):new e(r.west,r.south)},s.northwest=function(r,o){return t.typeOf.object("rectangle",r),n(o)?(o.longitude=r.west,o.latitude=r.north,o.height=0,o):new e(r.west,r.north)},s.northeast=function(r,o){return t.typeOf.object("rectangle",r),n(o)?(o.longitude=r.east,o.latitude=r.north,o.height=0,o):new e(r.east,r.north)},s.southeast=function(r,o){return t.typeOf.object("rectangle",r),n(o)?(o.longitude=r.east,o.latitude=r.south,o.height=0,o):new e(r.east,r.south)},s.center=function(r,o){t.typeOf.object("rectangle",r);var i=r.east,a=r.west;a>i&&(i+=u.TWO_PI);var s=u.negativePiToPi(.5*(a+i)),c=.5*(r.south+r.north);return n(o)?(o.longitude=s,o.latitude=c,o.height=0,o):new e(s,c)},s.intersection=function(e,r,o){t.typeOf.object("rectangle",e),t.typeOf.object("otherRectangle",r);var i=e.east,a=e.west,c=r.east,l=r.west;a>i&&c>0?i+=u.TWO_PI:l>c&&i>0&&(c+=u.TWO_PI),a>i&&0>l?l+=u.TWO_PI:l>c&&0>a&&(a+=u.TWO_PI);var f=u.negativePiToPi(Math.max(a,l)),E=u.negativePiToPi(Math.min(i,c));if(!((e.west<e.east||r.west<r.east)&&f>=E)){var h=Math.max(e.south,r.south),d=Math.min(e.north,r.north);if(!(h>=d))return n(o)?(o.west=f,o.south=h,o.east=E,o.north=d,o):new s(f,h,E,d)}},s.simpleIntersection=function(e,r,o){t.typeOf.object("rectangle",e),t.typeOf.object("otherRectangle",r);var i=Math.max(e.west,r.west),a=Math.max(e.south,r.south),u=Math.min(e.east,r.east),c=Math.min(e.north,r.north);return a>=c||i>=u?void 0:n(o)?(o.west=i,o.south=a,o.east=u,o.north=c,o):new s(i,a,u,c)},s.union=function(e,r,o){t.typeOf.object("rectangle",e),t.typeOf.object("otherRectangle",r),n(o)||(o=new s);var i=e.east,a=e.west,c=r.east,l=r.west;a>i&&c>0?i+=u.TWO_PI:l>c&&i>0&&(c+=u.TWO_PI),a>i&&0>l?l+=u.TWO_PI:l>c&&0>a&&(a+=u.TWO_PI);var f=u.convertLongitudeRange(Math.min(a,l)),E=u.convertLongitudeRange(Math.max(i,c));return o.west=f,o.south=Math.min(e.south,r.south),o.east=E,o.north=Math.max(e.north,r.north),o},s.expand=function(e,r,o){return t.typeOf.object("rectangle",e),t.typeOf.object("cartographic",r),n(o)||(o=new s),o.west=Math.min(e.west,r.longitude),o.south=Math.min(e.south,r.latitude),o.east=Math.max(e.east,r.longitude),o.north=Math.max(e.north,r.latitude),o},s.contains=function(e,r){t.typeOf.object("rectangle",e),t.typeOf.object("cartographic",r);var n=r.longitude,o=r.latitude,i=e.west,a=e.east;return i>a&&(a+=u.TWO_PI,0>n&&(n+=u.TWO_PI)),(n>i||u.equalsEpsilon(n,i,u.EPSILON14))&&(a>n||u.equalsEpsilon(n,a,u.EPSILON14))&&o>=e.south&&o<=e.north};var c=new e;return s.subsample=function(e,o,a,l){t.typeOf.object("rectangle",e),o=r(o,i.WGS84),a=r(a,0),n(l)||(l=[]);var f=0,E=e.north,h=e.south,d=e.east,p=e.west,_=c;_.height=a,_.longitude=p,_.latitude=E,l[f]=o.cartographicToCartesian(_,l[f]),f++,_.longitude=d,l[f]=o.cartographicToCartesian(_,l[f]),f++,_.latitude=h,l[f]=o.cartographicToCartesian(_,l[f]),f++,_.longitude=p,l[f]=o.cartographicToCartesian(_,l[f]),f++,0>E?_.latitude=E:h>0?_.latitude=h:_.latitude=0;for(var m=1;8>m;++m)_.longitude=-Math.PI+m*u.PI_OVER_TWO,s.contains(e,_)&&(l[f]=o.cartographicToCartesian(_,l[f]),f++);return 0===_.latitude&&(_.longitude=p,l[f]=o.cartographicToCartesian(_,l[f]),f++,_.longitude=d,l[f]=o.cartographicToCartesian(_,l[f]),f++),l.length=f,l},s.MAX_VALUE=a(new s(-Math.PI,-u.PI_OVER_TWO,Math.PI,u.PI_OVER_TWO)),s}),define("Core/BoundingSphere",["./Cartesian3","./Cartographic","./Check","./defaultValue","./defined","./Ellipsoid","./GeographicProjection","./Intersect","./Interval","./Matrix3","./Matrix4","./Rectangle"],function(e,t,r,n,o,i,a,u,s,c,l,f){"use strict";function E(t,r){this.center=e.clone(n(t,e.ZERO)),this.radius=n(r,0)}var h=new e,d=new e,p=new e,_=new e,m=new e,O=new e,R=new e,y=new e,T=new e,A=new e,S=new e,N=new e;E.fromPoints=function(t,r){if(o(r)||(r=new E),!o(t)||0===t.length)return r.center=e.clone(e.ZERO,r.center),r.radius=0,r;var n,i=e.clone(t[0],R),a=e.clone(i,h),u=e.clone(i,d),s=e.clone(i,p),c=e.clone(i,_),l=e.clone(i,m),f=e.clone(i,O),C=t.length;for(n=1;C>n;n++){e.clone(t[n],i);var g=i.x,I=i.y,b=i.z;g<a.x&&e.clone(i,a),g>c.x&&e.clone(i,c),I<u.y&&e.clone(i,u),I>l.y&&e.clone(i,l),b<s.z&&e.clone(i,s),b>f.z&&e.clone(i,f)}var M=e.magnitudeSquared(e.subtract(c,a,y)),w=e.magnitudeSquared(e.subtract(l,u,y)),v=e.magnitudeSquared(e.subtract(f,s,y)),F=a,L=c,P=M;w>P&&(P=w,F=u,L=l),v>P&&(P=v,F=s,L=f);var D=T;D.x=.5*(F.x+L.x),D.y=.5*(F.y+L.y),D.z=.5*(F.z+L.z);var U=e.magnitudeSquared(e.subtract(L,D,y)),B=Math.sqrt(U),x=A;x.x=a.x,x.y=u.y,x.z=s.z;var G=S;G.x=c.x,G.y=l.y,G.z=f.z;var q=e.multiplyByScalar(e.add(x,G,y),.5,N),j=0;for(n=0;C>n;n++){e.clone(t[n],i);var z=e.magnitude(e.subtract(i,q,y));z>j&&(j=z);var V=e.magnitudeSquared(e.subtract(i,D,y));if(V>U){var H=Math.sqrt(V);B=.5*(B+H),U=B*B;var X=H-B;D.x=(B*D.x+X*i.x)/H,D.y=(B*D.y+X*i.y)/H,D.z=(B*D.z+X*i.z)/H}}return j>B?(e.clone(D,r.center),r.radius=B):(e.clone(q,r.center),r.radius=j),r};var C=new a,g=new e,I=new e,b=new t,M=new t;E.fromRectangle2D=function(e,t,r){return E.fromRectangleWithHeights2D(e,t,0,0,r)},E.fromRectangleWithHeights2D=function(t,r,i,a,u){if(o(u)||(u=new E),!o(t))return u.center=e.clone(e.ZERO,u.center),u.radius=0,u;r=n(r,C),f.southwest(t,b),b.height=i,f.northeast(t,M),M.height=a;var s=r.project(b,g),c=r.project(M,I),l=c.x-s.x,h=c.y-s.y,d=c.z-s.z;u.radius=.5*Math.sqrt(l*l+h*h+d*d);var p=u.center;return p.x=s.x+.5*l,p.y=s.y+.5*h,p.z=s.z+.5*d,u};var w=[];E.fromRectangle3D=function(t,r,a,u){if(r=n(r,i.WGS84),a=n(a,0),o(u)||(u=new E),!o(t))return u.center=e.clone(e.ZERO,u.center),u.radius=0,u;var s=f.subsample(t,r,a,w);return E.fromPoints(s,u)},E.fromVertices=function(t,i,a,u){if(o(u)||(u=new E),!o(t)||0===t.length)return u.center=e.clone(e.ZERO,u.center),u.radius=0,u;i=n(i,e.ZERO),a=n(a,3),r.typeOf.number.greaterThanOrEquals("stride",a,3);var s=R;s.x=t[0]+i.x,s.y=t[1]+i.y,s.z=t[2]+i.z;var c,l=e.clone(s,h),f=e.clone(s,d),C=e.clone(s,p),g=e.clone(s,_),I=e.clone(s,m),b=e.clone(s,O),M=t.length;for(c=0;M>c;c+=a){var w=t[c]+i.x,v=t[c+1]+i.y,F=t[c+2]+i.z;s.x=w,s.y=v,s.z=F,w<l.x&&e.clone(s,l),w>g.x&&e.clone(s,g),v<f.y&&e.clone(s,f),v>I.y&&e.clone(s,I),F<C.z&&e.clone(s,C),F>b.z&&e.clone(s,b)}var L=e.magnitudeSquared(e.subtract(g,l,y)),P=e.magnitudeSquared(e.subtract(I,f,y)),D=e.magnitudeSquared(e.subtract(b,C,y)),U=l,B=g,x=L;P>x&&(x=P,U=f,B=I),D>x&&(x=D,U=C,B=b);var G=T;G.x=.5*(U.x+B.x),G.y=.5*(U.y+B.y),G.z=.5*(U.z+B.z);var q=e.magnitudeSquared(e.subtract(B,G,y)),j=Math.sqrt(q),z=A;z.x=l.x,z.y=f.y,z.z=C.z;var V=S;V.x=g.x,V.y=I.y,V.z=b.z;var H=e.multiplyByScalar(e.add(z,V,y),.5,N),X=0;for(c=0;M>c;c+=a){s.x=t[c]+i.x,s.y=t[c+1]+i.y,s.z=t[c+2]+i.z;var W=e.magnitude(e.subtract(s,H,y));W>X&&(X=W);var Y=e.magnitudeSquared(e.subtract(s,G,y));if(Y>q){var K=Math.sqrt(Y);j=.5*(j+K),q=j*j;var k=K-j;G.x=(j*G.x+k*s.x)/K,G.y=(j*G.y+k*s.y)/K,G.z=(j*G.z+k*s.z)/K}}return X>j?(e.clone(G,u.center),u.radius=j):(e.clone(H,u.center),u.radius=X),u},E.fromEncodedCartesianVertices=function(t,r,n){if(o(n)||(n=new E),!o(t)||!o(r)||t.length!==r.length||0===t.length)return n.center=e.clone(e.ZERO,n.center),n.radius=0,n;var i=R;i.x=t[0]+r[0],i.y=t[1]+r[1],i.z=t[2]+r[2];var a,u=e.clone(i,h),s=e.clone(i,d),c=e.clone(i,p),l=e.clone(i,_),f=e.clone(i,m),C=e.clone(i,O),g=t.length;for(a=0;g>a;a+=3){var I=t[a]+r[a],b=t[a+1]+r[a+1],M=t[a+2]+r[a+2];i.x=I,i.y=b,i.z=M,I<u.x&&e.clone(i,u),I>l.x&&e.clone(i,l),b<s.y&&e.clone(i,s),b>f.y&&e.clone(i,f),M<c.z&&e.clone(i,c),M>C.z&&e.clone(i,C)}var w=e.magnitudeSquared(e.subtract(l,u,y)),v=e.magnitudeSquared(e.subtract(f,s,y)),F=e.magnitudeSquared(e.subtract(C,c,y)),L=u,P=l,D=w;v>D&&(D=v,L=s,P=f),F>D&&(D=F,L=c,P=C);var U=T;U.x=.5*(L.x+P.x),U.y=.5*(L.y+P.y),U.z=.5*(L.z+P.z);var B=e.magnitudeSquared(e.subtract(P,U,y)),x=Math.sqrt(B),G=A;G.x=u.x,G.y=s.y,G.z=c.z;var q=S;q.x=l.x,q.y=f.y,q.z=C.z;var j=e.multiplyByScalar(e.add(G,q,y),.5,N),z=0;for(a=0;g>a;a+=3){i.x=t[a]+r[a],i.y=t[a+1]+r[a+1],i.z=t[a+2]+r[a+2];var V=e.magnitude(e.subtract(i,j,y));V>z&&(z=V);var H=e.magnitudeSquared(e.subtract(i,U,y));if(H>B){var X=Math.sqrt(H);x=.5*(x+X),B=x*x;var W=X-x;U.x=(x*U.x+W*i.x)/X,U.y=(x*U.y+W*i.y)/X,U.z=(x*U.z+W*i.z)/X}}return z>x?(e.clone(U,n.center),n.radius=x):(e.clone(j,n.center),n.radius=z),n},E.fromCornerPoints=function(t,n,i){r.typeOf.object("corner",t),r.typeOf.object("oppositeCorner",n),o(i)||(i=new E);var a=i.center;return e.add(t,n,a),e.multiplyByScalar(a,.5,a),i.radius=e.distance(a,n),i},E.fromEllipsoid=function(t,n){return r.typeOf.object("ellipsoid",t),o(n)||(n=new E),e.clone(e.ZERO,n.center),n.radius=t.maximumRadius,n};var v=new e;E.fromBoundingSpheres=function(t,r){if(o(r)||(r=new E),!o(t)||0===t.length)return r.center=e.clone(e.ZERO,r.center),r.radius=0,r;var n=t.length;if(1===n)return E.clone(t[0],r);if(2===n)return E.union(t[0],t[1],r);var i,a=[];for(i=0;n>i;i++)a.push(t[i].center);r=E.fromPoints(a,r);var u=r.center,s=r.radius;for(i=0;n>i;i++){var c=t[i];s=Math.max(s,e.distance(u,c.center,v)+c.radius)}return r.radius=s,r};var F=new e,L=new e,P=new e;E.fromOrientedBoundingBox=function(t,n){r.defined("orientedBoundingBox",t),o(n)||(n=new E);var i=t.halfAxes,a=c.getColumn(i,0,F),u=c.getColumn(i,1,L),s=c.getColumn(i,2,P);return e.add(a,u,a),e.add(a,s,a),n.center=e.clone(t.center,n.center),n.radius=e.magnitude(a),n},E.clone=function(t,r){return o(t)?o(r)?(r.center=e.clone(t.center,r.center),r.radius=t.radius,r):new E(t.center,t.radius):void 0},E.packedLength=4,E.pack=function(e,t,o){r.typeOf.object("value",e),r.defined("array",t),o=n(o,0);var i=e.center;return t[o++]=i.x,t[o++]=i.y,t[o++]=i.z,t[o]=e.radius,t},E.unpack=function(e,t,i){r.defined("array",e),t=n(t,0),o(i)||(i=new E);var a=i.center;return a.x=e[t++],a.y=e[t++],a.z=e[t++],i.radius=e[t],i};var D=new e,U=new e;E.union=function(t,n,i){r.typeOf.object("left",t),r.typeOf.object("right",n),o(i)||(i=new E);var a=t.center,u=t.radius,s=n.center,c=n.radius,l=e.subtract(s,a,D),f=e.magnitude(l);if(u>=f+c)return t.clone(i),i;if(c>=f+u)return n.clone(i),i;var h=.5*(u+f+c),d=e.multiplyByScalar(l,(-u+h)/f,U);return e.add(d,a,d),e.clone(d,i.center),i.radius=h,i};var B=new e;E.expand=function(t,n,o){r.typeOf.object("sphere",t),r.typeOf.object("point",n),o=E.clone(t,o);var i=e.magnitude(e.subtract(n,o.center,B));return i>o.radius&&(o.radius=i),o},E.intersectPlane=function(t,n){r.typeOf.object("sphere",t),r.typeOf.object("plane",n);var o=t.center,i=t.radius,a=n.normal,s=e.dot(a,o)+n.distance;return-i>s?u.OUTSIDE:i>s?u.INTERSECTING:u.INSIDE},E.transform=function(e,t,n){return r.typeOf.object("sphere",e),r.typeOf.object("transform",t),o(n)||(n=new E),n.center=l.multiplyByPoint(t,e.center,n.center),n.radius=l.getMaximumScale(t)*e.radius,n};var x=new e;E.distanceSquaredTo=function(t,n){r.typeOf.object("sphere",t),r.typeOf.object("cartesian",n);var o=e.subtract(t.center,n,x);return e.magnitudeSquared(o)-t.radius*t.radius},E.transformWithoutScale=function(e,t,n){return r.typeOf.object("sphere",e),r.typeOf.object("transform",t),o(n)||(n=new E),n.center=l.multiplyByPoint(t,e.center,n.center),n.radius=e.radius,n};var G=new e;E.computePlaneDistances=function(t,n,i,a){r.typeOf.object("sphere",t),r.typeOf.object("position",n),r.typeOf.object("direction",i),o(a)||(a=new s);var u=e.subtract(t.center,n,G),c=e.dot(i,u);return a.start=c-t.radius,a.stop=c+t.radius,a};for(var q=new e,j=new e,z=new e,V=new e,H=new e,X=new t,W=new Array(8),Y=0;8>Y;++Y)W[Y]=new e;var K=new a;return E.projectTo2D=function(t,o,i){r.typeOf.object("sphere",t),o=n(o,K);var a=o.ellipsoid,u=t.center,s=t.radius,c=a.geodeticSurfaceNormal(u,q),l=e.cross(e.UNIT_Z,c,j);e.normalize(l,l);var f=e.cross(c,l,z);e.normalize(f,f),e.multiplyByScalar(c,s,c),e.multiplyByScalar(f,s,f),e.multiplyByScalar(l,s,l);var h=e.negate(f,H),d=e.negate(l,V),p=W,_=p[0];e.add(c,f,_),e.add(_,l,_),_=p[1],e.add(c,f,_),e.add(_,d,_),_=p[2],e.add(c,h,_),e.add(_,d,_),_=p[3],e.add(c,h,_),e.add(_,l,_),e.negate(c,c),_=p[4],e.add(c,f,_),e.add(_,l,_),_=p[5],e.add(c,f,_),e.add(_,d,_),_=p[6],e.add(c,h,_),e.add(_,d,_),_=p[7],e.add(c,h,_),e.add(_,l,_);for(var m=p.length,O=0;m>O;++O){var R=p[O];e.add(u,R,R);var y=a.cartesianToCartographic(R,X);o.project(y,R)}i=E.fromPoints(p,i),u=i.center;var T=u.x,A=u.y,S=u.z;return u.x=S,u.y=T,u.z=A,i},E.isOccluded=function(e,t){return r.typeOf.object("sphere",e),r.typeOf.object("occluder",t),!t.isBoundingSphereVisible(e)},E.equals=function(t,r){return t===r||o(t)&&o(r)&&e.equals(t.center,r.center)&&t.radius===r.radius},E.prototype.intersectPlane=function(e){return E.intersectPlane(this,e)},E.prototype.distanceSquaredTo=function(e){return E.distanceSquaredTo(this,e)},E.prototype.computePlaneDistances=function(e,t,r){return E.computePlaneDistances(this,e,t,r)},E.prototype.isOccluded=function(e){return E.isOccluded(this,e)},E.prototype.equals=function(e){return E.equals(this,e)},E.prototype.clone=function(e){return E.clone(this,e)},E}),define("Core/Fullscreen",["./defined","./defineProperties"],function(e,t){"use strict";var r,n={requestFullscreen:void 0,exitFullscreen:void 0,fullscreenEnabled:void 0,fullscreenElement:void 0,fullscreenchange:void 0,fullscreenerror:void 0},o={};return t(o,{element:{get:function(){return o.supportsFullscreen()?document[n.fullscreenElement]:void 0}},changeEventName:{get:function(){return o.supportsFullscreen()?n.fullscreenchange:void 0}},errorEventName:{get:function(){return o.supportsFullscreen()?n.fullscreenerror:void 0}},enabled:{get:function(){return o.supportsFullscreen()?document[n.fullscreenEnabled]:void 0}},fullscreen:{get:function(){return o.supportsFullscreen()?null!==o.element:void 0}}}),o.supportsFullscreen=function(){if(e(r))return r;r=!1;var t=document.body;if("function"==typeof t.requestFullscreen)return n.requestFullscreen="requestFullscreen",n.exitFullscreen="exitFullscreen",n.fullscreenEnabled="fullscreenEnabled",n.fullscreenElement="fullscreenElement",n.fullscreenchange="fullscreenchange",n.fullscreenerror="fullscreenerror",r=!0;for(var o,i=["webkit","moz","o","ms","khtml"],a=0,u=i.length;u>a;++a){var s=i[a];o=s+"RequestFullscreen","function"==typeof t[o]?(n.requestFullscreen=o,r=!0):(o=s+"RequestFullScreen","function"==typeof t[o]&&(n.requestFullscreen=o,r=!0)),o=s+"ExitFullscreen","function"==typeof document[o]?n.exitFullscreen=o:(o=s+"CancelFullScreen","function"==typeof document[o]&&(n.exitFullscreen=o)),o=s+"FullscreenEnabled",void 0!==document[o]?n.fullscreenEnabled=o:(o=s+"FullScreenEnabled",void 0!==document[o]&&(n.fullscreenEnabled=o)),o=s+"FullscreenElement",void 0!==document[o]?n.fullscreenElement=o:(o=s+"FullScreenElement",void 0!==document[o]&&(n.fullscreenElement=o)),o=s+"fullscreenchange",void 0!==document["on"+o]&&("ms"===s&&(o="MSFullscreenChange"),n.fullscreenchange=o),o=s+"fullscreenerror",void 0!==document["on"+o]&&("ms"===s&&(o="MSFullscreenError"),n.fullscreenerror=o)}return r},o.requestFullscreen=function(e,t){o.supportsFullscreen()&&e[n.requestFullscreen]({vrDisplay:t})},o.exitFullscreen=function(){o.supportsFullscreen()&&document[n.exitFullscreen]()},o}),define("Core/FeatureDetection",["./defaultValue","./defined","./Fullscreen"],function(e,t,r){"use strict";function n(e){for(var t=e.split("."),r=0,n=t.length;n>r;++r)t[r]=parseInt(t[r],10);return t}function o(){if(!t(S)&&(S=!1,!E())){var e=/ Chrome\/([\.0-9]+)/.exec(A.userAgent);null!==e&&(S=!0,N=n(e[1]))}return S}function i(){return o()&&N}function a(){if(!t(C)&&(C=!1,!o()&&!E()&&/ Safari\/[\.0-9]+/.test(A.userAgent))){var e=/ Version\/([\.0-9]+)/.exec(A.userAgent);null!==e&&(C=!0,g=n(e[1]))}return C}function u(){return a()&&g}function s(){if(!t(I)){I=!1;var e=/ AppleWebKit\/([\.0-9]+)(\+?)/.exec(A.userAgent);null!==e&&(I=!0,b=n(e[1]),b.isNightly=!!e[2])}return I}function c(){return s()&&b}function l(){if(!t(M)){M=!1;var e;"Microsoft Internet Explorer"===A.appName?(e=/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(A.userAgent),null!==e&&(M=!0,w=n(e[1]))):"Netscape"===A.appName&&(e=/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(A.userAgent),null!==e&&(M=!0,w=n(e[1])))}return M}function f(){return l()&&w}function E(){if(!t(v)){v=!1;var e=/ Edge\/([\.0-9]+)/.exec(A.userAgent);null!==e&&(v=!0,F=n(e[1]))}return v}function h(){return E()&&F}function d(){if(!t(L)){L=!1;var e=/Firefox\/([\.0-9]+)/.exec(A.userAgent);null!==e&&(L=!0,P=n(e[1]))}return L}function p(){return t(D)||(D=/Windows/i.test(A.appVersion)),D}function _(){return d()&&P}function m(){return t(U)||(U="object"==typeof process&&"[object process]"===Object.prototype.toString.call(process)),U}function O(){return t(B)||(B="undefined"!=typeof PointerEvent&&(!t(A.pointerEnabled)||A.pointerEnabled)),B}function R(){if(!t(G)){var e=document.createElement("canvas");e.setAttribute("style","image-rendering: -moz-crisp-edges;image-rendering: pixelated;");var r=e.style.imageRendering;G=t(r)&&""!==r,G&&(x=r)}return G}function y(){return R()?x:void 0}function T(){var e=window.navigator.userAgent.toLowerCase(),t="ipad"==e.match(/ipad/i),r="iphone os"==e.match(/iphone os/i),n="midp"==e.match(/midp/i),o="rv:1.2.3.4"==e.match(/rv:1.2.3.4/i),i="ucweb"==e.match(/ucweb/i),a="android"==e.match(/android/i),u="windows ce"==e.match(/windows ce/i),s="windows mobile"==e.match(/windows mobile/i);return t||r||n||o||i||a||u||s?!1:!0}var A;A="undefined"!=typeof navigator?navigator:{};var S,N,C,g,I,b,M,w,v,F,L,P,D,U,B,x,G,q=[];"undefined"!=typeof ArrayBuffer&&(q.push(Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array),"undefined"!=typeof Uint8ClampedArray&&q.push(Uint8ClampedArray),"undefined"!=typeof CanvasPixelArray&&q.push(CanvasPixelArray));var j={isChrome:o,chromeVersion:i,isSafari:a,safariVersion:u,isWebkit:s,webkitVersion:c,isInternetExplorer:l,internetExplorerVersion:f,isEdge:E,edgeVersion:h,isFirefox:d,firefoxVersion:_,isWindows:p,isNodeJs:m,hardwareConcurrency:e(A.hardwareConcurrency,3),supportsPointerEvents:O,supportsImageRenderingPixelated:R,imageRenderingValue:y,typedArrayTypes:q,isPCBroswer:T};return j.supportsFullscreen=function(){return r.supportsFullscreen()},j.supportsTypedArrays=function(){return"undefined"!=typeof ArrayBuffer},j.supportsWebWorkers=function(){return"undefined"!=typeof Worker},j.supportsWebAssembly=function(){return"undefined"!=typeof WebAssembly&&!j.isEdge()},j}),define("Core/Color",["./Check","./defaultValue","./defined","./FeatureDetection","./freezeObject","./Math"],function(e,t,r,n,o,i){"use strict";function a(e,t,r){return 0>r&&(r+=1),r>1&&(r-=1),1>6*r?e+6*(t-e)*r:1>2*r?t:2>3*r?e+(t-e)*(2/3-r)*6:e}function u(e,r,n,o){this.red=t(e,1),this.green=t(r,1),this.blue=t(n,1),this.alpha=t(o,1)}u.fromCartesian4=function(t,n){return e.typeOf.object("cartesian",t),r(n)?(n.red=t.x,n.green=t.y,n.blue=t.z,n.alpha=t.w,n):new u(t.x,t.y,t.z,t.w)},u.fromBytes=function(e,n,o,i,a){return e=u.byteToFloat(t(e,255)),n=u.byteToFloat(t(n,255)),o=u.byteToFloat(t(o,255)),i=u.byteToFloat(t(i,255)),r(a)?(a.red=e,a.green=n,a.blue=o,a.alpha=i,a):new u(e,n,o,i)},u.fromAlpha=function(t,n,o){return e.typeOf.object("color",t),e.typeOf.number("alpha",n),r(o)?(o.red=t.red,o.green=t.green,o.blue=t.blue,o.alpha=n,o):new u(t.red,t.green,t.blue,n)};var s,c,l;n.supportsTypedArrays()&&(s=new ArrayBuffer(4),c=new Uint32Array(s),l=new Uint8Array(s)),u.fromRgba=function(e,t){return c[0]=e,u.fromBytes(l[0],l[1],l[2],l[3],t)},u.fromHsl=function(e,n,o,i,s){e=t(e,0)%1,n=t(n,0),o=t(o,0),i=t(i,1);var c=o,l=o,f=o;if(0!==n){var E;E=.5>o?o*(1+n):o+n-o*n;var h=2*o-E;c=a(h,E,e+1/3),l=a(h,E,e),f=a(h,E,e-1/3)}return r(s)?(s.red=c,s.green=l,s.blue=f,s.alpha=i,s):new u(c,l,f,i)},u.fromRandom=function(n,o){n=t(n,t.EMPTY_OBJECT);var a=n.red;if(!r(a)){var s=t(n.minimumRed,0),c=t(n.maximumRed,1);e.typeOf.number.lessThanOrEquals("minimumRed",s,c),a=s+i.nextRandomNumber()*(c-s)}var l=n.green;if(!r(l)){var f=t(n.minimumGreen,0),E=t(n.maximumGreen,1);e.typeOf.number.lessThanOrEquals("minimumGreen",f,E),l=f+i.nextRandomNumber()*(E-f)}var h=n.blue;if(!r(h)){var d=t(n.minimumBlue,0),p=t(n.maximumBlue,1);e.typeOf.number.lessThanOrEquals("minimumBlue",d,p),h=d+i.nextRandomNumber()*(p-d)}var _=n.alpha;if(!r(_)){var m=t(n.minimumAlpha,0),O=t(n.maximumAlpha,1);e.typeOf.number.lessThanOrEquals("minumumAlpha",m,O),_=m+i.nextRandomNumber()*(O-m)}return r(o)?(o.red=a,o.green=l,o.blue=h,o.alpha=_,o):new u(a,l,h,_)};var f=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,E=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,h=/^rgba?\(\s*([0-9.]+%?)\s*,\s*([0-9.]+%?)\s*,\s*([0-9.]+%?)(?:\s*,\s*([0-9.]+))?\s*\)$/i,d=/^hsla?\(\s*([0-9.]+)\s*,\s*([0-9.]+%)\s*,\s*([0-9.]+%)(?:\s*,\s*([0-9.]+))?\s*\)$/i;return u.fromCssColorString=function(n,o){e.typeOf.string("color",n),r(o)||(o=new u);var i=u[n.toUpperCase()];if(r(i))return u.clone(i,o),o;var a=f.exec(n);return null!==a?(o.red=parseInt(a[1],16)/15,o.green=parseInt(a[2],16)/15,o.blue=parseInt(a[3],16)/15,o.alpha=1,o):(a=E.exec(n),null!==a?(o.red=parseInt(a[1],16)/255,o.green=parseInt(a[2],16)/255,o.blue=parseInt(a[3],16)/255,o.alpha=1,o):(a=h.exec(n),null!==a?(o.red=parseFloat(a[1])/("%"===a[1].substr(-1)?100:255),o.green=parseFloat(a[2])/("%"===a[2].substr(-1)?100:255),o.blue=parseFloat(a[3])/("%"===a[3].substr(-1)?100:255),o.alpha=parseFloat(t(a[4],"1.0")),o):(a=d.exec(n),null!==a?u.fromHsl(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,parseFloat(t(a[4],"1.0")),o):o=void 0)))},u.packedLength=4,u.pack=function(r,n,o){return e.typeOf.object("value",r),e.defined("array",n),o=t(o,0),n[o++]=r.red,n[o++]=r.green,n[o++]=r.blue,n[o]=r.alpha,n},u.unpack=function(n,o,i){return e.defined("array",n),o=t(o,0),r(i)||(i=new u),i.red=n[o++],i.green=n[o++],i.blue=n[o++],i.alpha=n[o],i},u.byteToFloat=function(e){return e/255},u.floatToByte=function(e){return 1===e?255:256*e|0},u.clone=function(e,t){return r(e)?r(t)?(t.red=e.red,t.green=e.green,t.blue=e.blue,t.alpha=e.alpha,t):new u(e.red,e.green,e.blue,e.alpha):void 0},u.equals=function(e,t){return e===t||r(e)&&r(t)&&e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha},u.equalsArray=function(e,t,r){return e.red===t[r]&&e.green===t[r+1]&&e.blue===t[r+2]&&e.alpha===t[r+3]},u.prototype.clone=function(e){return u.clone(this,e)},u.prototype.equals=function(e){return u.equals(this,e)},u.prototype.equalsEpsilon=function(e,t){return this===e||r(e)&&Math.abs(this.red-e.red)<=t&&Math.abs(this.green-e.green)<=t&&Math.abs(this.blue-e.blue)<=t&&Math.abs(this.alpha-e.alpha)<=t},u.prototype.toString=function(){return"("+this.red+", "+this.green+", "+this.blue+", "+this.alpha+")"},u.prototype.toCssColorString=function(){var e=u.floatToByte(this.red),t=u.floatToByte(this.green),r=u.floatToByte(this.blue);return 1===this.alpha?"rgb("+e+","+t+","+r+")":"rgba("+e+","+t+","+r+","+this.alpha+")"},u.prototype.toBytes=function(e){var t=u.floatToByte(this.red),n=u.floatToByte(this.green),o=u.floatToByte(this.blue),i=u.floatToByte(this.alpha);return r(e)?(e[0]=t,e[1]=n,e[2]=o,e[3]=i,e):[t,n,o,i]},u.prototype.toRgba=function(){return l[0]=u.floatToByte(this.red),l[1]=u.floatToByte(this.green),l[2]=u.floatToByte(this.blue),l[3]=u.floatToByte(this.alpha),c[0]},u.prototype.brighten=function(t,r){return e.typeOf.number("magnitude",t),e.typeOf.number.greaterThanOrEquals("magnitude",t,0),e.typeOf.object("result",r),t=1-t,r.red=1-(1-this.red)*t,r.green=1-(1-this.green)*t,r.blue=1-(1-this.blue)*t,r.alpha=this.alpha,r},u.prototype.darken=function(t,r){return e.typeOf.number("magnitude",t),e.typeOf.number.greaterThanOrEquals("magnitude",t,0),e.typeOf.object("result",r),t=1-t,r.red=this.red*t,r.green=this.green*t,r.blue=this.blue*t,r.alpha=this.alpha,r},u.prototype.withAlpha=function(e,t){return u.fromAlpha(this,e,t)},u.add=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.red=t.red+r.red,n.green=t.green+r.green,n.blue=t.blue+r.blue,n.alpha=t.alpha+r.alpha,n},u.subtract=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.red=t.red-r.red,n.green=t.green-r.green,n.blue=t.blue-r.blue,n.alpha=t.alpha-r.alpha,n},u.multiply=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.red=t.red*r.red,n.green=t.green*r.green,n.blue=t.blue*r.blue,n.alpha=t.alpha*r.alpha,n},u.divide=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.red=t.red/r.red,n.green=t.green/r.green,n.blue=t.blue/r.blue,n.alpha=t.alpha/r.alpha,n},u.mod=function(t,r,n){return e.typeOf.object("left",t),e.typeOf.object("right",r),e.typeOf.object("result",n),n.red=t.red%r.red,n.green=t.green%r.green,n.blue=t.blue%r.blue,n.alpha=t.alpha%r.alpha,n},u.multiplyByScalar=function(t,r,n){return e.typeOf.object("color",t),e.typeOf.number("scalar",r),e.typeOf.object("result",n),n.red=t.red*r,n.green=t.green*r,n.blue=t.blue*r,n.alpha=t.alpha*r,n},u.divideByScalar=function(t,r,n){return e.typeOf.object("color",t),e.typeOf.number("scalar",r),e.typeOf.object("result",n),n.red=t.red/r,n.green=t.green/r,n.blue=t.blue/r,n.alpha=t.alpha/r,n},u.ALICEBLUE=o(u.fromCssColorString("#F0F8FF")),u.ANTIQUEWHITE=o(u.fromCssColorString("#FAEBD7")),u.AQUA=o(u.fromCssColorString("#00FFFF")),u.AQUAMARINE=o(u.fromCssColorString("#7FFFD4")),u.AZURE=o(u.fromCssColorString("#F0FFFF")),u.BEIGE=o(u.fromCssColorString("#F5F5DC")),u.BISQUE=o(u.fromCssColorString("#FFE4C4")),u.BLACK=o(u.fromCssColorString("#000000")),u.BLANCHEDALMOND=o(u.fromCssColorString("#FFEBCD")),u.BLUE=o(u.fromCssColorString("#0000FF")),u.BLUEVIOLET=o(u.fromCssColorString("#8A2BE2")),u.BROWN=o(u.fromCssColorString("#A52A2A")),u.BURLYWOOD=o(u.fromCssColorString("#DEB887")),u.CADETBLUE=o(u.fromCssColorString("#5F9EA0")),u.CHARTREUSE=o(u.fromCssColorString("#7FFF00")),u.CHOCOLATE=o(u.fromCssColorString("#D2691E")),u.CORAL=o(u.fromCssColorString("#FF7F50")),u.CORNFLOWERBLUE=o(u.fromCssColorString("#6495ED")),u.CORNSILK=o(u.fromCssColorString("#FFF8DC")),u.CRIMSON=o(u.fromCssColorString("#DC143C")),u.CYAN=o(u.fromCssColorString("#00FFFF")),u.DARKBLUE=o(u.fromCssColorString("#00008B")),u.DARKCYAN=o(u.fromCssColorString("#008B8B")),u.DARKGOLDENROD=o(u.fromCssColorString("#B8860B")),u.DARKGRAY=o(u.fromCssColorString("#A9A9A9")),u.DARKGREEN=o(u.fromCssColorString("#006400")),u.DARKGREY=u.DARKGRAY,u.DARKKHAKI=o(u.fromCssColorString("#BDB76B")),u.DARKMAGENTA=o(u.fromCssColorString("#8B008B")),u.DARKOLIVEGREEN=o(u.fromCssColorString("#556B2F")),u.DARKORANGE=o(u.fromCssColorString("#FF8C00")),u.DARKORCHID=o(u.fromCssColorString("#9932CC")),u.DARKRED=o(u.fromCssColorString("#8B0000")),u.DARKSALMON=o(u.fromCssColorString("#E9967A")),u.DARKSEAGREEN=o(u.fromCssColorString("#8FBC8F")),u.DARKSLATEBLUE=o(u.fromCssColorString("#483D8B")),u.DARKSLATEGRAY=o(u.fromCssColorString("#2F4F4F")),u.DARKSLATEGREY=u.DARKSLATEGRAY,u.DARKTURQUOISE=o(u.fromCssColorString("#00CED1")),u.DARKVIOLET=o(u.fromCssColorString("#9400D3")),u.DEEPPINK=o(u.fromCssColorString("#FF1493")),u.DEEPSKYBLUE=o(u.fromCssColorString("#00BFFF")),u.DIMGRAY=o(u.fromCssColorString("#696969")),u.DIMGREY=u.DIMGRAY,u.DODGERBLUE=o(u.fromCssColorString("#1E90FF")),u.FIREBRICK=o(u.fromCssColorString("#B22222")),u.FLORALWHITE=o(u.fromCssColorString("#FFFAF0")),u.FORESTGREEN=o(u.fromCssColorString("#228B22")),u.FUCHSIA=o(u.fromCssColorString("#FF00FF")),u.GAINSBORO=o(u.fromCssColorString("#DCDCDC")),u.GHOSTWHITE=o(u.fromCssColorString("#F8F8FF")),u.GOLD=o(u.fromCssColorString("#FFD700")),u.GOLDENROD=o(u.fromCssColorString("#DAA520")),u.GRAY=o(u.fromCssColorString("#808080")),u.GREEN=o(u.fromCssColorString("#008000")),u.GREENYELLOW=o(u.fromCssColorString("#ADFF2F")),u.GREY=u.GRAY,u.HONEYDEW=o(u.fromCssColorString("#F0FFF0")),u.HOTPINK=o(u.fromCssColorString("#FF69B4")),u.INDIANRED=o(u.fromCssColorString("#CD5C5C")),u.INDIGO=o(u.fromCssColorString("#4B0082")),u.IVORY=o(u.fromCssColorString("#FFFFF0")),u.KHAKI=o(u.fromCssColorString("#F0E68C")),u.LAVENDER=o(u.fromCssColorString("#E6E6FA")),u.LAVENDAR_BLUSH=o(u.fromCssColorString("#FFF0F5")),u.LAWNGREEN=o(u.fromCssColorString("#7CFC00")),u.LEMONCHIFFON=o(u.fromCssColorString("#FFFACD")),u.LIGHTBLUE=o(u.fromCssColorString("#ADD8E6")),u.LIGHTCORAL=o(u.fromCssColorString("#F08080")),u.LIGHTCYAN=o(u.fromCssColorString("#E0FFFF")),u.LIGHTGOLDENRODYELLOW=o(u.fromCssColorString("#FAFAD2")),u.LIGHTGRAY=o(u.fromCssColorString("#D3D3D3")),u.LIGHTGREEN=o(u.fromCssColorString("#90EE90")),u.LIGHTGREY=u.LIGHTGRAY,u.LIGHTPINK=o(u.fromCssColorString("#FFB6C1")),u.LIGHTSEAGREEN=o(u.fromCssColorString("#20B2AA")),u.LIGHTSKYBLUE=o(u.fromCssColorString("#87CEFA")),u.LIGHTSLATEGRAY=o(u.fromCssColorString("#778899")),u.LIGHTSLATEGREY=u.LIGHTSLATEGRAY,u.LIGHTSTEELBLUE=o(u.fromCssColorString("#B0C4DE")),u.LIGHTYELLOW=o(u.fromCssColorString("#FFFFE0")),u.LIME=o(u.fromCssColorString("#00FF00")),u.LIMEGREEN=o(u.fromCssColorString("#32CD32")),u.LINEN=o(u.fromCssColorString("#FAF0E6")),u.MAGENTA=o(u.fromCssColorString("#FF00FF")),u.MAROON=o(u.fromCssColorString("#800000")),u.MEDIUMAQUAMARINE=o(u.fromCssColorString("#66CDAA")),u.MEDIUMBLUE=o(u.fromCssColorString("#0000CD")),u.MEDIUMORCHID=o(u.fromCssColorString("#BA55D3")),u.MEDIUMPURPLE=o(u.fromCssColorString("#9370DB")),u.MEDIUMSEAGREEN=o(u.fromCssColorString("#3CB371")),u.MEDIUMSLATEBLUE=o(u.fromCssColorString("#7B68EE")),u.MEDIUMSPRINGGREEN=o(u.fromCssColorString("#00FA9A")),u.MEDIUMTURQUOISE=o(u.fromCssColorString("#48D1CC")),u.MEDIUMVIOLETRED=o(u.fromCssColorString("#C71585")),u.MIDNIGHTBLUE=o(u.fromCssColorString("#191970")),u.MINTCREAM=o(u.fromCssColorString("#F5FFFA")),u.MISTYROSE=o(u.fromCssColorString("#FFE4E1")),u.MOCCASIN=o(u.fromCssColorString("#FFE4B5")),u.NAVAJOWHITE=o(u.fromCssColorString("#FFDEAD")),u.NAVY=o(u.fromCssColorString("#000080")),u.OLDLACE=o(u.fromCssColorString("#FDF5E6")),u.OLIVE=o(u.fromCssColorString("#808000")),u.OLIVEDRAB=o(u.fromCssColorString("#6B8E23")),u.ORANGE=o(u.fromCssColorString("#FFA500")),u.ORANGERED=o(u.fromCssColorString("#FF4500")),u.ORCHID=o(u.fromCssColorString("#DA70D6")),u.PALEGOLDENROD=o(u.fromCssColorString("#EEE8AA")),u.PALEGREEN=o(u.fromCssColorString("#98FB98")),u.PALETURQUOISE=o(u.fromCssColorString("#AFEEEE")),u.PALEVIOLETRED=o(u.fromCssColorString("#DB7093")),u.PAPAYAWHIP=o(u.fromCssColorString("#FFEFD5")),u.PEACHPUFF=o(u.fromCssColorString("#FFDAB9")),u.PERU=o(u.fromCssColorString("#CD853F")),u.PINK=o(u.fromCssColorString("#FFC0CB")),u.PLUM=o(u.fromCssColorString("#DDA0DD")),u.POWDERBLUE=o(u.fromCssColorString("#B0E0E6")),u.PURPLE=o(u.fromCssColorString("#800080")),u.RED=o(u.fromCssColorString("#FF0000")),u.ROSYBROWN=o(u.fromCssColorString("#BC8F8F")),u.ROYALBLUE=o(u.fromCssColorString("#4169E1")),u.SADDLEBROWN=o(u.fromCssColorString("#8B4513")),u.SALMON=o(u.fromCssColorString("#FA8072")),u.SANDYBROWN=o(u.fromCssColorString("#F4A460")),u.SEAGREEN=o(u.fromCssColorString("#2E8B57")),u.SEASHELL=o(u.fromCssColorString("#FFF5EE")),u.SIENNA=o(u.fromCssColorString("#A0522D")),u.SILVER=o(u.fromCssColorString("#C0C0C0")),u.SKYBLUE=o(u.fromCssColorString("#87CEEB")),u.SLATEBLUE=o(u.fromCssColorString("#6A5ACD")),u.SLATEGRAY=o(u.fromCssColorString("#708090")),u.SLATEGREY=u.SLATEGRAY,u.SNOW=o(u.fromCssColorString("#FFFAFA")),u.SPRINGGREEN=o(u.fromCssColorString("#00FF7F")),u.STEELBLUE=o(u.fromCssColorString("#4682B4")),u.TAN=o(u.fromCssColorString("#D2B48C")),u.TEAL=o(u.fromCssColorString("#008080")),u.THISTLE=o(u.fromCssColorString("#D8BFD8")),u.TOMATO=o(u.fromCssColorString("#FF6347")),u.TURQUOISE=o(u.fromCssColorString("#40E0D0")),u.VIOLET=o(u.fromCssColorString("#EE82EE")),u.WHEAT=o(u.fromCssColorString("#F5DEB3")),u.WHITE=o(u.fromCssColorString("#FFFFFF")),u.WHITESMOKE=o(u.fromCssColorString("#F5F5F5")),u.YELLOW=o(u.fromCssColorString("#FFFF00")),u.YELLOWGREEN=o(u.fromCssColorString("#9ACD32")),u.TRANSPARENT=o(new u(0,0,0,0)),u}),define("Core/WebGLConstants",["./freezeObject"],function(e){"use strict";var t={DEPTH_BUFFER_BIT:256,STENCIL_BUFFER_BIT:1024,COLOR_BUFFER_BIT:16384,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,ZERO:0,ONE:1,SRC_COLOR:768,ONE_MINUS_SRC_COLOR:769,SRC_ALPHA:770,ONE_MINUS_SRC_ALPHA:771,DST_ALPHA:772,ONE_MINUS_DST_ALPHA:773,DST_COLOR:774,ONE_MINUS_DST_COLOR:775,SRC_ALPHA_SATURATE:776,
FUNC_ADD:32774,BLEND_EQUATION:32777,BLEND_EQUATION_RGB:32777,BLEND_EQUATION_ALPHA:34877,FUNC_SUBTRACT:32778,FUNC_REVERSE_SUBTRACT:32779,BLEND_DST_RGB:32968,BLEND_SRC_RGB:32969,BLEND_DST_ALPHA:32970,BLEND_SRC_ALPHA:32971,CONSTANT_COLOR:32769,ONE_MINUS_CONSTANT_COLOR:32770,CONSTANT_ALPHA:32771,ONE_MINUS_CONSTANT_ALPHA:32772,BLEND_COLOR:32773,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,ARRAY_BUFFER_BINDING:34964,ELEMENT_ARRAY_BUFFER_BINDING:34965,STREAM_DRAW:35040,STATIC_DRAW:35044,DYNAMIC_DRAW:35048,BUFFER_SIZE:34660,BUFFER_USAGE:34661,CURRENT_VERTEX_ATTRIB:34342,FRONT:1028,BACK:1029,FRONT_AND_BACK:1032,CULL_FACE:2884,BLEND:3042,DITHER:3024,STENCIL_TEST:2960,DEPTH_TEST:2929,SCISSOR_TEST:3089,POLYGON_OFFSET_FILL:32823,SAMPLE_ALPHA_TO_COVERAGE:32926,SAMPLE_COVERAGE:32928,NO_ERROR:0,INVALID_ENUM:1280,INVALID_VALUE:1281,INVALID_OPERATION:1282,OUT_OF_MEMORY:1285,CW:2304,CCW:2305,LINE_WIDTH:2849,ALIASED_POINT_SIZE_RANGE:33901,ALIASED_LINE_WIDTH_RANGE:33902,CULL_FACE_MODE:2885,FRONT_FACE:2886,DEPTH_RANGE:2928,DEPTH_WRITEMASK:2930,DEPTH_CLEAR_VALUE:2931,DEPTH_FUNC:2932,STENCIL_CLEAR_VALUE:2961,STENCIL_FUNC:2962,STENCIL_FAIL:2964,STENCIL_PASS_DEPTH_FAIL:2965,STENCIL_PASS_DEPTH_PASS:2966,STENCIL_REF:2967,STENCIL_VALUE_MASK:2963,STENCIL_WRITEMASK:2968,STENCIL_BACK_FUNC:34816,STENCIL_BACK_FAIL:34817,STENCIL_BACK_PASS_DEPTH_FAIL:34818,STENCIL_BACK_PASS_DEPTH_PASS:34819,STENCIL_BACK_REF:36003,STENCIL_BACK_VALUE_MASK:36004,STENCIL_BACK_WRITEMASK:36005,VIEWPORT:2978,SCISSOR_BOX:3088,COLOR_CLEAR_VALUE:3106,COLOR_WRITEMASK:3107,UNPACK_ALIGNMENT:3317,PACK_ALIGNMENT:3333,MAX_TEXTURE_SIZE:3379,MAX_VIEWPORT_DIMS:3386,SUBPIXEL_BITS:3408,RED_BITS:3410,GREEN_BITS:3411,BLUE_BITS:3412,ALPHA_BITS:3413,DEPTH_BITS:3414,STENCIL_BITS:3415,POLYGON_OFFSET_UNITS:10752,POLYGON_OFFSET_FACTOR:32824,TEXTURE_BINDING_2D:32873,SAMPLE_BUFFERS:32936,SAMPLES:32937,SAMPLE_COVERAGE_VALUE:32938,SAMPLE_COVERAGE_INVERT:32939,COMPRESSED_TEXTURE_FORMATS:34467,DONT_CARE:4352,FASTEST:4353,NICEST:4354,GENERATE_MIPMAP_HINT:33170,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,DEPTH_COMPONENT:6402,ALPHA:6406,RGB:6407,RGBA:6408,LUMINANCE:6409,LUMINANCE_ALPHA:6410,UNSIGNED_SHORT_4_4_4_4:32819,UNSIGNED_SHORT_5_5_5_1:32820,UNSIGNED_SHORT_5_6_5:33635,FRAGMENT_SHADER:35632,VERTEX_SHADER:35633,MAX_VERTEX_ATTRIBS:34921,MAX_VERTEX_UNIFORM_VECTORS:36347,MAX_VARYING_VECTORS:36348,MAX_COMBINED_TEXTURE_IMAGE_UNITS:35661,MAX_VERTEX_TEXTURE_IMAGE_UNITS:35660,MAX_TEXTURE_IMAGE_UNITS:34930,MAX_FRAGMENT_UNIFORM_VECTORS:36349,SHADER_TYPE:35663,DELETE_STATUS:35712,LINK_STATUS:35714,VALIDATE_STATUS:35715,ATTACHED_SHADERS:35717,ACTIVE_UNIFORMS:35718,ACTIVE_ATTRIBUTES:35721,SHADING_LANGUAGE_VERSION:35724,CURRENT_PROGRAM:35725,NEVER:512,LESS:513,EQUAL:514,LEQUAL:515,GREATER:516,NOTEQUAL:517,GEQUAL:518,ALWAYS:519,KEEP:7680,REPLACE:7681,INCR:7682,DECR:7683,INVERT:5386,INCR_WRAP:34055,DECR_WRAP:34056,VENDOR:7936,RENDERER:7937,VERSION:7938,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,TEXTURE_2D:3553,TEXTURE:5890,TEXTURE_CUBE_MAP:34067,TEXTURE_BINDING_CUBE_MAP:34068,TEXTURE_CUBE_MAP_POSITIVE_X:34069,TEXTURE_CUBE_MAP_NEGATIVE_X:34070,TEXTURE_CUBE_MAP_POSITIVE_Y:34071,TEXTURE_CUBE_MAP_NEGATIVE_Y:34072,TEXTURE_CUBE_MAP_POSITIVE_Z:34073,TEXTURE_CUBE_MAP_NEGATIVE_Z:34074,MAX_CUBE_MAP_TEXTURE_SIZE:34076,TEXTURE0:33984,TEXTURE1:33985,TEXTURE2:33986,TEXTURE3:33987,TEXTURE4:33988,TEXTURE5:33989,TEXTURE6:33990,TEXTURE7:33991,TEXTURE8:33992,TEXTURE9:33993,TEXTURE10:33994,TEXTURE11:33995,TEXTURE12:33996,TEXTURE13:33997,TEXTURE14:33998,TEXTURE15:33999,TEXTURE16:34e3,TEXTURE17:34001,TEXTURE18:34002,TEXTURE19:34003,TEXTURE20:34004,TEXTURE21:34005,TEXTURE22:34006,TEXTURE23:34007,TEXTURE24:34008,TEXTURE25:34009,TEXTURE26:34010,TEXTURE27:34011,TEXTURE28:34012,TEXTURE29:34013,TEXTURE30:34014,TEXTURE31:34015,ACTIVE_TEXTURE:34016,REPEAT:10497,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,INT_VEC2:35667,INT_VEC3:35668,INT_VEC4:35669,BOOL:35670,BOOL_VEC2:35671,BOOL_VEC3:35672,BOOL_VEC4:35673,FLOAT_MAT2:35674,FLOAT_MAT3:35675,FLOAT_MAT4:35676,SAMPLER_2D:35678,SAMPLER_CUBE:35680,VERTEX_ATTRIB_ARRAY_ENABLED:34338,VERTEX_ATTRIB_ARRAY_SIZE:34339,VERTEX_ATTRIB_ARRAY_STRIDE:34340,VERTEX_ATTRIB_ARRAY_TYPE:34341,VERTEX_ATTRIB_ARRAY_NORMALIZED:34922,VERTEX_ATTRIB_ARRAY_POINTER:34373,VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:34975,IMPLEMENTATION_COLOR_READ_TYPE:35738,IMPLEMENTATION_COLOR_READ_FORMAT:35739,COMPILE_STATUS:35713,LOW_FLOAT:36336,MEDIUM_FLOAT:36337,HIGH_FLOAT:36338,LOW_INT:36339,MEDIUM_INT:36340,HIGH_INT:36341,FRAMEBUFFER:36160,RENDERBUFFER:36161,RGBA4:32854,RGB5_A1:32855,RGB565:36194,DEPTH_COMPONENT16:33189,STENCIL_INDEX:6401,STENCIL_INDEX8:36168,DEPTH_STENCIL:34041,RENDERBUFFER_WIDTH:36162,RENDERBUFFER_HEIGHT:36163,RENDERBUFFER_INTERNAL_FORMAT:36164,RENDERBUFFER_RED_SIZE:36176,RENDERBUFFER_GREEN_SIZE:36177,RENDERBUFFER_BLUE_SIZE:36178,RENDERBUFFER_ALPHA_SIZE:36179,RENDERBUFFER_DEPTH_SIZE:36180,RENDERBUFFER_STENCIL_SIZE:36181,FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:36048,FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:36049,FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:36050,FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:36051,COLOR_ATTACHMENT0:36064,DEPTH_ATTACHMENT:36096,STENCIL_ATTACHMENT:36128,DEPTH_STENCIL_ATTACHMENT:33306,NONE:0,FRAMEBUFFER_COMPLETE:36053,FRAMEBUFFER_INCOMPLETE_ATTACHMENT:36054,FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:36055,FRAMEBUFFER_INCOMPLETE_DIMENSIONS:36057,FRAMEBUFFER_UNSUPPORTED:36061,FRAMEBUFFER_BINDING:36006,RENDERBUFFER_BINDING:36007,MAX_RENDERBUFFER_SIZE:34024,INVALID_FRAMEBUFFER_OPERATION:1286,UNPACK_FLIP_Y_WEBGL:37440,UNPACK_PREMULTIPLY_ALPHA_WEBGL:37441,CONTEXT_LOST_WEBGL:37442,UNPACK_COLORSPACE_CONVERSION_WEBGL:37443,BROWSER_DEFAULT_WEBGL:37444,COMPRESSED_RGB_S3TC_DXT1_EXT:33776,COMPRESSED_RGBA_S3TC_DXT1_EXT:33777,COMPRESSED_RGBA_S3TC_DXT3_EXT:33778,COMPRESSED_RGBA_S3TC_DXT5_EXT:33779,COMPRESSED_RGB_PVRTC_4BPPV1_IMG:35840,COMPRESSED_RGB_PVRTC_2BPPV1_IMG:35841,COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:35842,COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:35843,COMPRESSED_RGB_ETC1_WEBGL:36196,DOUBLE:5130,READ_BUFFER:3074,UNPACK_ROW_LENGTH:3314,UNPACK_SKIP_ROWS:3315,UNPACK_SKIP_PIXELS:3316,PACK_ROW_LENGTH:3330,PACK_SKIP_ROWS:3331,PACK_SKIP_PIXELS:3332,COLOR:6144,DEPTH:6145,STENCIL:6146,RED:6403,RGB8:32849,RGBA8:32856,RGB10_A2:32857,TEXTURE_BINDING_3D:32874,UNPACK_SKIP_IMAGES:32877,UNPACK_IMAGE_HEIGHT:32878,TEXTURE_3D:32879,TEXTURE_WRAP_R:32882,MAX_3D_TEXTURE_SIZE:32883,UNSIGNED_INT_2_10_10_10_REV:33640,MAX_ELEMENTS_VERTICES:33e3,MAX_ELEMENTS_INDICES:33001,TEXTURE_MIN_LOD:33082,TEXTURE_MAX_LOD:33083,TEXTURE_BASE_LEVEL:33084,TEXTURE_MAX_LEVEL:33085,MIN:32775,MAX:32776,DEPTH_COMPONENT24:33190,MAX_TEXTURE_LOD_BIAS:34045,TEXTURE_COMPARE_MODE:34892,TEXTURE_COMPARE_FUNC:34893,CURRENT_QUERY:34917,QUERY_RESULT:34918,QUERY_RESULT_AVAILABLE:34919,STREAM_READ:35041,STREAM_COPY:35042,STATIC_READ:35045,STATIC_COPY:35046,DYNAMIC_READ:35049,DYNAMIC_COPY:35050,MAX_DRAW_BUFFERS:34852,DRAW_BUFFER0:34853,DRAW_BUFFER1:34854,DRAW_BUFFER2:34855,DRAW_BUFFER3:34856,DRAW_BUFFER4:34857,DRAW_BUFFER5:34858,DRAW_BUFFER6:34859,DRAW_BUFFER7:34860,DRAW_BUFFER8:34861,DRAW_BUFFER9:34862,DRAW_BUFFER10:34863,DRAW_BUFFER11:34864,DRAW_BUFFER12:34865,DRAW_BUFFER13:34866,DRAW_BUFFER14:34867,DRAW_BUFFER15:34868,MAX_FRAGMENT_UNIFORM_COMPONENTS:35657,MAX_VERTEX_UNIFORM_COMPONENTS:35658,SAMPLER_3D:35679,SAMPLER_2D_SHADOW:35682,FRAGMENT_SHADER_DERIVATIVE_HINT:35723,PIXEL_PACK_BUFFER:35051,PIXEL_UNPACK_BUFFER:35052,PIXEL_PACK_BUFFER_BINDING:35053,PIXEL_UNPACK_BUFFER_BINDING:35055,FLOAT_MAT2x3:35685,FLOAT_MAT2x4:35686,FLOAT_MAT3x2:35687,FLOAT_MAT3x4:35688,FLOAT_MAT4x2:35689,FLOAT_MAT4x3:35690,SRGB:35904,SRGB8:35905,SRGB8_ALPHA8:35907,COMPARE_REF_TO_TEXTURE:34894,RGBA32F:34836,RGB32F:34837,RGBA16F:34842,RGB16F:34843,VERTEX_ATTRIB_ARRAY_INTEGER:35069,MAX_ARRAY_TEXTURE_LAYERS:35071,MIN_PROGRAM_TEXEL_OFFSET:35076,MAX_PROGRAM_TEXEL_OFFSET:35077,MAX_VARYING_COMPONENTS:35659,TEXTURE_2D_ARRAY:35866,TEXTURE_BINDING_2D_ARRAY:35869,R11F_G11F_B10F:35898,UNSIGNED_INT_10F_11F_11F_REV:35899,RGB9_E5:35901,UNSIGNED_INT_5_9_9_9_REV:35902,TRANSFORM_FEEDBACK_BUFFER_MODE:35967,MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:35968,TRANSFORM_FEEDBACK_VARYINGS:35971,TRANSFORM_FEEDBACK_BUFFER_START:35972,TRANSFORM_FEEDBACK_BUFFER_SIZE:35973,TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:35976,RASTERIZER_DISCARD:35977,MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:35978,MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:35979,INTERLEAVED_ATTRIBS:35980,SEPARATE_ATTRIBS:35981,TRANSFORM_FEEDBACK_BUFFER:35982,TRANSFORM_FEEDBACK_BUFFER_BINDING:35983,RGBA32UI:36208,RGB32UI:36209,RGBA16UI:36214,RGB16UI:36215,RGBA8UI:36220,RGB8UI:36221,RGBA32I:36226,RGB32I:36227,RGBA16I:36232,RGB16I:36233,RGBA8I:36238,RGB8I:36239,RED_INTEGER:36244,RGB_INTEGER:36248,RGBA_INTEGER:36249,SAMPLER_2D_ARRAY:36289,SAMPLER_2D_ARRAY_SHADOW:36292,SAMPLER_CUBE_SHADOW:36293,UNSIGNED_INT_VEC2:36294,UNSIGNED_INT_VEC3:36295,UNSIGNED_INT_VEC4:36296,INT_SAMPLER_2D:36298,INT_SAMPLER_3D:36299,INT_SAMPLER_CUBE:36300,INT_SAMPLER_2D_ARRAY:36303,UNSIGNED_INT_SAMPLER_2D:36306,UNSIGNED_INT_SAMPLER_3D:36307,UNSIGNED_INT_SAMPLER_CUBE:36308,UNSIGNED_INT_SAMPLER_2D_ARRAY:36311,DEPTH_COMPONENT32F:36012,DEPTH32F_STENCIL8:36013,FLOAT_32_UNSIGNED_INT_24_8_REV:36269,FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:33296,FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:33297,FRAMEBUFFER_ATTACHMENT_RED_SIZE:33298,FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:33299,FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:33300,FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:33301,FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:33302,FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:33303,FRAMEBUFFER_DEFAULT:33304,UNSIGNED_INT_24_8:34042,DEPTH24_STENCIL8:35056,UNSIGNED_NORMALIZED:35863,DRAW_FRAMEBUFFER_BINDING:36006,READ_FRAMEBUFFER:36008,DRAW_FRAMEBUFFER:36009,READ_FRAMEBUFFER_BINDING:36010,RENDERBUFFER_SAMPLES:36011,FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER:36052,MAX_COLOR_ATTACHMENTS:36063,COLOR_ATTACHMENT1:36065,COLOR_ATTACHMENT2:36066,COLOR_ATTACHMENT3:36067,COLOR_ATTACHMENT4:36068,COLOR_ATTACHMENT5:36069,COLOR_ATTACHMENT6:36070,COLOR_ATTACHMENT7:36071,COLOR_ATTACHMENT8:36072,COLOR_ATTACHMENT9:36073,COLOR_ATTACHMENT10:36074,COLOR_ATTACHMENT11:36075,COLOR_ATTACHMENT12:36076,COLOR_ATTACHMENT13:36077,COLOR_ATTACHMENT14:36078,COLOR_ATTACHMENT15:36079,FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:36182,MAX_SAMPLES:36183,HALF_FLOAT:5131,RG:33319,RG_INTEGER:33320,R8:33321,RG8:33323,R16F:33325,R32F:33326,RG16F:33327,RG32F:33328,R8I:33329,R8UI:33330,R16I:33331,R16UI:33332,R32I:33333,R32UI:33334,RG8I:33335,RG8UI:33336,RG16I:33337,RG16UI:33338,RG32I:33339,RG32UI:33340,VERTEX_ARRAY_BINDING:34229,R8_SNORM:36756,RG8_SNORM:36757,RGB8_SNORM:36758,RGBA8_SNORM:36759,SIGNED_NORMALIZED:36764,COPY_READ_BUFFER:36662,COPY_WRITE_BUFFER:36663,COPY_READ_BUFFER_BINDING:36662,COPY_WRITE_BUFFER_BINDING:36663,UNIFORM_BUFFER:35345,UNIFORM_BUFFER_BINDING:35368,UNIFORM_BUFFER_START:35369,UNIFORM_BUFFER_SIZE:35370,MAX_VERTEX_UNIFORM_BLOCKS:35371,MAX_FRAGMENT_UNIFORM_BLOCKS:35373,MAX_COMBINED_UNIFORM_BLOCKS:35374,MAX_UNIFORM_BUFFER_BINDINGS:35375,MAX_UNIFORM_BLOCK_SIZE:35376,MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:35377,MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:35379,UNIFORM_BUFFER_OFFSET_ALIGNMENT:35380,ACTIVE_UNIFORM_BLOCKS:35382,UNIFORM_TYPE:35383,UNIFORM_SIZE:35384,UNIFORM_BLOCK_INDEX:35386,UNIFORM_OFFSET:35387,UNIFORM_ARRAY_STRIDE:35388,UNIFORM_MATRIX_STRIDE:35389,UNIFORM_IS_ROW_MAJOR:35390,UNIFORM_BLOCK_BINDING:35391,UNIFORM_BLOCK_DATA_SIZE:35392,UNIFORM_BLOCK_ACTIVE_UNIFORMS:35394,UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES:35395,UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER:35396,UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER:35398,INVALID_INDEX:4294967295,MAX_VERTEX_OUTPUT_COMPONENTS:37154,MAX_FRAGMENT_INPUT_COMPONENTS:37157,MAX_SERVER_WAIT_TIMEOUT:37137,OBJECT_TYPE:37138,SYNC_CONDITION:37139,SYNC_STATUS:37140,SYNC_FLAGS:37141,SYNC_FENCE:37142,SYNC_GPU_COMMANDS_COMPLETE:37143,UNSIGNALED:37144,SIGNALED:37145,ALREADY_SIGNALED:37146,TIMEOUT_EXPIRED:37147,CONDITION_SATISFIED:37148,WAIT_FAILED:37149,SYNC_FLUSH_COMMANDS_BIT:1,VERTEX_ATTRIB_ARRAY_DIVISOR:35070,ANY_SAMPLES_PASSED:35887,ANY_SAMPLES_PASSED_CONSERVATIVE:36202,SAMPLER_BINDING:35097,RGB10_A2UI:36975,INT_2_10_10_10_REV:36255,TRANSFORM_FEEDBACK:36386,TRANSFORM_FEEDBACK_PAUSED:36387,TRANSFORM_FEEDBACK_ACTIVE:36388,TRANSFORM_FEEDBACK_BINDING:36389,COMPRESSED_R11_EAC:37488,COMPRESSED_SIGNED_R11_EAC:37489,COMPRESSED_RG11_EAC:37490,COMPRESSED_SIGNED_RG11_EAC:37491,COMPRESSED_RGB8_ETC2:37492,COMPRESSED_SRGB8_ETC2:37493,COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:37494,COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:37495,COMPRESSED_RGBA8_ETC2_EAC:37496,COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:37497,TEXTURE_IMMUTABLE_FORMAT:37167,MAX_ELEMENT_INDEX:36203,TEXTURE_IMMUTABLE_LEVELS:33503,MAX_TEXTURE_MAX_ANISOTROPY_EXT:34047};return e(t)}),define("Core/ComponentDatatype",["./defaultValue","./defined","./DeveloperError","./FeatureDetection","./freezeObject","./WebGLConstants"],function(e,t,r,n,o,i){"use strict";if(!n.supportsTypedArrays())return{};var a={BYTE:i.BYTE,UNSIGNED_BYTE:i.UNSIGNED_BYTE,SHORT:i.SHORT,UNSIGNED_SHORT:i.UNSIGNED_SHORT,INT:i.INT,UNSIGNED_INT:i.UNSIGNED_INT,FLOAT:i.FLOAT,DOUBLE:i.DOUBLE};return a.getSizeInBytes=function(e){if(!t(e))throw new r("value is required.");switch(e){case a.BYTE:return Int8Array.BYTES_PER_ELEMENT;case a.UNSIGNED_BYTE:return Uint8Array.BYTES_PER_ELEMENT;case a.SHORT:return Int16Array.BYTES_PER_ELEMENT;case a.UNSIGNED_SHORT:return Uint16Array.BYTES_PER_ELEMENT;case a.INT:return Int32Array.BYTES_PER_ELEMENT;case a.UNSIGNED_INT:return Uint32Array.BYTES_PER_ELEMENT;case a.FLOAT:return Float32Array.BYTES_PER_ELEMENT;case a.DOUBLE:return Float64Array.BYTES_PER_ELEMENT;default:throw new r("componentDatatype is not a valid value.")}},a.fromTypedArray=function(e){return e instanceof Int8Array?a.BYTE:e instanceof Uint8Array?a.UNSIGNED_BYTE:e instanceof Int16Array?a.SHORT:e instanceof Uint16Array?a.UNSIGNED_SHORT:e instanceof Int32Array?a.INT:e instanceof Uint32Array?a.UNSIGNED_INT:e instanceof Float32Array?a.FLOAT:e instanceof Float64Array?a.DOUBLE:void 0},a.validate=function(e){return t(e)&&(e===a.BYTE||e===a.UNSIGNED_BYTE||e===a.SHORT||e===a.UNSIGNED_SHORT||e===a.INT||e===a.UNSIGNED_INT||e===a.FLOAT||e===a.DOUBLE)},a.createTypedArray=function(e,n){if(!t(e))throw new r("componentDatatype is required.");if(!t(n))throw new r("valuesOrLength is required.");switch(e){case a.BYTE:return new Int8Array(n);case a.UNSIGNED_BYTE:return new Uint8Array(n);case a.SHORT:return new Int16Array(n);case a.UNSIGNED_SHORT:return new Uint16Array(n);case a.INT:return new Int32Array(n);case a.UNSIGNED_INT:return new Uint32Array(n);case a.FLOAT:return new Float32Array(n);case a.DOUBLE:return new Float64Array(n);default:throw new r("componentDatatype is not a valid value.")}},a.createArrayBufferView=function(n,o,i,u){if(!t(n))throw new r("componentDatatype is required.");if(!t(o))throw new r("buffer is required.");switch(i=e(i,0),u=e(u,(o.byteLength-i)/a.getSizeInBytes(n)),n){case a.BYTE:return new Int8Array(o,i,u);case a.UNSIGNED_BYTE:return new Uint8Array(o,i,u);case a.SHORT:return new Int16Array(o,i,u);case a.UNSIGNED_SHORT:return new Uint16Array(o,i,u);case a.INT:return new Int32Array(o,i,u);case a.UNSIGNED_INT:return new Uint32Array(o,i,u);case a.FLOAT:return new Float32Array(o,i,u);case a.DOUBLE:return new Float64Array(o,i,u);default:throw new r("componentDatatype is not a valid value.")}},a.fromName=function(e){switch(e){case"BYTE":return a.BYTE;case"UNSIGNED_BYTE":return a.UNSIGNED_BYTE;case"SHORT":return a.SHORT;case"UNSIGNED_SHORT":return a.UNSIGNED_SHORT;case"INT":return a.INT;case"UNSIGNED_INT":return a.UNSIGNED_INT;case"FLOAT":return a.FLOAT;case"DOUBLE":return a.DOUBLE;default:throw new r("name is not a valid value.")}},o(a)}),define("Core/GeometryType",["./freezeObject"],function(e){"use strict";var t={NONE:0,TRIANGLES:1,LINES:2,POLYLINES:3};return e(t)}),define("Core/PrimitiveType",["./freezeObject","./WebGLConstants"],function(e,t){"use strict";var r={POINTS:t.POINTS,LINES:t.LINES,LINE_LOOP:t.LINE_LOOP,LINE_STRIP:t.LINE_STRIP,TRIANGLES:t.TRIANGLES,TRIANGLE_STRIP:t.TRIANGLE_STRIP,TRIANGLE_FAN:t.TRIANGLE_FAN,validate:function(e){return e===r.POINTS||e===r.LINES||e===r.LINE_LOOP||e===r.LINE_STRIP||e===r.TRIANGLES||e===r.TRIANGLE_STRIP||e===r.TRIANGLE_FAN}};return e(r)}),define("Core/Geometry",["./Check","./defaultValue","./defined","./DeveloperError","./GeometryType","./PrimitiveType"],function(e,t,r,n,o,i){"use strict";function a(r){r=t(r,t.EMPTY_OBJECT),e.typeOf.object("options.attributes",r.attributes),this.attributes=r.attributes,this.indices=r.indices,this.primitiveType=t(r.primitiveType,i.TRIANGLES),this.boundingSphere=r.boundingSphere,this.geometryType=t(r.geometryType,o.NONE),this.boundingSphereCV=r.boundingSphereCV}return a.computeNumberOfVertices=function(t){e.typeOf.object("geometry",t);var o=-1;for(var i in t.attributes)if(t.attributes.hasOwnProperty(i)&&r(t.attributes[i])&&r(t.attributes[i].values)){var a=t.attributes[i],u=a.values.length/a.componentsPerAttribute;if(o!==u&&-1!==o)throw new n("All attribute lists must have the same number of attributes.");o=u}return o},a}),define("Core/GeometryAttribute",["./defaultValue","./defined","./DeveloperError"],function(e,t,r){"use strict";function n(n){if(n=e(n,e.EMPTY_OBJECT),!t(n.componentDatatype))throw new r("options.componentDatatype is required.");if(!t(n.componentsPerAttribute))throw new r("options.componentsPerAttribute is required.");if(n.componentsPerAttribute<1||n.componentsPerAttribute>4)throw new r("options.componentsPerAttribute must be between 1 and 4.");if(!t(n.values))throw new r("options.values is required.");this.componentDatatype=n.componentDatatype,this.componentsPerAttribute=n.componentsPerAttribute,this.normalize=e(n.normalize,!1),this.values=n.values}return n}),define("Core/GeometryAttributes",["./defaultValue"],function(e){"use strict";function t(t){t=e(t,e.EMPTY_OBJECT),this.position=t.position,this.normal=t.normal,this.st=t.st,this.bitangent=t.bitangent,this.tangent=t.tangent,this.color=t.color}return t}),define("Core/IndexDatatype",["./defined","./DeveloperError","./freezeObject","./Math","./WebGLConstants"],function(e,t,r,n,o){"use strict";var i={UNSIGNED_BYTE:o.UNSIGNED_BYTE,UNSIGNED_SHORT:o.UNSIGNED_SHORT,UNSIGNED_INT:o.UNSIGNED_INT};return i.getSizeInBytes=function(e){switch(e){case i.UNSIGNED_BYTE:return Uint8Array.BYTES_PER_ELEMENT;case i.UNSIGNED_SHORT:return Uint16Array.BYTES_PER_ELEMENT;case i.UNSIGNED_INT:return Uint32Array.BYTES_PER_ELEMENT}throw new t("indexDatatype is required and must be a valid IndexDatatype constant.")},i.validate=function(t){return e(t)&&(t===i.UNSIGNED_BYTE||t===i.UNSIGNED_SHORT||t===i.UNSIGNED_INT)},i.createTypedArray=function(r,o){if(!e(r))throw new t("numberOfVertices is required.");return r>=n.SIXTY_FOUR_KILOBYTES?new Uint32Array(o):new Uint16Array(o)},i.createTypedArrayFromArrayBuffer=function(r,o,i,a){if(!e(r))throw new t("numberOfVertices is required.");if(!e(o))throw new t("sourceArray is required.");if(!e(i))throw new t("byteOffset is required.");return r>=n.SIXTY_FOUR_KILOBYTES?new Uint32Array(o,i,a):new Uint16Array(o,i,a)},r(i)}),define("Core/EllipsoidGeodesic",["./Cartesian3","./Cartographic","./Check","./defaultValue","./defined","./defineProperties","./Ellipsoid","./Math"],function(e,t,r,n,o,i,a,u){"use strict";function s(e){var t=e._uSquared,r=e._ellipsoid.maximumRadius,n=e._ellipsoid.minimumRadius,o=(r-n)/r,i=Math.cos(e._startHeading),a=Math.sin(e._startHeading),u=(1-o)*Math.tan(e._start.latitude),s=1/Math.sqrt(1+u*u),c=s*u,l=Math.atan2(u,i),f=s*a,E=f*f,h=1-E,d=Math.sqrt(h),p=t/4,_=p*p,m=_*p,O=_*_,R=1+p-3*_/4+5*m/4-175*O/64,y=1-p+15*_/8-35*m/8,T=1-3*p+35*_/4,A=1-5*p,S=R*l-y*Math.sin(2*l)*p/2-T*Math.sin(4*l)*_/16-A*Math.sin(6*l)*m/48-5*Math.sin(8*l)*O/512,N=e._constants;N.a=r,N.b=n,N.f=o,N.cosineHeading=i,N.sineHeading=a,N.tanU=u,N.cosineU=s,N.sineU=c,N.sigma=l,N.sineAlpha=f,N.sineSquaredAlpha=E,N.cosineSquaredAlpha=h,N.cosineAlpha=d,N.u2Over4=p,N.u4Over16=_,N.u6Over64=m,N.u8Over256=O,N.a0=R,N.a1=y,N.a2=T,N.a3=A,N.distanceRatio=S}function c(e,t){return e*t*(4+e*(4-3*t))/16}function l(e,t,r,n,o,i,a){var u=c(e,r);return(1-u)*e*t*(n+u*o*(a+u*i*(2*a*a-1)))}function f(e,t,r,n,o,i,a){var s,c,f,E,h,d=(t-r)/t,p=i-n,_=Math.atan((1-d)*Math.tan(o)),m=Math.atan((1-d)*Math.tan(a)),O=Math.cos(_),R=Math.sin(_),y=Math.cos(m),T=Math.sin(m),A=O*y,S=O*T,N=R*T,C=R*y,g=p,I=u.TWO_PI,b=Math.cos(g),M=Math.sin(g);do{b=Math.cos(g),M=Math.sin(g);var w=S-C*b;f=Math.sqrt(y*y*M*M+w*w),c=N+A*b,s=Math.atan2(f,c);var v;0===f?(v=0,E=1):(v=A*M/f,E=1-v*v),I=g,h=c-2*N/E,isNaN(h)&&(h=0),g=p+l(d,v,E,s,f,c,h)}while(Math.abs(g-I)>u.EPSILON12);var F=E*(t*t-r*r)/(r*r),L=1+F*(4096+F*(F*(320-175*F)-768))/16384,P=F*(256+F*(F*(74-47*F)-128))/1024,D=h*h,U=P*f*(h+P*(c*(2*D-1)-P*h*(4*f*f-3)*(4*D-3)/6)/4),B=r*L*(s-U),x=Math.atan2(y*M,S-C*b),G=Math.atan2(O*M,S*b-C);e._distance=B,e._startHeading=x,e._endHeading=G,e._uSquared=F}function E(n,o,i,a){var u=e.normalize(a.cartographicToCartesian(o,p),d),c=e.normalize(a.cartographicToCartesian(i,p),p);r.typeOf.number.greaterThanOrEquals("value",Math.abs(Math.abs(e.angleBetween(u,c))-Math.PI),.0125),f(n,a.maximumRadius,a.minimumRadius,o.longitude,o.latitude,i.longitude,i.latitude),n._start=t.clone(o,n._start),n._end=t.clone(i,n._end),n._start.height=0,n._end.height=0,s(n)}function h(e,r,i){var u=n(i,a.WGS84);this._ellipsoid=u,this._start=new t,this._end=new t,this._constants={},this._startHeading=void 0,this._endHeading=void 0,this._distance=void 0,this._uSquared=void 0,o(e)&&o(r)&&E(this,e,r,u)}var d=new e,p=new e;return i(h.prototype,{ellipsoid:{get:function(){return this._ellipsoid}},surfaceDistance:{get:function(){return r.defined("distance",this._distance),this._distance}},start:{get:function(){return this._start}},end:{get:function(){return this._end}},startHeading:{get:function(){return r.defined("distance",this._distance),this._startHeading}},endHeading:{get:function(){return r.defined("distance",this._distance),this._endHeading}}}),h.prototype.setEndPoints=function(e,t){r.defined("start",e),r.defined("end",t),E(this,e,t,this._ellipsoid)},h.prototype.interpolateUsingFraction=function(e,t){return this.interpolateUsingSurfaceDistance(this._distance*e,t)},h.prototype.interpolateUsingSurfaceDistance=function(e,n){r.defined("distance",this._distance);var i=this._constants,a=i.distanceRatio+e/i.b,u=Math.cos(2*a),s=Math.cos(4*a),c=Math.cos(6*a),f=Math.sin(2*a),E=Math.sin(4*a),h=Math.sin(6*a),d=Math.sin(8*a),p=a*a,_=a*p,m=i.u8Over256,O=i.u2Over4,R=i.u6Over64,y=i.u4Over16,T=2*_*m*u/3+a*(1-O+7*y/4-15*R/4+579*m/64-(y-15*R/4+187*m/16)*u-(5*R/4-115*m/16)*s-29*m*c/16)+(O/2-y+71*R/32-85*m/16)*f+(5*y/16-5*R/4+383*m/96)*E-p*((R-11*m/2)*f+5*m*E/2)+(29*R/96-29*m/16)*h+539*m*d/1536,A=Math.asin(Math.sin(T)*i.cosineAlpha),S=Math.atan(i.a/i.b*Math.tan(A));T-=i.sigma;var N=Math.cos(2*i.sigma+T),C=Math.sin(T),g=Math.cos(T),I=i.cosineU*g,b=i.sineU*C,M=Math.atan2(C*i.sineHeading,I-b*i.cosineHeading),w=M-l(i.f,i.sineAlpha,i.cosineSquaredAlpha,T,C,g,N);return o(n)?(n.longitude=this._start.longitude+w,n.latitude=S,n.height=0,n):new t(this._start.longitude+w,S,0)},h}),define("Core/QuadraticRealPolynomial",["./DeveloperError","./Math"],function(e,t){"use strict";function r(e,r,n){var o=e+r;return t.sign(e)!==t.sign(r)&&Math.abs(o/Math.max(Math.abs(e),Math.abs(r)))<n?0:o}var n={};return n.computeDiscriminant=function(t,r,n){if("number"!=typeof t)throw new e("a is a required number.");if("number"!=typeof r)throw new e("b is a required number.");if("number"!=typeof n)throw new e("c is a required number.");var o=r*r-4*t*n;return o},n.computeRealRoots=function(n,o,i){if("number"!=typeof n)throw new e("a is a required number.");if("number"!=typeof o)throw new e("b is a required number.");if("number"!=typeof i)throw new e("c is a required number.");var a;if(0===n)return 0===o?[]:[-i/o];if(0===o){if(0===i)return[0,0];var u=Math.abs(i),s=Math.abs(n);if(s>u&&u/s<t.EPSILON14)return[0,0];if(u>s&&s/u<t.EPSILON14)return[];if(a=-i/n,0>a)return[];var c=Math.sqrt(a);return[-c,c]}if(0===i)return a=-o/n,0>a?[a,0]:[0,a];var l=o*o,f=4*n*i,E=r(l,-f,t.EPSILON14);if(0>E)return[];var h=-.5*r(o,t.sign(o)*Math.sqrt(E),t.EPSILON14);return o>0?[h/n,i/h]:[i/h,h/n]},n}),define("Core/CubicRealPolynomial",["./DeveloperError","./QuadraticRealPolynomial"],function(e,t){"use strict";function r(e,t,r,n){var o,i,a=e,u=t/3,s=r/3,c=n,l=a*s,f=u*c,E=u*u,h=s*s,d=a*s-E,p=a*c-u*s,_=u*c-h,m=4*d*_-p*p;if(0>m){var O,R,y;E*f>=l*h?(O=a,R=d,y=-2*u*d+a*p):(O=c,R=_,y=-c*p+2*s*_);var T=0>y?-1:1,A=-T*Math.abs(O)*Math.sqrt(-m);i=-y+A;var S=i/2,N=0>S?-Math.pow(-S,1/3):Math.pow(S,1/3),C=i===A?-N:-R/N;return o=0>=R?N+C:-y/(N*N+C*C+R),E*f>=l*h?[(o-u)/a]:[-c/(o+s)]}var g=d,I=-2*u*d+a*p,b=_,M=-c*p+2*s*_,w=Math.sqrt(m),v=Math.sqrt(3)/2,F=Math.abs(Math.atan2(a*w,-I)/3);o=2*Math.sqrt(-g);var L=Math.cos(F);i=o*L;var P=o*(-L/2-v*Math.sin(F)),D=i+P>2*u?i-u:P-u,U=a,B=D/U;F=Math.abs(Math.atan2(c*w,-M)/3),o=2*Math.sqrt(-b),L=Math.cos(F),i=o*L,P=o*(-L/2-v*Math.sin(F));var x=-c,G=2*s>i+P?i+s:P+s,q=x/G,j=U*G,z=-D*G-U*x,V=D*x,H=(s*z-u*V)/(-u*z+s*j);return H>=B?q>=B?q>=H?[B,H,q]:[B,q,H]:[q,B,H]:q>=B?[H,B,q]:q>=H?[H,q,B]:[q,H,B]}var n={};return n.computeDiscriminant=function(t,r,n,o){if("number"!=typeof t)throw new e("a is a required number.");if("number"!=typeof r)throw new e("b is a required number.");if("number"!=typeof n)throw new e("c is a required number.");if("number"!=typeof o)throw new e("d is a required number.");var i=t*t,a=r*r,u=n*n,s=o*o,c=18*t*r*n*o+a*u-27*i*s-4*(t*u*n+a*r*o);return c},n.computeRealRoots=function(n,o,i,a){if("number"!=typeof n)throw new e("a is a required number.");if("number"!=typeof o)throw new e("b is a required number.");if("number"!=typeof i)throw new e("c is a required number.");if("number"!=typeof a)throw new e("d is a required number.");var u,s;if(0===n)return t.computeRealRoots(o,i,a);if(0===o){if(0===i){if(0===a)return[0,0,0];s=-a/n;var c=0>s?-Math.pow(-s,1/3):Math.pow(s,1/3);return[c,c,c]}return 0===a?(u=t.computeRealRoots(n,0,i),0===u.Length?[0]:[u[0],0,u[1]]):r(n,0,i,a)}return 0===i?0===a?(s=-o/n,0>s?[s,0,0]:[0,0,s]):r(n,o,0,a):0===a?(u=t.computeRealRoots(n,o,i),0===u.length?[0]:u[1]<=0?[u[0],u[1],0]:u[0]>=0?[0,u[0],u[1]]:[u[0],0,u[1]]):r(n,o,i,a)},n}),define("Core/QuarticRealPolynomial",["./CubicRealPolynomial","./DeveloperError","./Math","./QuadraticRealPolynomial"],function(e,t,r,n){"use strict";function o(t,o,i,a){var u=t*t,s=o-3*u/8,c=i-o*t/2+u*t/8,l=a-i*t/4+o*u/16-3*u*u/256,f=e.computeRealRoots(1,2*s,s*s-4*l,-c*c);if(f.length>0){var E=-t/4,h=f[f.length-1];if(Math.abs(h)<r.EPSILON14){var d=n.computeRealRoots(1,s,l);if(2===d.length){var p,_=d[0],m=d[1];if(_>=0&&m>=0){var O=Math.sqrt(_),R=Math.sqrt(m);return[E-R,E-O,E+O,E+R]}if(_>=0&&0>m)return p=Math.sqrt(_),[E-p,E+p];if(0>_&&m>=0)return p=Math.sqrt(m),[E-p,E+p]}return[]}if(h>0){var y=Math.sqrt(h),T=(s+h-c/y)/2,A=(s+h+c/y)/2,S=n.computeRealRoots(1,y,T),N=n.computeRealRoots(1,-y,A);return 0!==S.length?(S[0]+=E,S[1]+=E,0!==N.length?(N[0]+=E,N[1]+=E,S[1]<=N[0]?[S[0],S[1],N[0],N[1]]:N[1]<=S[0]?[N[0],N[1],S[0],S[1]]:S[0]>=N[0]&&S[1]<=N[1]?[N[0],S[0],S[1],N[1]]:N[0]>=S[0]&&N[1]<=S[1]?[S[0],N[0],N[1],S[1]]:S[0]>N[0]&&S[0]<N[1]?[N[0],S[0],N[1],S[1]]:[S[0],N[0],S[1],N[1]]):S):0!==N.length?(N[0]+=E,N[1]+=E,N):[]}}return[]}function i(t,o,i,a){var u=i*i,s=o*o,c=t*t,l=-2*o,f=i*t+s-4*a,E=c*a-i*o*t+u,h=e.computeRealRoots(1,l,f,E);if(h.length>0){var d,p,_=h[0],m=o-_,O=m*m,R=t/2,y=m/2,T=O-4*a,A=O+4*Math.abs(a),S=c-4*_,N=c+4*Math.abs(_);if(0>_||S*A>T*N){var C=Math.sqrt(S);d=C/2,p=0===C?0:(t*y-i)/C}else{var g=Math.sqrt(T);d=0===g?0:(t*y-i)/g,p=g/2}var I,b;0===R&&0===d?(I=0,b=0):r.sign(R)===r.sign(d)?(I=R+d,b=_/I):(b=R-d,I=_/b);var M,w;0===y&&0===p?(M=0,w=0):r.sign(y)===r.sign(p)?(M=y+p,w=a/M):(w=y-p,M=a/w);var v=n.computeRealRoots(1,I,M),F=n.computeRealRoots(1,b,w);if(0!==v.length)return 0!==F.length?v[1]<=F[0]?[v[0],v[1],F[0],F[1]]:F[1]<=v[0]?[F[0],F[1],v[0],v[1]]:v[0]>=F[0]&&v[1]<=F[1]?[F[0],v[0],v[1],F[1]]:F[0]>=v[0]&&F[1]<=v[1]?[v[0],F[0],F[1],v[1]]:v[0]>F[0]&&v[0]<F[1]?[F[0],v[0],F[1],v[1]]:[v[0],F[0],v[1],F[1]]:v;if(0!==F.length)return F}return[]}var a={};return a.computeDiscriminant=function(e,r,n,o,i){if("number"!=typeof e)throw new t("a is a required number.");if("number"!=typeof r)throw new t("b is a required number.");if("number"!=typeof n)throw new t("c is a required number.");if("number"!=typeof o)throw new t("d is a required number.");if("number"!=typeof i)throw new t("e is a required number.");var a=e*e,u=a*e,s=r*r,c=s*r,l=n*n,f=l*n,E=o*o,h=E*o,d=i*i,p=d*i,_=s*l*E-4*c*h-4*e*f*E+18*e*r*n*h-27*a*E*E+256*u*p+i*(18*c*n*o-4*s*f+16*e*l*l-80*e*r*l*o-6*e*s*E+144*a*n*E)+d*(144*e*s*n-27*s*s-128*a*l-192*a*r*o);return _},a.computeRealRoots=function(n,a,u,s,c){if("number"!=typeof n)throw new t("a is a required number.");if("number"!=typeof a)throw new t("b is a required number.");if("number"!=typeof u)throw new t("c is a required number.");if("number"!=typeof s)throw new t("d is a required number.");if("number"!=typeof c)throw new t("e is a required number.");if(Math.abs(n)<r.EPSILON15)return e.computeRealRoots(a,u,s,c);var l=a/n,f=u/n,E=s/n,h=c/n,d=0>l?1:0;switch(d+=0>f?d+1:d,d+=0>E?d+1:d,d+=0>h?d+1:d){case 0:return o(l,f,E,h);case 1:return i(l,f,E,h);case 2:return i(l,f,E,h);case 3:return o(l,f,E,h);case 4:return o(l,f,E,h);case 5:return i(l,f,E,h);case 6:return o(l,f,E,h);case 7:return o(l,f,E,h);case 8:return i(l,f,E,h);case 9:return o(l,f,E,h);case 10:return o(l,f,E,h);case 11:return i(l,f,E,h);case 12:return o(l,f,E,h);case 13:return o(l,f,E,h);case 14:return o(l,f,E,h);case 15:return o(l,f,E,h);default:return}},a}),define("Core/Ray",["./Cartesian3","./defaultValue","./defined","./DeveloperError"],function(e,t,r,n){"use strict";function o(r,n){n=e.clone(t(n,e.ZERO)),e.equals(n,e.ZERO)||e.normalize(n,n),this.origin=e.clone(t(r,e.ZERO)),this.direction=n}return o.getPoint=function(t,o,i){if(!r(t))throw new n("ray is requred");if("number"!=typeof o)throw new n("t is a required number");return r(i)||(i=new e),i=e.multiplyByScalar(t.direction,o,i),e.add(t.origin,i,i)},o}),define("Core/IntersectionTests",["./Cartesian3","./Cartographic","./defaultValue","./defined","./DeveloperError","./Interval","./Math","./Matrix3","./QuadraticRealPolynomial","./QuarticRealPolynomial","./Ray"],function(e,t,r,n,o,i,a,u,s,c,l){"use strict";function f(e,t,r,n){var o=t*t-4*e*r;if(!(0>o)){if(o>0){var i=1/(2*e),a=Math.sqrt(o),u=(-t+a)*i,s=(-t-a)*i;return s>u?(n.root0=u,n.root1=s):(n.root0=s,n.root1=u),n}var c=-t/(2*e);if(0!==c)return n.root0=n.root1=c,n}}function E(t,r,o){n(o)||(o=new i);var a=t.origin,u=t.direction,s=r.center,c=r.radius*r.radius,l=e.subtract(a,s,O),E=e.dot(u,u),h=2*e.dot(u,l),d=e.magnitudeSquared(l)-c,p=f(E,h,d,A);return n(p)?(o.start=p.root0,o.stop=p.root1,o):void 0}function h(e,t,r){var n=e+t;return a.sign(e)!==a.sign(t)&&Math.abs(n/Math.max(Math.abs(e),Math.abs(t)))<r?0:n}function d(t,r,n,o,i){var l,f=o*o,E=i*i,d=(t[u.COLUMN1ROW1]-t[u.COLUMN2ROW2])*E,p=i*(o*h(t[u.COLUMN1ROW0],t[u.COLUMN0ROW1],a.EPSILON15)+r.y),_=t[u.COLUMN0ROW0]*f+t[u.COLUMN2ROW2]*E+o*r.x+n,m=E*h(t[u.COLUMN2ROW1],t[u.COLUMN1ROW2],a.EPSILON15),O=i*(o*h(t[u.COLUMN2ROW0],t[u.COLUMN0ROW2])+r.z),R=[];if(0===O&&0===m){if(l=s.computeRealRoots(d,p,_),0===l.length)return R;var y=l[0],T=Math.sqrt(Math.max(1-y*y,0));if(R.push(new e(o,i*y,i*-T)),R.push(new e(o,i*y,i*T)),2===l.length){var A=l[1],S=Math.sqrt(Math.max(1-A*A,0));R.push(new e(o,i*A,i*-S)),R.push(new e(o,i*A,i*S))}return R}var N=O*O,C=m*m,g=d*d,I=O*m,b=g+C,M=2*(p*d+I),w=2*_*d+p*p-C+N,v=2*(_*p-I),F=_*_-N;if(0===b&&0===M&&0===w&&0===v)return R;l=c.computeRealRoots(b,M,w,v,F);var L=l.length;if(0===L)return R;for(var P=0;L>P;++P){var D,U=l[P],B=U*U,x=Math.max(1-B,0),G=Math.sqrt(x);D=a.sign(d)===a.sign(_)?h(d*B+_,p*U,a.EPSILON12):a.sign(_)===a.sign(p*U)?h(d*B,p*U+_,a.EPSILON12):h(d*B+p*U,_,a.EPSILON12);
var q=h(m*U,O,a.EPSILON15),j=D*q;0>j?R.push(new e(o,i*U,i*G)):j>0?R.push(new e(o,i*U,i*-G)):0!==G?(R.push(new e(o,i*U,i*-G)),R.push(new e(o,i*U,i*G)),++P):R.push(new e(o,i*U,i*G))}return R}var p={};p.rayPlane=function(t,r,i){if(!n(t))throw new o("ray is required.");if(!n(r))throw new o("plane is required.");n(i)||(i=new e);var u=t.origin,s=t.direction,c=r.normal,l=e.dot(c,s);if(!(Math.abs(l)<a.EPSILON15)){var f=(-r.distance-e.dot(c,u))/l;if(!(0>f))return i=e.multiplyByScalar(s,f,i),e.add(u,i,i)}};var _=new e,m=new e,O=new e,R=new e,y=new e;p.rayTriangleParametric=function(t,i,u,s,c){if(!n(t))throw new o("ray is required.");if(!n(i))throw new o("p0 is required.");if(!n(u))throw new o("p1 is required.");if(!n(s))throw new o("p2 is required.");c=r(c,!1);var l,f,E,h,d,p=t.origin,T=t.direction,A=e.subtract(u,i,_),S=e.subtract(s,i,m),N=e.cross(T,S,O),C=e.dot(A,N);if(c){if(C<a.EPSILON6)return;if(l=e.subtract(p,i,R),E=e.dot(l,N),0>E||E>C)return;if(f=e.cross(l,A,y),h=e.dot(T,f),0>h||E+h>C)return;d=e.dot(S,f)/C}else{if(Math.abs(C)<a.EPSILON6)return;var g=1/C;if(l=e.subtract(p,i,R),E=e.dot(l,N)*g,0>E||E>1)return;if(f=e.cross(l,A,y),h=e.dot(T,f)*g,0>h||E+h>1)return;d=e.dot(S,f)*g}return d},p.rayTriangle=function(t,r,o,i,a,u){var s=p.rayTriangleParametric(t,r,o,i,a);if(n(s)&&!(0>s))return n(u)||(u=new e),e.multiplyByScalar(t.direction,s,u),e.add(t.origin,u,u)};var T=new l;p.lineSegmentTriangle=function(t,r,i,a,u,s,c){if(!n(t))throw new o("v0 is required.");if(!n(r))throw new o("v1 is required.");if(!n(i))throw new o("p0 is required.");if(!n(a))throw new o("p1 is required.");if(!n(u))throw new o("p2 is required.");var l=T;e.clone(t,l.origin),e.subtract(r,t,l.direction),e.normalize(l.direction,l.direction);var f=p.rayTriangleParametric(l,i,a,u,s);return!n(f)||0>f||f>e.distance(t,r)?void 0:(n(c)||(c=new e),e.multiplyByScalar(l.direction,f,c),e.add(l.origin,c,c))};var A={root0:0,root1:0};p.raySphere=function(e,t,r){if(!n(e))throw new o("ray is required.");if(!n(t))throw new o("sphere is required.");return r=E(e,t,r),!n(r)||r.stop<0?void 0:(r.start=Math.max(r.start,0),r)};var S=new l;p.lineSegmentSphere=function(t,r,i,a){if(!n(t))throw new o("p0 is required.");if(!n(r))throw new o("p1 is required.");if(!n(i))throw new o("sphere is required.");var u=S;e.clone(t,u.origin);var s=e.subtract(r,t,u.direction),c=e.magnitude(s);return e.normalize(s,s),a=E(u,i,a),!n(a)||a.stop<0||a.start>c?void 0:(a.start=Math.max(a.start,0),a.stop=Math.min(a.stop,c),a)};var N=new e,C=new e;p.rayEllipsoid=function(t,r){if(!n(t))throw new o("ray is required.");if(!n(r))throw new o("ellipsoid is required.");var a,u,s,c,l,f=r.oneOverRadii,E=e.multiplyComponents(f,t.origin,N),h=e.multiplyComponents(f,t.direction,C),d=e.magnitudeSquared(E),p=e.dot(E,h);if(d>1){if(p>=0)return;var _=p*p;if(a=d-1,u=e.magnitudeSquared(h),s=u*a,s>_)return;if(_>s){c=p*p-s,l=-p+Math.sqrt(c);var m=l/u,O=a/l;return O>m?new i(m,O):{start:O,stop:m}}var R=Math.sqrt(a/u);return new i(R,R)}return 1>d?(a=d-1,u=e.magnitudeSquared(h),s=u*a,c=p*p-s,l=-p+Math.sqrt(c),new i(0,l/u)):0>p?(u=e.magnitudeSquared(h),new i(0,-p/u)):void 0};var g=new e,I=new e,b=new e,M=new e,w=new e,v=new u,F=new u,L=new u,P=new u,D=new u,U=new u,B=new u,x=new e,G=new e,q=new t;p.grazingAltitudeLocation=function(t,r){if(!n(t))throw new o("ray is required.");if(!n(r))throw new o("ellipsoid is required.");var i=t.origin,s=t.direction;if(!e.equals(i,e.ZERO)){var c=r.geodeticSurfaceNormal(i,g);if(e.dot(s,c)>=0)return i}var l=n(this.rayEllipsoid(t,r)),f=r.transformPositionToScaledSpace(s,g),E=e.normalize(f,f),h=e.mostOrthogonalAxis(f,M),p=e.normalize(e.cross(h,E,I),I),_=e.normalize(e.cross(E,p,b),b),m=v;m[0]=E.x,m[1]=E.y,m[2]=E.z,m[3]=p.x,m[4]=p.y,m[5]=p.z,m[6]=_.x,m[7]=_.y,m[8]=_.z;var O=u.transpose(m,F),R=u.fromScale(r.radii,L),y=u.fromScale(r.oneOverRadii,P),T=D;T[0]=0,T[1]=-s.z,T[2]=s.y,T[3]=s.z,T[4]=0,T[5]=-s.x,T[6]=-s.y,T[7]=s.x,T[8]=0;var A,S,N=u.multiply(u.multiply(O,y,U),T,U),C=u.multiply(u.multiply(N,R,B),m,B),j=u.multiplyByVector(N,i,w),z=d(C,e.negate(j,g),0,0,1),V=z.length;if(V>0){for(var H=e.clone(e.ZERO,G),X=Number.NEGATIVE_INFINITY,W=0;V>W;++W){A=u.multiplyByVector(R,u.multiplyByVector(m,z[W],x),x);var Y=e.normalize(e.subtract(A,i,M),M),K=e.dot(Y,s);K>X&&(X=K,H=e.clone(A,H))}var k=r.cartesianToCartographic(H,q);return X=a.clamp(X,0,1),S=e.magnitude(e.subtract(H,i,M))*Math.sqrt(1-X*X),S=l?-S:S,k.height=S,r.cartographicToCartesian(k,new e)}};var j=new e;return p.lineSegmentPlane=function(t,r,i,u){if(!n(t))throw new o("endPoint0 is required.");if(!n(r))throw new o("endPoint1 is required.");if(!n(i))throw new o("plane is required.");n(u)||(u=new e);var s=e.subtract(r,t,j),c=i.normal,l=e.dot(c,s);if(!(Math.abs(l)<a.EPSILON6)){var f=e.dot(c,t),E=-(i.distance+f)/l;if(!(0>E||E>1))return e.multiplyByScalar(s,E,u),e.add(t,u,u),u}},p.trianglePlaneIntersection=function(t,r,i,a){if(!(n(t)&&n(r)&&n(i)&&n(a)))throw new o("p0, p1, p2, and plane are required.");var u=a.normal,s=a.distance,c=e.dot(u,t)+s<0,l=e.dot(u,r)+s<0,f=e.dot(u,i)+s<0,E=0;E+=c?1:0,E+=l?1:0,E+=f?1:0;var h,d;if((1===E||2===E)&&(h=new e,d=new e),1===E){if(c)return p.lineSegmentPlane(t,r,a,h),p.lineSegmentPlane(t,i,a,d),{positions:[t,r,i,h,d],indices:[0,3,4,1,2,4,1,4,3]};if(l)return p.lineSegmentPlane(r,i,a,h),p.lineSegmentPlane(r,t,a,d),{positions:[t,r,i,h,d],indices:[1,3,4,2,0,4,2,4,3]};if(f)return p.lineSegmentPlane(i,t,a,h),p.lineSegmentPlane(i,r,a,d),{positions:[t,r,i,h,d],indices:[2,3,4,0,1,4,0,4,3]}}else if(2===E){if(!c)return p.lineSegmentPlane(r,t,a,h),p.lineSegmentPlane(i,t,a,d),{positions:[t,r,i,h,d],indices:[1,2,4,1,4,3,0,3,4]};if(!l)return p.lineSegmentPlane(i,r,a,h),p.lineSegmentPlane(t,r,a,d),{positions:[t,r,i,h,d],indices:[2,0,4,2,4,3,1,3,4]};if(!f)return p.lineSegmentPlane(t,i,a,h),p.lineSegmentPlane(r,i,a,d),{positions:[t,r,i,h,d],indices:[0,1,4,0,4,3,2,3,4]}}},p}),define("Core/isArray",["./defined"],function(e){"use strict";var t=Array.isArray;return e(t)||(t=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),t}),define("Core/Plane",["./Cartesian3","./defined","./DeveloperError","./freezeObject","./Math"],function(e,t,r,n,o){"use strict";function i(n,i){if(!t(n))throw new r("normal is required.");if(!o.equalsEpsilon(e.magnitude(n),1,o.EPSILON6))throw new r("normal must be normalized.");if(!t(i))throw new r("distance is required.");this.normal=e.clone(n),this.distance=i}i.fromPointNormal=function(n,a,u){if(!t(n))throw new r("point is required.");if(!t(a))throw new r("normal is required.");if(!o.equalsEpsilon(e.magnitude(a),1,o.EPSILON6))throw new r("normal must be normalized.");var s=-e.dot(a,n);return t(u)?(e.clone(a,u.normal),u.distance=s,u):new i(a,s)};var a=new e;return i.fromCartesian4=function(n,u){if(!t(n))throw new r("coefficients is required.");var s=e.fromCartesian4(n,a),c=n.w;if(!o.equalsEpsilon(e.magnitude(s),1,o.EPSILON6))throw new r("normal must be normalized.");return t(u)?(e.clone(s,u.normal),u.distance=c,u):new i(s,c)},i.getPointDistance=function(n,o){if(!t(n))throw new r("plane is required.");if(!t(o))throw new r("point is required.");return e.dot(n.normal,o)+n.distance},i.ORIGIN_XY_PLANE=n(new i(e.UNIT_Z,0)),i.ORIGIN_YZ_PLANE=n(new i(e.UNIT_X,0)),i.ORIGIN_ZX_PLANE=n(new i(e.UNIT_Y,0)),i}),define("Core/PolylinePipeline",["./Cartesian3","./Cartographic","./defaultValue","./defined","./DeveloperError","./Ellipsoid","./EllipsoidGeodesic","./IntersectionTests","./isArray","./Math","./Matrix4","./Plane"],function(e,t,r,n,o,i,a,u,s,c,l,f){"use strict";function E(e,t,r){var n=C;n.length=e;var o;if(t===r){for(o=0;e>o;o++)n[o]=t;return n}var i=r-t,a=i/e;for(o=0;e>o;o++){var u=t+o*a;n[o]=u}return n}function h(e,t){var r=C;r.length=e;for(var n=0;e>n;n++)r[n]=t*Math.sin(Math.PI*n/e);return r}function d(t,r,n,o,i,a,u,s,c){var l=o.scaleToGeodeticSurface(t,M),f=o.scaleToGeodeticSurface(r,w),d=p.numberOfPoints(t,r,n),_=o.cartesianToCartographic(l,g),m=o.cartesianToCartographic(f,I),O=void 0;O=c>0?h(d,c):E(d,i,a),v.setEndPoints(_,m);var R=v.surfaceDistance/d,y=s;_.height=i;var T=o.cartographicToCartesian(_,b);e.pack(T,u,y),y+=3;for(var A=1;d>A;A++){var S=v.interpolateUsingSurfaceDistance(A*R,I);S.height=O[A],T=o.cartographicToCartesian(S,b),e.pack(T,u,y),y+=3}return y}var p={};p.numberOfPoints=function(t,r,n){var o=e.distance(t,r);return Math.ceil(o/n)};var _=new t;p.extractHeights=function(e,t){for(var r=e.length,n=new Array(r),o=0;r>o;o++){var i=e[o];n[o]=t.cartesianToCartographic(i,_).height}return n};var m=new l,O=new e,R=new e,y=new f(e.UNIT_X,0),T=new e,A=new f(e.UNIT_X,0),S=new e,N=new e,C=[],g=new t,I=new t,b=new e,M=new e,w=new e,v=new a;return p.wrapLongitude=function(t,o){var i=[],a=[];if(n(t)&&t.length>0){o=r(o,l.IDENTITY);var s=l.inverseTransformation(o,m),c=l.multiplyByPoint(s,e.ZERO,O),E=e.normalize(l.multiplyByPointAsVector(s,e.UNIT_Y,R),R),h=f.fromPointNormal(c,E,y),d=e.normalize(l.multiplyByPointAsVector(s,e.UNIT_X,T),T),p=f.fromPointNormal(c,d,A),_=1;i.push(e.clone(t[0]));for(var C=i[0],g=t.length,I=1;g>I;++I){var b=t[I];if(f.getPointDistance(p,C)<0||f.getPointDistance(p,b)<0){var M=u.lineSegmentPlane(C,b,h,S);if(n(M)){var w=e.multiplyByScalar(E,5e-9,N);f.getPointDistance(h,C)<0&&e.negate(w,w),i.push(e.add(M,w,new e)),a.push(_+1),e.negate(w,w),i.push(e.add(M,w,new e)),_=1}}i.push(e.clone(t[I])),_++,C=b}a.push(_)}return{positions:i,lengths:a}},p.generateArc=function(t){n(t)||(t={});var a=t.positions;if(!n(a))throw new o("options.positions is required.");var u=a.length,l=r(t.ellipsoid,i.WGS84),f=r(t.height,0),E=s(f);if(1>u)return[];if(1===u){var h=l.scaleToGeodeticSurface(a[0],M);if(f=E?f[0]:f,0!==f){var _=l.geodeticSurfaceNormal(h,b);e.multiplyByScalar(_,f,_),e.add(h,_,h)}return[h.x,h.y,h.z]}var m=t.minDistance;if(!n(m)){var O=r(t.granularity,c.RADIANS_PER_DEGREE);m=c.chordLength(O,l.maximumRadius)}var R,y=0;for(R=0;u-1>R;R++)y+=p.numberOfPoints(a[R],a[R+1],m);var T=t.hMax,A=3*(y+1),S=new Array(A),N=0;for(R=0;u-1>R;R++){var I=a[R],w=a[R+1],v=E?f[R]:f,F=E?f[R+1]:f;N=d(I,w,m,l,v,F,S,N,T)}C.length=0;var L=a[u-1],P=l.cartesianToCartographic(L,g);P.height=E?f[u-1]:f;var D=l.cartographicToCartesian(P,b);return e.pack(D,S,A-3),S},p.generateCartesianArc=function(t){for(var r=p.generateArc(t),n=r.length/3,o=new Array(n),i=0;n>i;i++)o[i]=e.unpack(r,3*i);return o},p}),define("Core/VertexFormat",["./defaultValue","./defined","./DeveloperError","./freezeObject"],function(e,t,r,n){"use strict";function o(t){t=e(t,e.EMPTY_OBJECT),this.position=e(t.position,!1),this.normal=e(t.normal,!1),this.st=e(t.st,!1),this.bitangent=e(t.bitangent,!1),this.tangent=e(t.tangent,!1),this.color=e(t.color,!1)}return o.POSITION_ONLY=n(new o({position:!0})),o.POSITION_AND_NORMAL=n(new o({position:!0,normal:!0})),o.POSITION_NORMAL_AND_ST=n(new o({position:!0,normal:!0,st:!0})),o.POSITION_AND_ST=n(new o({position:!0,st:!0})),o.POSITION_AND_COLOR=n(new o({position:!0,color:!0})),o.ALL=n(new o({position:!0,normal:!0,st:!0,tangent:!0,bitangent:!0})),o.DEFAULT=o.POSITION_NORMAL_AND_ST,o.packedLength=6,o.pack=function(n,o,i){if(!t(n))throw new r("value is required");if(!t(o))throw new r("array is required");return i=e(i,0),o[i++]=n.position?1:0,o[i++]=n.normal?1:0,o[i++]=n.st?1:0,o[i++]=n.tangent?1:0,o[i++]=n.bitangent?1:0,o[i]=n.color?1:0,o},o.unpack=function(n,i,a){if(!t(n))throw new r("array is required");return i=e(i,0),t(a)||(a=new o),a.position=1===n[i++],a.normal=1===n[i++],a.st=1===n[i++],a.tangent=1===n[i++],a.bitangent=1===n[i++],a.color=1===n[i],a},o.clone=function(e,r){return t(e)?(t(r)||(r=new o),r.position=e.position,r.normal=e.normal,r.st=e.st,r.tangent=e.tangent,r.bitangent=e.bitangent,r.color=e.color,r):void 0},o}),define("Core/PolylineGeometry",["./arrayRemoveDuplicates","./BoundingSphere","./Cartesian3","./Color","./ComponentDatatype","./defaultValue","./defined","./DeveloperError","./Ellipsoid","./Geometry","./GeometryAttribute","./GeometryAttributes","./GeometryType","./IndexDatatype","./Math","./PolylinePipeline","./PrimitiveType","./VertexFormat"],function(e,t,r,n,o,i,a,u,s,c,l,f,E,h,d,p,_,m){"use strict";function O(e,t,r,o,i){var a=y;a.length=i;var u,s=r.red,c=r.green,l=r.blue,f=r.alpha,E=o.red,h=o.green,d=o.blue,p=o.alpha;if(n.equals(r,o)){for(u=0;i>u;u++)a[u]=n.clone(r);return a}var _=(E-s)/i,m=(h-c)/i,O=(d-l)/i,R=(p-f)/i;for(u=0;i>u;u++)a[u]=new n(s+u*_,c+u*m,l+u*O,f+u*R);return a}function R(e){e=i(e,i.EMPTY_OBJECT);var t=e.positions,o=e.colors,c=i(e.width,1),l=i(e.hMax,-1),f=i(e.colorsPerVertex,!1);if(!a(t)||t.length<2)throw new u("At least two positions are required.");if("number"!=typeof c)throw new u("width must be a number");if(a(o)&&(f&&o.length<t.length||!f&&o.length<t.length-1))throw new u("colors has an invalid length.");this._positions=t,this._colors=o,this._width=c,this._hMax=l,this._colorsPerVertex=f,this._dist=e.dist,this._period=e.period,this._vertexFormat=m.clone(i(e.vertexFormat,m.DEFAULT)),this._followSurface=i(e.followSurface,!0),this._granularity=i(e.granularity,d.RADIANS_PER_DEGREE),this._ellipsoid=s.clone(i(e.ellipsoid,s.WGS84)),this._workerName="createPolylineGeometry";var E=1+t.length*r.packedLength;E+=a(o)?1+o.length*n.packedLength:1,this.packedLength=E+s.packedLength+m.packedLength+4+1+2}var y=[];R.pack=function(e,t,o){if(!a(e))throw new u("value is required");if(!a(t))throw new u("array is required");o=i(o,0);var c,l=e._positions,f=l.length;for(t[o++]=f,c=0;f>c;++c,o+=r.packedLength)r.pack(l[c],t,o);var E=e._colors;for(f=a(E)?E.length:0,t[o++]=f,c=0;f>c;++c,o+=n.packedLength)n.pack(E[c],t,o);return s.pack(e._ellipsoid,t,o),o+=s.packedLength,m.pack(e._vertexFormat,t,o),o+=m.packedLength,t[o++]=e._width,t[o++]=e._colorsPerVertex?1:0,t[o++]=e._followSurface?1:0,t[o++]=e._granularity,t[o++]=e._hMax,t[o++]=e._dist,t[o]=e._period,t};var T=s.clone(s.UNIT_SPHERE),A=new m,S={positions:void 0,colors:void 0,ellipsoid:T,vertexFormat:A,width:void 0,colorsPerVertex:void 0,followSurface:void 0,granularity:void 0};R.unpack=function(e,t,o){if(!a(e))throw new u("array is required");t=i(t,0);var c,l=e[t++],f=new Array(l);for(c=0;l>c;++c,t+=r.packedLength)f[c]=r.unpack(e,t);l=e[t++];var E=l>0?new Array(l):void 0;for(c=0;l>c;++c,t+=n.packedLength)E[c]=n.unpack(e,t);var h=s.unpack(e,t,T);t+=s.packedLength;var d=m.unpack(e,t,A);t+=m.packedLength;var p=e[t++],_=1===e[t++],O=1===e[t++],y=e[t++],N=e[t++],C=1==e[t++],g=e[t];return a(o)?(o._positions=f,o._colors=E,o._ellipsoid=s.clone(h,o._ellipsoid),o._vertexFormat=m.clone(d,o._vertexFormat),o._width=p,o._colorsPerVertex=_,o._followSurface=O,o._granularity=y,o._hMax=N,o._dist=C,o._period=g,o):(S.positions=f,S.colors=E,S.width=p,S.colorsPerVertex=_,S.followSurface=O,S.granularity=y,S.hMax=N,S.dist=C,S.period=g,new R(S))};var N=new r,C=new r,g=new r,I=new r;return R.createGeometry=function(i){var u,s,m,R=i._width,T=i._hMax,A=i._vertexFormat,S=i._colors,b=i._colorsPerVertex,M=i._followSurface,w=i._granularity,v=i._ellipsoid,F=i._dist,L=i._period,P=e(i._positions,r.equalsEpsilon),D=P.length;if(!(2>D||0>=R)){if(M){var U=p.extractHeights(P,v),B=d.chordLength(w,v.maximumRadius);if(a(S)){var x=1;for(u=0;D-1>u;++u)x+=p.numberOfPoints(P[u],P[u+1],B);var G=new Array(x),q=0;for(u=0;D-1>u;++u){var j=P[u],z=P[u+1],V=S[u],H=p.numberOfPoints(j,z,B);if(b&&x>u){var X=S[u+1],W=O(j,z,V,X,H),Y=W.length;for(s=0;Y>s;++s)G[q++]=W[s]}else for(s=0;H>s;++s)G[q++]=n.clone(V)}G[q]=n.clone(S[S.length-1]),S=G,y.length=0}P=p.generateCartesianArc({positions:P,minDistance:B,ellipsoid:v,height:U,hMax:T})}D=P.length;var K,k=4*D-4,Z=new Float64Array(3*k),Q=new Float64Array(3*k),J=new Float64Array(3*k),$=new Float32Array(2*k),ee=A.st?new Float32Array(2*k):void 0,te=a(S)?new Uint8Array(4*k):void 0,re=F?new Float32Array(3*k):void 0,ne=0,oe=0,ie=0,ae=0,ue=0,se=0;for(s=0;D>s;++s){0===s?(K=N,r.subtract(P[0],P[1],K),r.add(P[0],K,K)):K=P[s-1],r.clone(K,g),r.clone(P[s],C),s===D-1?(K=N,r.subtract(P[D-1],P[D-2],K),r.add(P[D-1],K,K)):K=P[s+1],r.clone(K,I);var ce,le;a(te)&&(ce=0===s||b?S[s]:S[s-1],s!==D-1&&(le=S[s]));var fe=0===s?2:0,Ee=s===D-1?2:4;for(m=fe;Ee>m;++m){r.pack(C,Z,ne),r.pack(g,Q,ne),r.pack(I,J,ne),ne+=3;var he=0>m-2?-1:1,de=2*(m%2)-1,pe=de*s/D;if(T>0?$[oe++]=pe:$[oe++]=de,$[oe++]=he*R,A.st&&(ee[ie++]=s/(D-1),ee[ie++]=Math.max($[oe-2],0)),a(te)){var _e=2>m?ce:le;te[ae++]=n.floatToByte(_e.red),te[ae++]=n.floatToByte(_e.green),te[ae++]=n.floatToByte(_e.blue),te[ae++]=n.floatToByte(_e.alpha)}F&&(re[3*ue]=se,ue++)}var me=r.distance(K,P[s]);se+=me}if(F){var Oe=se,Re=Math.random()*(L>0?L:Oe);for(s=0;k>s;s++)re[3*s+1]=Oe,re[3*s+2]=Re}var ye=new f;ye.position=new l({componentDatatype:o.DOUBLE,componentsPerAttribute:3,values:Z}),ye.prevPosition=new l({componentDatatype:o.DOUBLE,componentsPerAttribute:3,values:Q}),ye.nextPosition=new l({componentDatatype:o.DOUBLE,componentsPerAttribute:3,values:J}),ye.expandAndWidth=new l({componentDatatype:o.FLOAT,componentsPerAttribute:2,values:$}),A.st&&(ye.st=new l({componentDatatype:o.FLOAT,componentsPerAttribute:2,values:ee})),a(te)&&(ye.color=new l({componentDatatype:o.UNSIGNED_BYTE,componentsPerAttribute:4,values:te,normalize:!0})),F&&(ye.dist=new l({componentDatatype:o.FLOAT,componentsPerAttribute:3,values:re}));var Te=h.createTypedArray(k,6*D-6),Ae=0,Se=0,Ne=D-1;for(s=0;Ne>s;++s)Te[Se++]=Ae,Te[Se++]=Ae+2,Te[Se++]=Ae+1,Te[Se++]=Ae+1,Te[Se++]=Ae+2,Te[Se++]=Ae+3,Ae+=4;return new c({attributes:ye,indices:Te,primitiveType:_.TRIANGLES,boundingSphere:t.fromPoints(P),geometryType:E.POLYLINES})}},R}),define("Workers/createPolylineGeometry",["../Core/defined","../Core/Ellipsoid","../Core/PolylineGeometry"],function(e,t,r){"use strict";function n(n,o){return e(o)&&(n=r.unpack(n,o)),n._ellipsoid=t.clone(n._ellipsoid),r.createGeometry(n)}return n})}(); |
|
__init__.py | from .shape import *
from .image import Image
from .table import Table | from .roi import *
from .surface import * |
|
bazel_build.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2016 The Tulsi Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Bridge between Xcode and Bazel for the "build" action."""
import atexit
import errno
import fcntl
import hashlib
import inspect
import io
import json
import os
import pipes
import re
import shutil
import signal
import subprocess
import sys
import textwrap
import threading
import time
import zipfile
from apfs_clone_copy import CopyOnWrite
import bazel_build_events
import bazel_build_settings
import bazel_options
from bootstrap_lldbinit import BootstrapLLDBInit
from bootstrap_lldbinit import TULSI_LLDBINIT_FILE
import tulsi_logging
from update_symbol_cache import UpdateSymbolCache
# List of frameworks that Xcode injects into test host targets that should be
# re-signed when running the tests on devices.
XCODE_INJECTED_FRAMEWORKS = [
'libXCTestBundleInject.dylib',
'libXCTestSwiftSupport.dylib',
'IDEBundleInjection.framework',
'XCTAutomationSupport.framework',
'XCTest.framework',
]
_logger = None
def _PrintUnbuffered(msg):
sys.stdout.write('%s\n' % msg)
sys.stdout.flush()
def _PrintXcodeWarning(msg):
sys.stdout.write(':: warning: %s\n' % msg)
sys.stdout.flush()
def _PrintXcodeError(msg):
sys.stderr.write(':: error: %s\n' % msg)
sys.stderr.flush()
def _Fatal(msg, fatal_frame=None):
"""Print a fatal error pointing to the failure line inside the script."""
if not fatal_frame:
fatal_frame = inspect.currentframe().f_back
filename, line_number, _, _, _ = inspect.getframeinfo(fatal_frame)
_PrintUnbuffered('%s:%d: error: %s' % (os.path.abspath(filename),
line_number, msg))
CLEANUP_BEP_FILE_AT_EXIT = False
# Function to be called atexit to clean up the BEP file if one is present.
# This is especially useful in cases of abnormal termination (such as what
# happens when Xcode is killed).
def _BEPFileExitCleanup(bep_file_path):
if not CLEANUP_BEP_FILE_AT_EXIT:
return
try:
os.remove(bep_file_path)
except OSError as e:
_PrintXcodeWarning('Failed to remove BEP file from %s. Error: %s' %
(bep_file_path, e.strerror))
def _InterruptHandler(signum, frame):
"""Gracefully exit on SIGINT."""
del signum, frame # Unused.
_PrintUnbuffered('Caught interrupt signal. Exiting...')
sys.exit(0)
class Timer(object):
"""Simple profiler."""
def __init__(self, action_name, action_id):
"""Creates a new Timer object.
Args:
action_name: A human-readable action name, shown in the build log.
action_id: A machine-readable action identifier, can be used for metrics.
Returns:
A Timer instance.
Raises:
RuntimeError: if Timer is created without initializing _logger.
"""
if _logger is None:
raise RuntimeError('Attempted to create Timer without a logger.')
self.action_name = action_name
self.action_id = action_id
self._start = None
def Start(self):
self._start = time.time()
return self
def End(self, log_absolute_times=False):
end = time.time()
seconds = end - self._start
if log_absolute_times:
_logger.log_action(self.action_name, self.action_id, seconds,
self._start, end)
else:
_logger.log_action(self.action_name, self.action_id, seconds)
def _LockFileCreate():
# This relies on this script running at the root of the bazel workspace.
cwd = os.environ['PWD']
cwd_hash = hashlib.sha256(cwd.encode()).hexdigest()
return '/tmp/tulsi_bazel_build_{}.lock'.format(cwd_hash)
# Function to be called atexit to release the file lock on script termination.
def _LockFileExitCleanup(lock_file_handle):
lock_file_handle.close()
def _LockFileAcquire(lock_path):
"""Force script to wait on file lock to serialize build target actions.
Args:
lock_path: Path to the lock file.
"""
_PrintUnbuffered('Queuing Tulsi build...')
lockfile = open(lock_path, 'w')
# Register "fclose(...)" as early as possible, before acquiring lock.
atexit.register(_LockFileExitCleanup, lockfile)
while True:
try:
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except IOError as err:
if err.errno != errno.EAGAIN:
raise
else:
time.sleep(0.1)
class CodesignBundleAttributes(object):
"""Wrapper class for codesigning attributes of a signed bundle."""
# List of codesigning attributes that this script requires.
_ATTRIBUTES = ['Authority', 'Identifier', 'TeamIdentifier']
def __init__(self, codesign_output):
self.attributes = {}
pending_attributes = list(self._ATTRIBUTES)
for line in codesign_output.split('\n'):
if not pending_attributes:
break
for attribute in pending_attributes:
if line.startswith(attribute):
value = line[len(attribute) + 1:]
self.attributes[attribute] = value
pending_attributes.remove(attribute)
break
for attribute in self._ATTRIBUTES:
if attribute not in self.attributes:
_PrintXcodeError(
'Failed to extract %s from %s.\n' % (attribute, codesign_output))
def Get(self, attribute):
"""Returns the value for the given attribute, or None if it wasn't found."""
value = self.attributes.get(attribute)
if attribute not in self._ATTRIBUTES:
_PrintXcodeError(
'Attribute %s not declared to be parsed. ' % attribute +
'Available attributes are %s.\n' % self._ATTRIBUTES)
return value
class _OptionsParser(object):
"""Handles parsing script options."""
# List of all supported Xcode configurations.
KNOWN_CONFIGS = ['Debug', 'Release']
def __init__(self, build_settings, sdk_version, platform_name, arch):
self.targets = []
self.build_settings = build_settings
self.common_build_options = [
'--verbose_failures',
'--bes_outerr_buffer_size=0', # Don't buffer Bazel output.
]
self.sdk_version = sdk_version
self.platform_name = platform_name
if self.platform_name.startswith('watch'):
config_platform = 'watchos'
elif self.platform_name.startswith('iphone'):
config_platform = 'ios'
elif self.platform_name.startswith('macos'):
config_platform = 'macos'
elif self.platform_name.startswith('appletv'):
config_platform = 'tvos'
else:
self._WarnUnknownPlatform()
config_platform = 'ios'
self.bazel_build_config = '{}_{}'.format(config_platform, arch)
if self.bazel_build_config not in build_settings.platformConfigFlags:
_PrintXcodeError('Unknown active compilation target of "{}". '
'Please report a Tulsi bug.'
.format(self.bazel_build_config))
sys.exit(1)
self.verbose = 0
self.bazel_bin_path = 'bazel-bin'
self.bazel_executable = None
@staticmethod
def _UsageMessage():
"""Returns a usage message string."""
usage = textwrap.dedent("""\
Usage: %s <target> [<target2> ...] --bazel <bazel_binary_path> [options]
Where options are:
--verbose [-v]
Increments the verbosity of the script by one level. This argument
may be provided multiple times to enable additional output levels.
--bazel_bin_path <path>
Path at which Bazel-generated artifacts may be retrieved.
""" % sys.argv[0])
return usage
def ParseOptions(self, args):
"""Parses arguments, returning (message, exit_code)."""
bazel_executable_index = args.index('--bazel')
self.targets = args[:bazel_executable_index]
if not self.targets or len(args) < bazel_executable_index + 2:
return (self._UsageMessage(), 10)
self.bazel_executable = args[bazel_executable_index + 1]
return self._ParseVariableOptions(args[bazel_executable_index + 2:])
def GetBaseFlagsForTargets(self, config):
is_debug = config == 'Debug'
return self.build_settings.flags_for_target(
self.targets[0],
is_debug,
self.bazel_build_config)
def GetEnabledFeatures(self):
"""Returns a list of enabled Bazel features for the active target."""
return self.build_settings.features_for_target(self.targets[0])
def GetBazelOptions(self, config):
"""Returns the full set of build options for the given config."""
bazel, start_up, build = self.GetBaseFlagsForTargets(config)
all_build = []
all_build.extend(self.common_build_options)
all_build.extend(build)
xcode_version_flag = self._ComputeXcodeVersionFlag()
if xcode_version_flag:
all_build.append('--xcode_version=%s' % xcode_version_flag)
return bazel, start_up, all_build
def _WarnUnknownPlatform(self):
_PrintUnbuffered('Warning: unknown platform "%s" will be treated as '
'iOS' % self.platform_name)
def _ParseVariableOptions(self, args):
"""Parses flag-based args, returning (message, exit_code)."""
verbose_re = re.compile('-(v+)$')
while args:
arg = args[0]
args = args[1:]
if arg == '--bazel_bin_path':
if not args:
return ('Missing required parameter for %s' % arg, 2)
self.bazel_bin_path = args[0]
args = args[1:]
elif arg == '--verbose':
self.verbose += 1
else:
match = verbose_re.match(arg)
if match:
self.verbose += len(match.group(1))
else:
return ('Unknown option "%s"\n%s' % (arg, self._UsageMessage()), 1)
return (None, 0)
@staticmethod
def _GetXcodeBuildVersionString():
"""Returns Xcode build version from the environment as a string."""
return os.environ['XCODE_PRODUCT_BUILD_VERSION']
@staticmethod
def _GetXcodeVersionString():
"""Returns Xcode version info from the environment as a string."""
reported_version = os.environ['XCODE_VERSION_ACTUAL']
match = re.match(r'(\d{2})(\d)(\d)$', reported_version)
if not match:
_PrintUnbuffered('Warning: Failed to extract Xcode version from %s' % (
reported_version))
return None
major_version = int(match.group(1))
minor_version = int(match.group(2))
fix_version = int(match.group(3))
return '%d.%d.%d' % (major_version, minor_version, fix_version)
@staticmethod
def _ComputeXcodeVersionFlag():
"""Returns a string for the --xcode_version build flag, if any.
The flag should be used if the active Xcode version was not the same one
used during project generation.
Note this a best-attempt only; this may not be accurate as Bazel itself
caches the active DEVELOPER_DIR path and the user may have changed their
installed Xcode version.
"""
xcode_version = _OptionsParser._GetXcodeVersionString()
build_version = _OptionsParser._GetXcodeBuildVersionString()
if not xcode_version or not build_version:
return None
# Of the form Major.Minor.Fix.Build (new Bazel form) or Major.Min.Fix (old).
full_bazel_version = os.environ.get('TULSI_XCODE_VERSION')
if not full_bazel_version: # Unexpected: Tulsi gen didn't set the flag.
return xcode_version
# Newer Bazel versions specify the version as Major.Minor.Fix.Build.
if full_bazel_version.count('.') == 3:
components = full_bazel_version.rsplit('.', 1)
bazel_xcode_version = components[0]
bazel_build_version = components[1]
if (xcode_version != bazel_xcode_version
or build_version != bazel_build_version):
return '{}.{}'.format(xcode_version, build_version)
else:
return None
else: # Old version of Bazel. We need to use form Major.Minor.Fix.
return xcode_version if xcode_version != full_bazel_version else None
class BazelBuildBridge(object):
"""Handles invoking Bazel and unpacking generated binaries."""
BUILD_EVENTS_FILE = 'build_events.json'
def __init__(self, build_settings):
self.build_settings = build_settings
self.verbose = 0
self.bazel_bin_path = None
self.codesign_attributes = {}
self.codesigning_folder_path = os.environ['CODESIGNING_FOLDER_PATH']
self.xcode_action = os.environ['ACTION'] # The Xcode build action.
# When invoked as an external build system script, Xcode will set ACTION to
# an empty string.
if not self.xcode_action:
self.xcode_action = 'build'
if int(os.environ['XCODE_VERSION_MAJOR']) < 900:
xcode_build_version = os.environ['XCODE_PRODUCT_BUILD_VERSION']
_PrintXcodeWarning('Tulsi officially supports Xcode 9+. You are using an '
'earlier Xcode, build %s.' % xcode_build_version)
self.tulsi_version = os.environ.get('TULSI_VERSION', 'UNKNOWN')
# TODO(b/69857078): Remove this when wrapped_clang is updated.
self.direct_debug_prefix_map = False
self.normalized_prefix_map = False
self.update_symbol_cache = UpdateSymbolCache()
# Target architecture. Must be defined for correct setting of
# the --cpu flag. Note that Xcode will set multiple values in
# ARCHS when building for a Generic Device.
archs = os.environ.get('ARCHS')
if not archs:
_PrintXcodeError('Tulsi requires env variable ARCHS to be '
'set. Please file a bug against Tulsi.')
sys.exit(1)
self.arch = archs.split()[-1]
# Path into which generated artifacts should be copied.
self.built_products_dir = os.environ['BUILT_PRODUCTS_DIR']
# Path where Xcode expects generated sources to be placed.
self.derived_sources_folder_path = os.environ.get('DERIVED_SOURCES_DIR')
# Full name of the target artifact (e.g., "MyApp.app" or "Test.xctest").
self.full_product_name = os.environ['FULL_PRODUCT_NAME']
# Whether to generate runfiles for this target.
self.gen_runfiles = os.environ.get('GENERATE_RUNFILES')
# Target SDK version.
self.sdk_version = os.environ.get('SDK_VERSION')
# TEST_HOST for unit tests.
self.test_host_binary = os.environ.get('TEST_HOST')
# Whether this target is a test or not.
self.is_test = os.environ.get('WRAPPER_EXTENSION') == 'xctest'
# Target platform.
self.platform_name = os.environ['PLATFORM_NAME']
# Type of the target artifact.
self.product_type = os.environ['PRODUCT_TYPE']
# Path to the parent of the xcodeproj bundle.
self.project_dir = os.environ['PROJECT_DIR']
# Path to the xcodeproj bundle.
self.project_file_path = os.environ['PROJECT_FILE_PATH']
# Path to the directory containing the WORKSPACE file.
self.workspace_root = os.path.abspath(os.environ['TULSI_WR'])
# Set to the name of the generated bundle for bundle-type targets, None for
# single file targets (like static libraries).
self.wrapper_name = os.environ.get('WRAPPER_NAME')
self.wrapper_suffix = os.environ.get('WRAPPER_SUFFIX', '')
# Path where Xcode expects the artifacts to be written to. This is not the
# codesigning_path as device vs simulator builds have different signing
# requirements, so Xcode expects different paths to be signed. This is
# mostly apparent on XCUITests where simulator builds set the codesigning
# path to be the .xctest bundle, but for device builds it is actually the
# UI runner app (since it needs to be codesigned to run on the device.) The
# FULL_PRODUCT_NAME variable is a stable path on where to put the expected
# artifacts. For static libraries (objc_library, swift_library),
# FULL_PRODUCT_NAME corresponds to the .a file name, which coincides with
# the expected location for a single artifact output.
# TODO(b/35811023): Check these paths are still valid.
self.artifact_output_path = os.path.join(
os.environ['TARGET_BUILD_DIR'],
os.environ['FULL_PRODUCT_NAME'])
# Path to where Xcode expects the binary to be placed.
self.binary_path = os.path.join(
os.environ['TARGET_BUILD_DIR'], os.environ['EXECUTABLE_PATH'])
self.is_simulator = self.platform_name.endswith('simulator')
# Check to see if code signing actions should be skipped or not.
if self.is_simulator:
self.codesigning_allowed = False
else:
self.codesigning_allowed = os.environ.get('CODE_SIGNING_ALLOWED') == 'YES'
if self.codesigning_allowed:
platform_prefix = 'iOS'
if self.platform_name.startswith('macos'):
platform_prefix = 'macOS'
entitlements_filename = '%sXCTRunner.entitlements' % platform_prefix
self.runner_entitlements_template = os.path.join(self.project_file_path,
'.tulsi',
'Resources',
entitlements_filename)
self.bazel_executable = None
def Run(self, args):
"""Executes a Bazel build based on the environment and given arguments."""
if self.xcode_action != 'build':
sys.stderr.write('Xcode action is %s, ignoring.' % self.xcode_action)
return 0
parser = _OptionsParser(self.build_settings,
self.sdk_version,
self.platform_name,
self.arch)
timer = Timer('Parsing options', 'parsing_options').Start()
message, exit_code = parser.ParseOptions(args[1:])
timer.End()
if exit_code:
_PrintXcodeError('Option parsing failed: %s' % message)
return exit_code
self.verbose = parser.verbose
self.bazel_bin_path = os.path.abspath(parser.bazel_bin_path)
self.bazel_executable = parser.bazel_executable
self.bazel_exec_root = self.build_settings.bazelExecRoot
# Update feature flags.
features = parser.GetEnabledFeatures()
self.direct_debug_prefix_map = 'DirectDebugPrefixMap' in features
self.normalized_prefix_map = 'DebugPathNormalization' in features
# Path to the Build Events JSON file uses pid and is removed if the
# build is successful.
filename = '%d_%s' % (os.getpid(), BazelBuildBridge.BUILD_EVENTS_FILE)
self.build_events_file_path = os.path.join(
self.project_file_path,
'.tulsi',
filename)
(command, retval) = self._BuildBazelCommand(parser)
if retval:
return retval
timer = Timer('Running Bazel', 'running_bazel').Start()
exit_code, outputs = self._RunBazelAndPatchOutput(command)
timer.End()
if exit_code:
_Fatal('Bazel build failed with exit code %d. Please check the build '
'log in Report Navigator (⌘9) for more information.'
% exit_code)
return exit_code
post_bazel_timer = Timer('Total Tulsi Post-Bazel time', 'total_post_bazel')
post_bazel_timer.Start()
if not os.path.exists(self.bazel_exec_root):
_Fatal('No Bazel execution root was found at %r. Debugging experience '
'will be compromised. Please report a Tulsi bug.'
% self.bazel_exec_root)
return 404
# This needs to run after `bazel build`, since it depends on the Bazel
# workspace directory
exit_code = self._LinkTulsiWorkspace()
if exit_code:
return exit_code
exit_code, outputs_data = self._ExtractAspectOutputsData(outputs)
if exit_code:
return exit_code
# Generated headers are installed on a thread since we are launching
# a separate process to do so. This gives us clean timings.
install_thread = threading.Thread(
target=self._InstallGeneratedHeaders, args=(outputs,))
install_thread.start()
timer = Timer('Installing artifacts', 'installing_artifacts').Start()
exit_code = self._InstallArtifact(outputs_data)
timer.End()
install_thread.join()
if exit_code:
return exit_code
exit_code, dsym_paths = self._InstallDSYMBundles(
self.built_products_dir, outputs_data)
if exit_code:
return exit_code
if not dsym_paths:
# Clean any bundles from a previous build that can interfere with
# debugging in LLDB.
self._CleanExistingDSYMs()
else:
for path in dsym_paths:
# Starting with Xcode 9.x, a plist based remapping exists for dSYM
# bundles that works with Swift as well as (Obj-)C(++).
#
# This solution also works for Xcode 8.x for (Obj-)C(++) but not
# for Swift.
timer = Timer('Adding remappings as plists to dSYM',
'plist_dsym').Start()
exit_code = self._PlistdSYMPaths(path)
timer.End()
if exit_code:
_PrintXcodeError('Remapping dSYMs process returned %i, please '
'report a Tulsi bug and attach a full Xcode '
'build log.' % exit_code)
return exit_code
# Starting with Xcode 7.3, XCTests inject several supporting frameworks
# into the test host that need to be signed with the same identity as
# the host itself.
if (self.is_test and not self.platform_name.startswith('macos') and
self.codesigning_allowed):
exit_code = self._ResignTestArtifacts()
if exit_code:
return exit_code
# Starting with Xcode 8, .lldbinit files are honored during Xcode debugging
# sessions. This allows use of the target.source-map field to remap the
# debug symbol paths encoded in the binary to the paths expected by Xcode.
#
# This will not work with dSYM bundles, or a direct -fdebug-prefix-map from
# the Bazel-built locations to Xcode-visible sources.
timer = Timer('Updating .lldbinit', 'updating_lldbinit').Start()
clear_source_map = dsym_paths or self.direct_debug_prefix_map
exit_code = self._UpdateLLDBInit(clear_source_map)
timer.End()
if exit_code:
_PrintXcodeWarning('Updating .lldbinit action failed with code %d' %
exit_code)
post_bazel_timer.End(log_absolute_times=True)
return 0
def _BuildBazelCommand(self, options):
"""Builds up a commandline string suitable for running Bazel."""
configuration = os.environ['CONFIGURATION']
# Treat the special testrunner build config as a Debug compile.
test_runner_config_prefix = '__TulsiTestRunner_'
if configuration.startswith(test_runner_config_prefix):
configuration = configuration[len(test_runner_config_prefix):]
elif os.environ.get('TULSI_TEST_RUNNER_ONLY') == 'YES':
_PrintXcodeError('Building test targets with configuration "%s" is not '
'allowed. Please use the "Test" action or "Build for" > '
'"Testing" instead.' % configuration)
return (None, 1)
if configuration not in _OptionsParser.KNOWN_CONFIGS:
_PrintXcodeError('Unknown build configuration "%s"' % configuration)
return (None, 1)
bazel, start_up, build = options.GetBazelOptions(configuration)
bazel_command = [bazel]
bazel_command.extend(start_up)
bazel_command.append('build')
bazel_command.extend(build)
bazel_command.extend([
# The following flags are used by Tulsi to identify itself and read
# build information from Bazel. They shold not affect Bazel anaylsis
# caching.
'--tool_tag=tulsi:bazel_build',
'--build_event_json_file=%s' % self.build_events_file_path,
'--noexperimental_build_event_json_file_path_conversion',
'--aspects', '@tulsi//:tulsi/tulsi_aspects.bzl%tulsi_outputs_aspect'])
if self.is_test and self.gen_runfiles:
bazel_command.append('--output_groups=+tulsi_outputs')
else:
bazel_command.append('--output_groups=tulsi_outputs,default')
bazel_command.extend(options.targets)
extra_options = bazel_options.BazelOptions(os.environ)
bazel_command.extend(extra_options.bazel_feature_flags())
return (bazel_command, 0)
def _RunBazelAndPatchOutput(self, command):
"""Runs subprocess command, patching output as it's received."""
self._PrintVerbose('Running "%s", patching output for workspace root at '
'"%s" with project path at "%s".' %
(' '.join([pipes.quote(x) for x in command]),
self.workspace_root,
self.project_dir))
# Clean up bazel output to make it look better in Xcode.
bazel_line_regex = re.compile(
r'(INFO|DEBUG|WARNING|ERROR|FAILED): ([^:]+:\d+:(?:\d+:)?)\s+(.+)')
bazel_generic_regex = re.compile(r'(INFO|DEBUG|WARNING|ERROR|FAILED): (.*)')
def PatchBazelDiagnosticStatements(output_line):
"""Make Bazel output more Xcode friendly."""
def BazelLabelToXcodeLabel(bazel_label):
"""Map Bazel labels to xcode labels for build output."""
xcode_labels = {
'INFO': 'note',
'DEBUG': 'note',
'WARNING': 'warning',
'ERROR': 'error',
'FAILED': 'error'
}
return xcode_labels.get(bazel_label, bazel_label)
match = bazel_line_regex.match(output_line)
if match:
xcode_label = BazelLabelToXcodeLabel(match.group(1))
output_line = '%s %s: %s' % (match.group(2), xcode_label,
match.group(3))
else:
match = bazel_generic_regex.match(output_line)
if match:
xcode_label = BazelLabelToXcodeLabel(match.group(1))
output_line = '%s: %s' % (xcode_label, match.group(2))
return output_line
if self.workspace_root != self.project_dir:
# Match (likely) filename:line_number: lines.
xcode_parsable_line_regex = re.compile(r'([^/][^:]+):\d+:')
def PatchOutputLine(output_line):
output_line = PatchBazelDiagnosticStatements(output_line)
if xcode_parsable_line_regex.match(output_line):
output_line = '%s/%s' % (self.workspace_root, output_line)
return output_line
patch_xcode_parsable_line = PatchOutputLine
else:
patch_xcode_parsable_line = PatchBazelDiagnosticStatements
def HandleOutput(output):
for line in output.splitlines():
_logger.log_bazel_message(patch_xcode_parsable_line(line))
def WatcherUpdate(watcher):
"""Processes any new events in the given watcher.
Args:
watcher: a BazelBuildEventsWatcher object.
Returns:
A list of new tulsiout file names seen.
"""
new_events = watcher.check_for_new_events()
new_outputs = []
for build_event in new_events:
if build_event.stderr:
HandleOutput(build_event.stderr)
if build_event.stdout:
HandleOutput(build_event.stdout)
if build_event.files:
outputs = [x for x in build_event.files if x.endswith('.tulsiouts')]
new_outputs.extend(outputs)
return new_outputs
def ReaderThread(file_handle, out_buffer):
out_buffer.append(file_handle.read())
file_handle.close()
# Make sure the BEP JSON file exists and is empty. We do this to prevent
# any sort of race between the watcher, bazel, and the old file contents.
open(self.build_events_file_path, 'w').close()
# Capture the stderr and stdout from Bazel. We only display it if it we're
# unable to read any BEP events.
process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1)
# Register atexit function to clean up BEP file.
atexit.register(_BEPFileExitCleanup, self.build_events_file_path)
global CLEANUP_BEP_FILE_AT_EXIT
CLEANUP_BEP_FILE_AT_EXIT = True
# Start capturing output from Bazel.
reader_buffer = []
reader_thread = threading.Thread(target=ReaderThread,
args=(process.stdout, reader_buffer))
reader_thread.daemon = True
reader_thread.start()
with io.open(self.build_events_file_path, 'r', -1, 'utf-8', 'ignore'
) as bep_file:
watcher = bazel_build_events.BazelBuildEventsWatcher(bep_file,
_PrintXcodeWarning)
output_locations = []
while process.returncode is None:
output_locations.extend(WatcherUpdate(watcher))
time.sleep(0.1)
process.poll()
output_locations.extend(WatcherUpdate(watcher))
# If BEP JSON parsing failed, we should display the raw stdout and
# stderr from Bazel.
reader_thread.join()
if not watcher.has_read_events():
HandleOutput(reader_buffer[0])
if process.returncode == 0 and not output_locations:
CLEANUP_BEP_FILE_AT_EXIT = False
_PrintXcodeError('Unable to find location of the .tulsiouts file.'
'Please report this as a Tulsi bug, including the'
'contents of %s.' % self.build_events_file_path)
return 1, output_locations
return process.returncode, output_locations
def _ExtractAspectOutputsData(self, output_files):
"""Converts aspect output from paths to json to a list of dictionaries.
Args:
output_files: A list of strings to files representing Bazel aspect output
in UTF-8 JSON format.
Returns:
return_code, [dict]: A tuple with a return code as its first argument and
for its second argument, a list of dictionaries for
each output_file that could be interpreted as valid
JSON, representing the returned Bazel aspect
information.
return_code, None: If an error occurred while converting the list of
files into JSON.
"""
outputs_data = []
for output_file in output_files:
try:
output_data = json.load(open(output_file))
except (ValueError, IOError) as e:
_PrintXcodeError('Failed to load output map ""%s". '
'%s' % (output_file, e))
return 600, None
outputs_data.append(output_data)
return 0, outputs_data
def _InstallArtifact(self, outputs_data):
"""Installs Bazel-generated artifacts into the Xcode output directory."""
xcode_artifact_path = self.artifact_output_path
if not outputs_data:
_PrintXcodeError('Failed to load top level output file.')
return 600
primary_output_data = outputs_data[0]
if 'artifact' not in primary_output_data:
_PrintXcodeError(
'Failed to find an output artifact for target %s in output map %r' %
(xcode_artifact_path, primary_output_data))
return 601
primary_artifact = primary_output_data['artifact']
artifact_archive_root = primary_output_data.get('archive_root')
bundle_name = primary_output_data.get('bundle_name')
# The PRODUCT_NAME used by the Xcode project is not trustable as it may be
# modified by the user and, more importantly, may have been modified by
# Tulsi to disambiguate multiple targets with the same name.
self.bazel_product_name = bundle_name
# We need to handle IPAs (from {ios, tvos}_application) differently from
# ZIPs (from the other bundled rules) because they output slightly different
# directory structures.
is_ipa = primary_artifact.endswith('.ipa')
is_zip = primary_artifact.endswith('.zip')
if is_ipa or is_zip:
expected_bundle_name = bundle_name + self.wrapper_suffix
# The directory structure within the IPA is then determined based on
# Bazel's package and/or product type.
if is_ipa:
bundle_subpath = os.path.join('Payload', expected_bundle_name)
else:
# If the artifact is a ZIP, assume that the bundle is the top-level
# directory (this is the way in which Skylark rules package artifacts
# that are not standalone IPAs).
bundle_subpath = expected_bundle_name
# Prefer to copy over files from the archive root instead of unzipping the
# ipa/zip in order to help preserve timestamps. Note that the archive root
# is only present for local builds; for remote builds we must extract from
# the zip file.
if self._IsValidArtifactArchiveRoot(artifact_archive_root, bundle_name):
source_location = os.path.join(artifact_archive_root, bundle_subpath)
exit_code = self._RsyncBundle(os.path.basename(primary_artifact),
source_location,
xcode_artifact_path)
else:
exit_code = self._UnpackTarget(primary_artifact,
xcode_artifact_path,
bundle_subpath)
if exit_code:
return exit_code
elif os.path.isfile(primary_artifact):
# Remove the old artifact before copying.
if os.path.isfile(xcode_artifact_path):
try:
os.remove(xcode_artifact_path)
except OSError as e:
_PrintXcodeError('Failed to remove stale output file ""%s". '
'%s' % (xcode_artifact_path, e))
return 600
exit_code = self._CopyFile(os.path.basename(primary_artifact),
primary_artifact,
xcode_artifact_path)
if exit_code:
return exit_code
else:
self._RsyncBundle(os.path.basename(primary_artifact),
primary_artifact,
xcode_artifact_path)
# When the rules output a tree artifact, Tulsi will copy the bundle as is
# into the expected Xcode output location. But because they're copied as
# is from the bazel output, they come with bazel's permissions, which are
# read only. Here we set them to write as well, so Xcode can modify the
# bundle too (for example, for codesigning).
chmod_timer = Timer('Modifying permissions of output bundle',
'bundle_chmod').Start()
self._PrintVerbose('Spawning subprocess to add write permissions to '
'copied bundle...')
process = subprocess.Popen(['chmod', '-R', 'uga+w', xcode_artifact_path])
process.wait()
chmod_timer.End()
# No return code check as this is not an essential operation.
self._InstallEmbeddedBundlesIfNecessary(primary_output_data)
return 0
def _IsValidArtifactArchiveRoot(self, archive_root, bundle_name):
"""Returns true if the archive root is valid for use."""
if not archive_root or not os.path.isdir(archive_root):
return False
# The archive root will not be updated for any remote builds, but will be
# valid for local builds. We detect this by using an implementation detail
# of the rules_apple bundler: archives will always be transformed from
# <name>.unprocessed.zip (locally or remotely) to <name>.archive-root.
#
# Thus if the mod time on the archive root is not greater than the mod
# time on the on the zip, the archive root is not valid. Remote builds
# will end up copying the <name>.unprocessed.zip but not the
# <name>.archive-root, making this a valid temporary solution.
#
# In the future, it would be better to have this handled by the rules;
# until then this should suffice as a work around to improve build times.
unprocessed_zip = os.path.join(os.path.dirname(archive_root),
'%s.unprocessed.zip' % bundle_name)
if not os.path.isfile(unprocessed_zip):
return False
return os.path.getmtime(archive_root) > os.path.getmtime(unprocessed_zip)
def _InstallEmbeddedBundlesIfNecessary(self, output_data):
"""Install embedded bundles next to the current target's output."""
# In order to find and load symbols for the binary installed on device,
# Instruments needs to "see" it in Spotlight index somewhere on the local
# filesystem. This is only needed for on-device instrumentation.
#
# Unfortunatelly, it does not seem to be possible to detect when a build is
# being made for profiling, thus we can't exclude this step for on-device
# non-profiling builds.
if self.is_simulator or ('embedded_bundles' not in output_data):
return
timer = Timer('Installing embedded bundles',
'installing_embedded_bundles').Start()
for bundle_info in output_data['embedded_bundles']:
bundle_name = bundle_info['bundle_name']
bundle_extension = bundle_info['bundle_extension']
full_name = bundle_name + bundle_extension
output_path = os.path.join(self.built_products_dir, full_name)
# TODO(b/68936732): See if copying just the binary (not the whole bundle)
# is enough to make Instruments work.
if self._IsValidArtifactArchiveRoot(bundle_info['archive_root'],
bundle_name):
source_path = os.path.join(bundle_info['archive_root'], full_name)
self._RsyncBundle(full_name, source_path, output_path)
else:
# Try to find the embedded bundle within the installed main bundle.
bundle_path = self._FindEmbeddedBundleInMain(bundle_name,
bundle_extension)
if bundle_path:
self._RsyncBundle(full_name, bundle_path, output_path)
else:
_PrintXcodeWarning('Could not find bundle %s in main bundle. ' %
(full_name) +
'Device-level Instruments debugging will be '
'disabled for this bundle. Please report a '
'Tulsi bug and attach a full Xcode build log.')
timer.End()
# Maps extensions to anticipated subfolders.
_EMBEDDED_BUNDLE_PATHS = {
'.appex': 'PlugIns',
'.framework': 'Frameworks'
}
def _FindEmbeddedBundleInMain(self, bundle_name, bundle_extension):
"""Retrieves the first embedded bundle found within our main bundle."""
main_bundle = os.environ.get('EXECUTABLE_FOLDER_PATH')
if not main_bundle:
return None
main_bundle_path = os.path.join(self.built_products_dir,
main_bundle)
return self._FindEmbeddedBundle(bundle_name,
bundle_extension,
main_bundle_path)
def _FindEmbeddedBundle(self, bundle_name, bundle_extension, bundle_path):
"""Retrieves the first embedded bundle found within this bundle path."""
embedded_subfolder = self._EMBEDDED_BUNDLE_PATHS.get(bundle_extension)
if not embedded_subfolder:
return None
projected_bundle_path = os.path.join(bundle_path,
embedded_subfolder,
bundle_name + bundle_extension)
if os.path.isdir(projected_bundle_path):
return projected_bundle_path
# For frameworks not in the main app bundle, and possibly other executable
# bundle content in the future, we recurse through every .appex in PlugIns
# to find those frameworks.
#
# This won't support frameworks that could potentially have the same name
# but are different between the app and extensions, but we intentionally
# choose not to handle that case. Xcode build system only supports
# uniquely named frameworks, and we shouldn't confuse the dynamic loader
# with frameworks that have the same image names but different content.
appex_root_path = os.path.join(bundle_path, 'PlugIns')
if not os.path.isdir(appex_root_path):
return None
# Find each directory within appex_root_path and attempt to find a bundle.
# If one can't be found, return None.
appex_dirs = os.listdir(appex_root_path)
for appex_dir in appex_dirs:
appex_path = os.path.join(appex_root_path, appex_dir)
path = self._FindEmbeddedBundle(bundle_name,
bundle_extension,
appex_path)
if path:
return path
return None
def _InstallGeneratedHeaders(self, outputs):
"""Invokes install_genfiles.py to install generated Bazel files."""
genfiles_timer = Timer('Installing generated headers',
'installing_generated_headers').Start()
# Resolve the path to the install_genfiles.py script.
# It should be in the same directory as this script.
path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'install_genfiles.py')
args = [path, self.bazel_exec_root]
args.extend(outputs)
self._PrintVerbose('Spawning subprocess install_genfiles.py to copy '
'generated files in the background...')
process = subprocess.Popen(args)
process.wait()
genfiles_timer.End()
def _InstallBundle(self, source_path, output_path):
"""Copies the bundle at source_path to output_path."""
if not os.path.isdir(source_path):
return 0, None
if os.path.isdir(output_path):
try:
shutil.rmtree(output_path)
except OSError as e:
_PrintXcodeError('Failed to remove stale bundle ""%s". '
'%s' % (output_path, e))
return 700, None
exit_code = self._CopyBundle(os.path.basename(source_path),
source_path,
output_path)
return exit_code, output_path
def _RsyncBundle(self, source_path, full_source_path, output_path):
"""Rsyncs the given bundle to the given expected output path."""
self._PrintVerbose('Rsyncing %s to %s' % (source_path, output_path))
# rsync behavior changes based on presence of a trailing slash.
if not full_source_path.endswith('/'):
full_source_path += '/'
try:
# Use -c to check differences by checksum, -v for verbose,
# and --delete to delete stale files.
# The rest of the flags are the same as -a but without preserving
# timestamps, which is done intentionally so the timestamp will
# only change when the file is changed.
subprocess.check_output(['rsync',
'-vcrlpgoD',
'--delete',
full_source_path,
output_path],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
_PrintXcodeError('Rsync failed. %s' % e)
return 650
return 0
def _CopyBundle(self, source_path, full_source_path, output_path):
"""Copies the given bundle to the given expected output path."""
self._PrintVerbose('Copying %s to %s' % (source_path, output_path))
try:
CopyOnWrite(full_source_path, output_path, tree=True)
except OSError as e:
_PrintXcodeError('Copy failed. %s' % e)
return 650
return 0
def _CopyFile(self, source_path, full_source_path, output_path):
"""Copies the given file to the given expected output path."""
self._PrintVerbose('Copying %s to %s' % (source_path, output_path))
output_path_dir = os.path.dirname(output_path)
if not os.path.exists(output_path_dir):
try:
os.makedirs(output_path_dir)
except OSError as e:
_PrintXcodeError('Failed to create output directory "%s". '
'%s' % (output_path_dir, e))
return 650
try:
CopyOnWrite(full_source_path, output_path)
except OSError as e:
_PrintXcodeError('Copy failed. %s' % e)
return 650
return 0
def _UnpackTarget(self, bundle_path, output_path, bundle_subpath):
"""Unpacks generated bundle into the given expected output path."""
self._PrintVerbose('Unpacking %s to %s' % (bundle_path, output_path))
if not os.path.isfile(bundle_path):
_PrintXcodeError('Generated bundle not found at "%s"' % bundle_path)
return 670
if os.path.isdir(output_path):
try:
shutil.rmtree(output_path)
except OSError as e:
_PrintXcodeError('Failed to remove stale output directory ""%s". '
'%s' % (output_path, e))
return 600
# We need to handle IPAs (from {ios, tvos}_application) differently from
# ZIPs (from the other bundled rules) because they output slightly different
# directory structures.
is_ipa = bundle_path.endswith('.ipa')
with zipfile.ZipFile(bundle_path, 'r') as zf:
for item in zf.infolist():
filename = item.filename
# Support directories do not seem to be needed by the debugger and are
# skipped.
basedir = filename.split(os.sep)[0]
if basedir.endswith('Support') or basedir.endswith('Support2'):
continue
if len(filename) < len(bundle_subpath):
continue
attributes = (item.external_attr >> 16) & 0o777
self._PrintVerbose('Extracting %s (%o)' % (filename, attributes),
level=1)
if not filename.startswith(bundle_subpath):
_PrintXcodeWarning('Mismatched extraction path. Bundle content '
'at "%s" expected to have subpath of "%s"' %
(filename, bundle_subpath))
dir_components = self._SplitPathComponents(filename)
# Get the file's path, ignoring the payload components if the archive
# is an IPA.
if is_ipa:
subpath = os.path.join(*dir_components[2:])
else:
subpath = os.path.join(*dir_components[1:])
target_path = os.path.join(output_path, subpath)
# Ensure the target directory exists.
try:
target_dir = os.path.dirname(target_path)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
except OSError as e:
_PrintXcodeError(
'Failed to create target path "%s" during extraction. %s' % (
target_path, e))
return 671
# If the archive item looks like a file, extract it.
if not filename.endswith(os.sep):
with zf.open(item) as src, file(target_path, 'wb') as dst:
shutil.copyfileobj(src, dst)
# Patch up the extracted file's attributes to match the zip content.
if attributes:
os.chmod(target_path, attributes)
return 0
def _InstallDSYMBundles(self, output_dir, outputs_data):
"""Copies any generated dSYM bundles to the given directory."""
# Indicates that our aspect reports a dSYM was generated for this build.
primary_output_data = outputs_data[0]
has_dsym = primary_output_data['has_dsym']
if not has_dsym:
return 0, None
# Start the timer now that we know we have dSYM bundles to install.
timer = Timer('Installing DSYM bundles', 'installing_dsym').Start()
# Declares the Xcode-generated name of our main target's dSYM.
# This environment variable is always set, for any possible Xcode output
# that could generate a dSYM bundle.
#
# Note that this may differ from the Bazel name as Tulsi may modify the
# Xcode `BUNDLE_NAME`, so we need to make sure we use Bazel as the source
# of truth for Bazel's dSYM name, but copy it over to where Xcode expects.
xcode_target_dsym = os.environ.get('DWARF_DSYM_FILE_NAME')
dsym_to_process = set()
if xcode_target_dsym:
dsym_path = primary_output_data.get('dsym_path')
if dsym_path:
dsym_to_process.add((dsym_path, xcode_target_dsym))
else:
_PrintXcodeWarning(
'Unable to resolve dSYM paths for main bundle %s'
% primary_output_data)
# Collect additional dSYM bundles generated by the dependencies of this
# build such as extensions or frameworks.
child_dsyms = set()
for data in outputs_data:
for bundle_info in data.get('embedded_bundles', []):
if not bundle_info['has_dsym']:
continue
dsym_path = bundle_info.get('dsym_path')
if dsym_path:
child_dsyms.add((dsym_path, os.path.basename(dsym_path)))
else:
_PrintXcodeWarning(
'Unable to resolve dSYM paths for embedded bundle %s'
% bundle_info)
dsym_to_process.update(child_dsyms)
dsyms_found = []
for input_dsym_full_path, xcode_dsym_name in dsym_to_process:
output_full_path = os.path.join(output_dir, xcode_dsym_name)
exit_code, path = self._InstallBundle(input_dsym_full_path,
output_full_path)
if exit_code:
_PrintXcodeWarning('Failed to install dSYM to "%s" (%s)'
% (input_dsym_full_path, exit_code))
elif path is None:
_PrintXcodeWarning('Did not find a dSYM bundle at %s'
% input_dsym_full_path)
else:
dsyms_found.append(path)
timer.End()
return 0, dsyms_found
def _ResignBundle(self, bundle_path, signing_identity, entitlements=None):
"""Re-signs the bundle with the given signing identity and entitlements."""
if not self.codesigning_allowed:
return 0
timer = Timer('\tSigning ' + bundle_path, 'signing_bundle').Start()
command = [
'xcrun',
'codesign',
'-f',
'--timestamp=none',
'-s',
signing_identity,
]
if entitlements:
command.extend(['--entitlements', entitlements])
else:
command.append('--preserve-metadata=entitlements')
command.append(bundle_path)
returncode, output = self._RunSubprocess(command)
timer.End()
if returncode:
_PrintXcodeError('Re-sign command %r failed. %s' % (command, output))
return 800 + returncode
return 0
def _ResignTestArtifacts(self):
"""Resign test related artifacts that Xcode injected into the outputs."""
if not self.is_test:
return 0
# Extract the signing identity from the bundle at the expected output path
# since that's where the signed bundle from bazel was placed.
signing_identity = self._ExtractSigningIdentity(self.artifact_output_path)
if not signing_identity:
return 800
exit_code = 0
timer = Timer('Re-signing injected test host artifacts',
'resigning_test_host').Start()
if self.test_host_binary:
# For Unit tests, we need to resign the frameworks that Xcode injected
# into the test host bundle.
test_host_bundle = os.path.dirname(self.test_host_binary)
exit_code = self._ResignXcodeTestFrameworks(
test_host_bundle, signing_identity)
else:
# For UI tests, we need to resign the UI test runner app and the
# frameworks that Xcode injected into the runner app. The UI Runner app
# also needs to be signed with entitlements.
exit_code = self._ResignXcodeTestFrameworks(
self.codesigning_folder_path, signing_identity)
if exit_code == 0:
entitlements_path = self._InstantiateUIRunnerEntitlements()
if entitlements_path:
exit_code = self._ResignBundle(
self.codesigning_folder_path,
signing_identity,
entitlements_path)
else:
_PrintXcodeError('Could not instantiate UI runner entitlements.')
exit_code = 800
timer.End()
return exit_code
def _ResignXcodeTestFrameworks(self, bundle, signing_identity):
"""Re-signs the support frameworks injected by Xcode in the given bundle."""
if not self.codesigning_allowed:
return 0
for framework in XCODE_INJECTED_FRAMEWORKS:
framework_path = os.path.join(
bundle, 'Frameworks', framework)
if os.path.isdir(framework_path) or os.path.isfile(framework_path):
exit_code = self._ResignBundle(framework_path, signing_identity)
if exit_code != 0:
return exit_code
return 0
def _InstantiateUIRunnerEntitlements(self):
"""Substitute team and bundle identifiers into UI runner entitlements.
This method throws an IOError exception if the template wasn't found in
its expected location, or an OSError if the expected output folder could
not be created.
Returns:
The path to where the entitlements file was generated.
"""
if not self.codesigning_allowed:
return None
if not os.path.exists(self.derived_sources_folder_path):
os.makedirs(self.derived_sources_folder_path)
output_file = os.path.join(
self.derived_sources_folder_path,
self.bazel_product_name + '_UIRunner.entitlements')
if os.path.exists(output_file):
os.remove(output_file)
with open(self.runner_entitlements_template, 'r') as template:
contents = template.read()
contents = contents.replace(
'$(TeamIdentifier)',
self._ExtractSigningTeamIdentifier(self.artifact_output_path))
contents = contents.replace(
'$(BundleIdentifier)',
self._ExtractSigningBundleIdentifier(self.artifact_output_path))
with open(output_file, 'w') as output:
output.write(contents)
return output_file
def _ExtractSigningIdentity(self, signed_bundle):
"""Returns the identity used to sign the given bundle path."""
return self._ExtractSigningAttribute(signed_bundle, 'Authority')
def _ExtractSigningTeamIdentifier(self, signed_bundle):
"""Returns the team identifier used to sign the given bundle path."""
return self._ExtractSigningAttribute(signed_bundle, 'TeamIdentifier')
def _ExtractSigningBundleIdentifier(self, signed_bundle):
"""Returns the bundle identifier used to sign the given bundle path."""
return self._ExtractSigningAttribute(signed_bundle, 'Identifier')
def _ExtractSigningAttribute(self, signed_bundle, attribute):
"""Returns the attribute used to sign the given bundle path."""
if not self.codesigning_allowed:
return '<CODE_SIGNING_ALLOWED=NO>'
cached = self.codesign_attributes.get(signed_bundle)
if cached:
return cached.Get(attribute)
timer = Timer('\tExtracting signature for ' + signed_bundle,
'extracting_signature').Start()
output = subprocess.check_output(['xcrun',
'codesign',
'-dvv',
signed_bundle],
stderr=subprocess.STDOUT)
timer.End()
bundle_attributes = CodesignBundleAttributes(output)
self.codesign_attributes[signed_bundle] = bundle_attributes
return bundle_attributes.Get(attribute)
def _UpdateLLDBInit(self, clear_source_map=False):
"""Updates ~/.lldbinit-tulsiproj to enable debugging of Bazel binaries."""
# Make sure a reference to ~/.lldbinit-tulsiproj exists in ~/.lldbinit or
# ~/.lldbinit-Xcode. Priority is given to ~/.lldbinit-Xcode if it exists,
# otherwise the bootstrapping will be written to ~/.lldbinit.
BootstrapLLDBInit()
with open(TULSI_LLDBINIT_FILE, 'w') as out:
out.write('# This file is autogenerated by Tulsi and should not be '
'edited.\n')
if clear_source_map:
out.write('settings clear target.source-map\n')
return 0
if self.normalized_prefix_map:
so | else:
# NOTE: settings target.source-map is different from
# DBGSourcePathRemapping; the former is an LLDB target-level
# remapping API that rewrites breakpoints, the latter is an LLDB
# module-level remapping API that changes DWARF debug info in memory.
#
# If we had multiple remappings, it would not make sense for the
# two APIs to share the same mappings. They have very different
# side-effects in how they individually handle debug information.
source_map = self._ExtractTargetSourceMap()
out.write('# This maps Bazel\'s execution root to that used by '
'%r.\n' % os.path.basename(self.project_file_path))
out.write('settings set target.source-map "%s" "%s"\n' % source_map)
return 0
def _DWARFdSYMBinaries(self, dsym_bundle_path):
"""Returns an array of abs paths to DWARF binaries in the dSYM bundle.
Args:
dsym_bundle_path: absolute path to the dSYM bundle.
Returns:
str[]: a list of strings representing the absolute paths to each binary
found within the dSYM bundle.
"""
dwarf_dir = os.path.join(dsym_bundle_path,
'Contents',
'Resources',
'DWARF')
dsym_binaries = []
for f in os.listdir(dwarf_dir):
# Ignore hidden files, such as .DS_Store files.
if not f.startswith('.'):
# Append full path info.
dsym_binary = os.path.join(dwarf_dir, f)
dsym_binaries.append(dsym_binary)
return dsym_binaries
def _UUIDInfoForBinary(self, source_binary_path):
"""Returns exit code of dwarfdump along with every UUID + arch found.
Args:
source_binary_path: absolute path to the binary file.
Returns:
(Int, str[(str, str)]): a tuple containing the return code of dwarfdump
as its first element, and a list of strings
representing each UUID found for each given
binary slice found within the binary with its
given architecture, if no error has occcured.
"""
returncode, output = self._RunSubprocess([
'xcrun',
'dwarfdump',
'--uuid',
source_binary_path
])
if returncode:
_PrintXcodeWarning('dwarfdump returned %d while finding the UUID for %s'
% (returncode, source_binary_path))
return (returncode, [])
# All UUIDs for binary slices will be returned as the second from left,
# from output; "UUID: D4DE5AA2-79EE-36FE-980C-755AED318308 (x86_64)
# /Applications/Calendar.app/Contents/MacOS/Calendar"
uuids_found = []
for dwarfdump_output in output.split('\n'):
if not dwarfdump_output:
continue
found_output = re.match(r'^(?:UUID: )([^ ]+) \(([^)]+)', dwarfdump_output)
if not found_output:
continue
found_uuid = found_output.group(1)
if not found_uuid:
continue
found_arch = found_output.group(2)
if not found_arch:
continue
uuids_found.append((found_uuid, found_arch))
return (0, uuids_found)
def _CreateUUIDPlist(self, dsym_bundle_path, uuid, arch, source_maps):
"""Creates a UUID.plist in a dSYM bundle to redirect sources.
Args:
dsym_bundle_path: absolute path to the dSYM bundle.
uuid: string representing the UUID of the binary slice with paths to
remap in the dSYM bundle.
arch: the architecture of the binary slice.
source_maps: list of tuples representing all absolute paths to source
files compiled by Bazel as strings ($0) associated with the
paths to Xcode-visible sources used for the purposes of
Tulsi debugging as strings ($1).
Returns:
Bool: True if no error was found, or False, representing a failure to
write when creating the plist.
"""
# Create a UUID plist at (dsym_bundle_path)/Contents/Resources/.
remap_plist = os.path.join(dsym_bundle_path,
'Contents',
'Resources',
'%s.plist' % uuid)
# Via an XML plist, add the mappings from _ExtractTargetSourceMap().
try:
with open(remap_plist, 'w') as out:
out.write('<?xml version="1.0" encoding="UTF-8"?>\n'
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" '
'"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
'<plist version="1.0">\n'
'<dict>\n'
'<key>DBGSourcePathRemapping</key>\n'
'<dict>\n')
for source_map in source_maps:
# Add the mapping as a DBGSourcePathRemapping to the UUID plist here.
out.write('<key>%s</key>\n<string>%s</string>\n' % source_map)
# Make sure that we also set DBGVersion to 3.
out.write('</dict>\n'
'<key>DBGVersion</key>\n'
'<string>3</string>\n'
'</dict>\n'
'</plist>\n')
except OSError as e:
_PrintXcodeError('Failed to write %s, received error %s' %
(remap_plist, e))
return False
# Update the dSYM symbol cache with a reference to this dSYM bundle.
err_msg = self.update_symbol_cache.UpdateUUID(uuid,
dsym_bundle_path,
arch)
if err_msg:
_PrintXcodeWarning('Attempted to save (uuid, dsym_bundle_path, arch) '
'to DBGShellCommands\' dSYM cache, but got error '
'\"%s\".' % err_msg)
return True
def _CleanExistingDSYMs(self):
"""Clean dSYM bundles that were left over from a previous build."""
output_dir = self.built_products_dir
output_dir_list = os.listdir(output_dir)
for item in output_dir_list:
if item.endswith('.dSYM'):
shutil.rmtree(os.path.join(output_dir, item))
def _PlistdSYMPaths(self, dsym_bundle_path):
"""Adds Plists to a given dSYM bundle to redirect DWARF data."""
# Retrieve the paths that we are expected to remap.
# Always include a direct path from the execroot to Xcode-visible sources.
source_maps = [self._ExtractTargetSourceMap()]
# Remap relative paths from the workspace root.
if self.normalized_prefix_map:
# Take the normalized path and map that to Xcode-visible sources.
source_maps.append(('./', self._NormalizePath(self.workspace_root)))
# Find the binaries within the dSYM bundle. UUIDs will match that of the
# binary it was based on.
dsym_binaries = self._DWARFdSYMBinaries(dsym_bundle_path)
if not dsym_binaries:
_PrintXcodeWarning('Could not find the binaries that the dSYM %s was '
'based on to determine DWARF binary slices to patch. '
'Debugging will probably fail.' % (dsym_bundle_path))
return 404
# Find the binary slice UUIDs with dwarfdump from each binary.
for source_binary_path in dsym_binaries:
returncode, uuid_info_found = self._UUIDInfoForBinary(source_binary_path)
if returncode:
return returncode
# Create a plist per UUID, each indicating a binary slice to remap paths.
for uuid, arch in uuid_info_found:
plist_created = self._CreateUUIDPlist(dsym_bundle_path,
uuid,
arch,
source_maps)
if not plist_created:
return 405
return 0
def _NormalizePath(self, path):
"""Returns paths with a common form, normalized with a trailing slash.
Args:
path: a file system path given in the form of a string.
Returns:
str: a normalized string with a trailing slash, based on |path|.
"""
return os.path.normpath(path) + os.sep
def _ExtractTargetSourceMap(self, normalize=True):
"""Extracts the source path as a tuple associated with the WORKSPACE path.
Args:
normalize: Defines if all paths should be normalized. Preferred for APIs
like DBGSourcePathRemapping and target.source-map but won't
work for the purposes of -fdebug-prefix-map.
Returns:
None: if an error occurred.
(str, str): a single tuple representing all absolute paths to source
files compiled by Bazel as strings ($0) associated with
the paths to Xcode-visible sources used for the purposes
of Tulsi debugging as strings ($1).
"""
# All paths route to the "workspace root" for sources visible from Xcode.
sm_destpath = self.workspace_root
if normalize:
sm_destpath = self._NormalizePath(sm_destpath)
# Add a redirection for the Bazel execution root, the path where sources
# are referenced by Bazel.
sm_execroot = self.bazel_exec_root
if normalize:
sm_execroot = self._NormalizePath(sm_execroot)
return (sm_execroot, sm_destpath)
def _LinkTulsiWorkspace(self):
"""Links the Bazel Workspace to the Tulsi Workspace (`tulsi-workspace`)."""
tulsi_workspace = os.path.join(self.project_file_path,
'.tulsi',
'tulsi-workspace')
if os.path.islink(tulsi_workspace):
os.unlink(tulsi_workspace)
os.symlink(self.bazel_exec_root, tulsi_workspace)
if not os.path.exists(tulsi_workspace):
_PrintXcodeError(
'Linking Tulsi Workspace to %s failed.' % tulsi_workspace)
return -1
@staticmethod
def _SplitPathComponents(path):
"""Splits the given path into an array of all of its components."""
components = path.split(os.sep)
# Patch up the first component if path started with an os.sep
if not components[0]:
components[0] = os.sep
return components
def _RunSubprocess(self, cmd):
"""Runs the given command as a subprocess, returning (exit_code, output)."""
self._PrintVerbose('%r' % cmd, 1)
process = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output, _ = process.communicate()
return (process.returncode, output)
def _PrintVerbose(self, msg, level=0):
if self.verbose > level:
_PrintUnbuffered(msg)
def main(argv):
build_settings = bazel_build_settings.BUILD_SETTINGS
if build_settings is None:
_Fatal('Unable to resolve build settings. Please report a Tulsi bug.')
return 1
return BazelBuildBridge(build_settings).Run(argv)
if __name__ == '__main__':
# Register the interrupt handler immediately in case we receive SIGINT while
# trying to acquire the lock.
signal.signal(signal.SIGINT, _InterruptHandler)
_LockFileAcquire(_LockFileCreate())
_logger = tulsi_logging.Logger()
logger_warning = tulsi_logging.validity_check()
if logger_warning:
_PrintXcodeWarning(logger_warning)
_timer = Timer('Everything', 'complete_build').Start()
_exit_code = main(sys.argv)
_timer.End()
sys.exit(_exit_code)
| urce_map = ('./', self._NormalizePath(self.workspace_root))
out.write('# This maps the normalized root to that used by '
'%r.\n' % os.path.basename(self.project_file_path))
|
text_case.rs | use wasm_bindgen::prelude::*;
use convert_case::{Case, Casing};
#[wasm_bindgen]
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug)]
pub enum TextCase {
Upper,
Lower,
Title,
Toggle,
Camel,
Pascal,
UpperCamel,
Snake,
UpperSnake,
ScreamingSnake,
Kebab,
Cobol,
UpperKebab,
Train,
Flat,
UpperFlat,
Alternating,
}
impl TextCase {
// Reference: https://doc.rust-jp.rs/rust-by-example-ja/custom_types/enum.html#型エイリアス
fn into_case(&s | ase {
match self {
Self::Upper => Case::Upper,
Self::Lower => Case::Lower,
Self::Title => Case::Title,
Self::Toggle => Case::Toggle,
Self::Camel => Case::Camel,
Self::Pascal => Case::Pascal,
Self::UpperCamel => Case::UpperCamel,
Self::Snake => Case::Snake,
Self::ScreamingSnake => Case::ScreamingSnake,
Self::Kebab => Case::Kebab,
Self::Cobol => Case::Cobol,
Self::UpperKebab => Case::UpperKebab,
Self::Train => Case::Train,
Self::Flat => Case::Flat,
Self::UpperFlat => Case::UpperFlat,
Self::Alternating => Case::Alternating,
_ => Case::Alternating,
}
}
}
#[wasm_bindgen]
pub fn text_case_convert(txt: &str, to_case: TextCase) -> String {
txt.to_case(to_case.into_case())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_case_snake() {
let input = "__weird--var _name-";
let expect = "weird_var_name";
let output = text_case_convert(input, TextCase::Snake);
assert_eq!(expect, output);
}
}
| elf) -> C |
resolver.rs | use crate::dns_packet::{BufferIO, Packet, Query, QueryType, ReturnCode};
use crate::packet_buffer::PacketBuffer;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub struct Resolver {
socket: UdpSocket,
}
impl Resolver {
pub fn new(bind_addr: &str, port: u16) -> Result<Self> {
let socket = UdpSocket::bind((bind_addr, port))?;
Ok(Resolver { socket })
}
fn send_packet(
&self,
mut packet: Packet,
socket: &UdpSocket,
dst_socket: &(IpAddr, u16),
) -> Result<()> {
let mut buf = PacketBuffer::new();
packet.write_to_buffer(&mut buf)?;
socket.send_to(buf.get_range(0, buf.pos())?, dst_socket)?;
Ok(())
}
fn receive_packet(&self, socket: &UdpSocket) -> Result<(Packet, SocketAddr)> {
let mut raw_buf: [u8; 512] = [0; 512];
let (_, src_socket) = socket.recv_from(&mut raw_buf)?;
let mut buf = PacketBuffer::from_u8_array(raw_buf);
let packet = Packet::from_buffer(&mut buf)?;
Ok((packet, src_socket))
}
pub fn handle_query(&self) -> Result<()> {
let (req_packet, src_socket) = self.receive_packet(&self.socket)?;
let mut res_packet = Packet::new();
res_packet.header.id = req_packet.header.id;
res_packet.header.recursion_desired = true;
res_packet.header.recursion_available = true;
res_packet.header.response = true;
if req_packet.queries.is_empty() {
res_packet.header.return_code = ReturnCode::FORMERR;
}
for query in req_packet.queries.iter() {
println!("Received query: {:?}", query);
if let Ok(result) = self.recursive_lookup(&query.qname, query.qtype) {
res_packet.queries.push(query.clone());
res_packet.header.return_code = result.header.return_code;
for rec in result.answer_records {
println!("Answer record: {:?}", rec);
res_packet.answer_records.push(rec);
}
for rec in result.authoritative_records {
println!("Authority record: {:?}", rec);
res_packet.authoritative_records.push(rec);
}
for rec in result.additional_records {
println!("Additional record: {:?}", rec);
res_packet.additional_records.push(rec);
}
} else {
res_packet.header.return_code = ReturnCode::SERVFAIL;
}
}
self.send_packet(
res_packet,
&self.socket,
&(src_socket.ip(), src_socket.port()),
)?;
Ok(())
}
fn lookup(&self, qname: &str, qtype: QueryType, server: (IpAddr, u16)) -> Result<Packet> {
let lookup_socket = UdpSocket::bind(("0.0.0.0", 43210))?;
let mut req_packet = Packet::new();
req_packet.header.id = 1234;
req_packet.header.queries_total = 1;
req_packet.header.recursion_desired = true;
req_packet
.queries
.push(Query::new(qname.to_string(), qtype));
self.send_packet(req_packet, &lookup_socket, &server)?;
let (res_packet, _) = self.receive_packet(&lookup_socket)?;
Ok(res_packet)
}
fn recursive_lookup(&self, qname: &str, qtype: QueryType) -> Result<Packet> {
let a_root_servers_net_ip = "198.41.0.4";
let mut ns = IpAddr::V4(a_root_servers_net_ip.parse::<Ipv4Addr>().unwrap());
loop {
println!("Performing lookup of {:?} {} with ns {}", qtype, qname, ns);
let server = (ns, 53);
let response = self.lookup(qname, qtype, server)?;
if (!response.answer_records.is_empty()
&& response.header.return_code == ReturnCode::NOERROR)
|| response.header.return_code == ReturnCode::NXDOMAIN
{
return Ok(response);
}
if let Some(&new_ns) = response.get_ns_from_additional_records(qname).last() {
ns = IpAddr::V4(*new_ns);
continue;
}
let new_ns_host = match response.get_ns_hosts(qname).last() {
Some(&host) => host,
None => return Ok(response),
};
let recursive_response = self.recursive_lookup(new_ns_host, qtype)?;
ns = match recursive_response.get_answer_a_records().last() {
Some(&new_ns) => IpAddr::V4(*new_ns),
None => return Ok(response),
};
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recursive_lookup() -> Result<()> {
/* Arrange */
let localhost_str = "127.0.0.1";
let localhost_addr = localhost_str.parse::<Ipv4Addr>()?;
// Resolver
let resolver_port = 2053;
let resolver = Resolver::new(localhost_str, resolver_port)?;
// Client
let socket = UdpSocket::bind((localhost_str, 2054))?;
// Query Packet
let qname = "google.com";
let qtype = QueryType::A;
let mut packet = Packet::new();
packet.header.id = 123;
packet.header.queries_total = 1;
packet.header.recursion_desired = true;
packet.queries.push(Query::new(qname.to_string(), qtype));
let mut req_buffer = PacketBuffer::new();
packet.write_to_buffer(&mut req_buffer)?;
/* Act */
socket.send_to(
req_buffer.get_range(0, req_buffer.pos())?,
(localhost_addr, resolver_port),
)?;
resolver.handle_query()?;
let mut raw_buf: [u8; 512] = [0; 512];
socket.recv_from(&mut raw_buf)?;
let mut res_buf = PacketBuffer::from_u8_array(raw_buf);
let res_packet = Packet::from_buffer(&mut res_buf)?;
/* Assert */
assert!(res_packet.queries.len() > 0);
assert_eq!(res_packet.queries[0].qname, "google.com");
assert!(res_packet.answer_records.len() > 0);
match res_packet.answer_records[0] { | _ => panic!(),
}
Ok(())
}
} | crate::dns_packet::ResourceRecord::A { ref domain, .. } => {
assert_eq!("google.com", domain);
} |
output.rs | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct StartDocumentTextDetectionOutput {
/// <p>The identifier of the text detection job for the document. Use <code>JobId</code> to
/// identify the job in a subsequent call to <code>GetDocumentTextDetection</code>.
/// A <code>JobId</code> value is only valid for 7 days.</p>
pub job_id: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for StartDocumentTextDetectionOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("StartDocumentTextDetectionOutput");
formatter.field("job_id", &self.job_id);
formatter.finish()
}
}
/// See [`StartDocumentTextDetectionOutput`](crate::output::StartDocumentTextDetectionOutput)
pub mod start_document_text_detection_output {
/// A builder for [`StartDocumentTextDetectionOutput`](crate::output::StartDocumentTextDetectionOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) job_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the text detection job for the document. Use <code>JobId</code> to
/// identify the job in a subsequent call to <code>GetDocumentTextDetection</code>.
/// A <code>JobId</code> value is only valid for 7 days.</p>
pub fn job_id(mut self, input: impl Into<std::string::String>) -> Self {
self.job_id = Some(input.into());
self
}
pub fn set_job_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.job_id = input;
self
}
/// Consumes the builder and constructs a [`StartDocumentTextDetectionOutput`](crate::output::StartDocumentTextDetectionOutput)
pub fn build(self) -> crate::output::StartDocumentTextDetectionOutput {
crate::output::StartDocumentTextDetectionOutput {
job_id: self.job_id,
}
}
}
}
impl StartDocumentTextDetectionOutput {
/// Creates a new builder-style object to manufacture [`StartDocumentTextDetectionOutput`](crate::output::StartDocumentTextDetectionOutput)
pub fn builder() -> crate::output::start_document_text_detection_output::Builder {
crate::output::start_document_text_detection_output::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct StartDocumentAnalysisOutput {
/// <p>The identifier for the document text detection job. Use <code>JobId</code> to identify
/// the job in a subsequent call to <code>GetDocumentAnalysis</code>. A <code>JobId</code> value
/// is only valid for 7 days.</p>
pub job_id: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for StartDocumentAnalysisOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("StartDocumentAnalysisOutput");
formatter.field("job_id", &self.job_id);
formatter.finish()
}
}
/// See [`StartDocumentAnalysisOutput`](crate::output::StartDocumentAnalysisOutput)
pub mod start_document_analysis_output {
/// A builder for [`StartDocumentAnalysisOutput`](crate::output::StartDocumentAnalysisOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) job_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier for the document text detection job. Use <code>JobId</code> to identify
/// the job in a subsequent call to <code>GetDocumentAnalysis</code>. A <code>JobId</code> value
/// is only valid for 7 days.</p>
pub fn job_id(mut self, input: impl Into<std::string::String>) -> Self {
self.job_id = Some(input.into());
self
}
pub fn set_job_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.job_id = input;
self
}
/// Consumes the builder and constructs a [`StartDocumentAnalysisOutput`](crate::output::StartDocumentAnalysisOutput)
pub fn build(self) -> crate::output::StartDocumentAnalysisOutput {
crate::output::StartDocumentAnalysisOutput {
job_id: self.job_id,
}
}
}
}
impl StartDocumentAnalysisOutput {
/// Creates a new builder-style object to manufacture [`StartDocumentAnalysisOutput`](crate::output::StartDocumentAnalysisOutput)
pub fn builder() -> crate::output::start_document_analysis_output::Builder {
crate::output::start_document_analysis_output::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetDocumentTextDetectionOutput {
/// <p>Information about a document that Amazon Textract processed. <code>DocumentMetadata</code> is
/// returned in every page of paginated responses from an Amazon Textract video operation.</p>
pub document_metadata: std::option::Option<crate::model::DocumentMetadata>,
/// <p>The current status of the text detection job.</p>
pub job_status: std::option::Option<crate::model::JobStatus>,
/// <p>If the response is truncated, Amazon Textract returns this token. You can use this token in
/// the subsequent request to retrieve the next set of text-detection results.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The results of the text-detection operation.</p>
pub blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
/// <p>A list of warnings that occurred during the text-detection operation for the
/// document.</p>
pub warnings: std::option::Option<std::vec::Vec<crate::model::Warning>>,
/// <p>Returns if the detection job could not be completed. Contains explanation for what error occured. </p>
pub status_message: std::option::Option<std::string::String>,
/// <p></p>
pub detect_document_text_model_version: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for GetDocumentTextDetectionOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetDocumentTextDetectionOutput");
formatter.field("document_metadata", &self.document_metadata);
formatter.field("job_status", &self.job_status);
formatter.field("next_token", &self.next_token);
formatter.field("blocks", &self.blocks);
formatter.field("warnings", &self.warnings);
formatter.field("status_message", &self.status_message);
formatter.field(
"detect_document_text_model_version",
&self.detect_document_text_model_version,
);
formatter.finish()
}
}
/// See [`GetDocumentTextDetectionOutput`](crate::output::GetDocumentTextDetectionOutput)
pub mod get_document_text_detection_output {
/// A builder for [`GetDocumentTextDetectionOutput`](crate::output::GetDocumentTextDetectionOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) document_metadata: std::option::Option<crate::model::DocumentMetadata>,
pub(crate) job_status: std::option::Option<crate::model::JobStatus>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
pub(crate) warnings: std::option::Option<std::vec::Vec<crate::model::Warning>>,
pub(crate) status_message: std::option::Option<std::string::String>,
pub(crate) detect_document_text_model_version: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Information about a document that Amazon Textract processed. <code>DocumentMetadata</code> is
/// returned in every page of paginated responses from an Amazon Textract video operation.</p>
pub fn document_metadata(mut self, input: crate::model::DocumentMetadata) -> Self {
self.document_metadata = Some(input);
self
}
pub fn set_document_metadata(
mut self,
input: std::option::Option<crate::model::DocumentMetadata>,
) -> Self {
self.document_metadata = input;
self
}
/// <p>The current status of the text detection job.</p>
pub fn job_status(mut self, input: crate::model::JobStatus) -> Self {
self.job_status = Some(input);
self
}
pub fn set_job_status(
mut self,
input: std::option::Option<crate::model::JobStatus>,
) -> Self {
self.job_status = input;
self
}
/// <p>If the response is truncated, Amazon Textract returns this token. You can use this token in
/// the subsequent request to retrieve the next set of text-detection results.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
pub fn blocks(mut self, input: impl Into<crate::model::Block>) -> Self {
let mut v = self.blocks.unwrap_or_default();
v.push(input.into());
self.blocks = Some(v);
self
}
pub fn set_blocks(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Block>>,
) -> Self {
self.blocks = input;
self
}
pub fn warnings(mut self, input: impl Into<crate::model::Warning>) -> Self {
let mut v = self.warnings.unwrap_or_default();
v.push(input.into());
self.warnings = Some(v);
self
}
pub fn set_warnings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Warning>>,
) -> Self {
self.warnings = input;
self
}
/// <p>Returns if the detection job could not be completed. Contains explanation for what error occured. </p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// <p></p>
pub fn detect_document_text_model_version(
mut self,
input: impl Into<std::string::String>,
) -> Self {
self.detect_document_text_model_version = Some(input.into());
self
}
pub fn set_detect_document_text_model_version(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.detect_document_text_model_version = input;
self
}
/// Consumes the builder and constructs a [`GetDocumentTextDetectionOutput`](crate::output::GetDocumentTextDetectionOutput)
pub fn build(self) -> crate::output::GetDocumentTextDetectionOutput {
crate::output::GetDocumentTextDetectionOutput {
document_metadata: self.document_metadata,
job_status: self.job_status,
next_token: self.next_token,
blocks: self.blocks,
warnings: self.warnings,
status_message: self.status_message,
detect_document_text_model_version: self.detect_document_text_model_version,
}
}
}
}
impl GetDocumentTextDetectionOutput {
/// Creates a new builder-style object to manufacture [`GetDocumentTextDetectionOutput`](crate::output::GetDocumentTextDetectionOutput)
pub fn builder() -> crate::output::get_document_text_detection_output::Builder {
crate::output::get_document_text_detection_output::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetDocumentAnalysisOutput {
/// <p>Information about a document that Amazon Textract processed. <code>DocumentMetadata</code> is
/// returned in every page of paginated responses from an Amazon Textract video operation.</p>
pub document_metadata: std::option::Option<crate::model::DocumentMetadata>,
/// <p>The current status of the text detection job.</p>
pub job_status: std::option::Option<crate::model::JobStatus>,
/// <p>If the response is truncated, Amazon Textract returns this token. You can use this token in
/// the subsequent request to retrieve the next set of text detection results.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The results of the text-analysis operation.</p>
pub blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
/// <p>A list of warnings that occurred during the document-analysis operation.</p>
pub warnings: std::option::Option<std::vec::Vec<crate::model::Warning>>,
/// <p>Returns if the detection job could not be completed. Contains explanation for what error occured.</p>
pub status_message: std::option::Option<std::string::String>,
/// <p></p>
pub analyze_document_model_version: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for GetDocumentAnalysisOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetDocumentAnalysisOutput");
formatter.field("document_metadata", &self.document_metadata);
formatter.field("job_status", &self.job_status);
formatter.field("next_token", &self.next_token);
formatter.field("blocks", &self.blocks);
formatter.field("warnings", &self.warnings);
formatter.field("status_message", &self.status_message);
formatter.field(
"analyze_document_model_version",
&self.analyze_document_model_version,
);
formatter.finish()
}
}
/// See [`GetDocumentAnalysisOutput`](crate::output::GetDocumentAnalysisOutput)
pub mod get_document_analysis_output {
/// A builder for [`GetDocumentAnalysisOutput`](crate::output::GetDocumentAnalysisOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) document_metadata: std::option::Option<crate::model::DocumentMetadata>,
pub(crate) job_status: std::option::Option<crate::model::JobStatus>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
pub(crate) warnings: std::option::Option<std::vec::Vec<crate::model::Warning>>,
pub(crate) status_message: std::option::Option<std::string::String>,
pub(crate) analyze_document_model_version: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Information about a document that Amazon Textract processed. <code>DocumentMetadata</code> is
/// returned in every page of paginated responses from an Amazon Textract video operation.</p>
pub fn document_metadata(mut self, input: crate::model::DocumentMetadata) -> Self {
self.document_metadata = Some(input);
self
}
pub fn set_document_metadata(
mut self,
input: std::option::Option<crate::model::DocumentMetadata>,
) -> Self {
self.document_metadata = input;
self
}
/// <p>The current status of the text detection job.</p>
pub fn job_status(mut self, input: crate::model::JobStatus) -> Self {
self.job_status = Some(input);
self
}
pub fn set_job_status(
mut self,
input: std::option::Option<crate::model::JobStatus>,
) -> Self {
self.job_status = input;
self
}
/// <p>If the response is truncated, Amazon Textract returns this token. You can use this token in
/// the subsequent request to retrieve the next set of text detection results.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
pub fn blocks(mut self, input: impl Into<crate::model::Block>) -> Self {
let mut v = self.blocks.unwrap_or_default();
v.push(input.into());
self.blocks = Some(v);
self
}
pub fn set_blocks(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Block>>,
) -> Self {
self.blocks = input;
self
}
pub fn warnings(mut self, input: impl Into<crate::model::Warning>) -> Self {
let mut v = self.warnings.unwrap_or_default();
v.push(input.into());
self.warnings = Some(v);
self
}
pub fn set_warnings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Warning>>,
) -> Self {
self.warnings = input;
self
}
/// <p>Returns if the detection job could not be completed. Contains explanation for what error occured.</p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// <p></p>
pub fn analyze_document_model_version(
mut self,
input: impl Into<std::string::String>,
) -> Self {
self.analyze_document_model_version = Some(input.into());
self
}
pub fn set_analyze_document_model_version(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.analyze_document_model_version = input;
self
}
/// Consumes the builder and constructs a [`GetDocumentAnalysisOutput`](crate::output::GetDocumentAnalysisOutput)
pub fn build(self) -> crate::output::GetDocumentAnalysisOutput {
crate::output::GetDocumentAnalysisOutput {
document_metadata: self.document_metadata,
job_status: self.job_status,
next_token: self.next_token,
blocks: self.blocks,
warnings: self.warnings,
status_message: self.status_message,
analyze_document_model_version: self.analyze_document_model_version,
}
}
}
}
impl GetDocumentAnalysisOutput {
/// Creates a new builder-style object to manufacture [`GetDocumentAnalysisOutput`](crate::output::GetDocumentAnalysisOutput)
pub fn builder() -> crate::output::get_document_analysis_output::Builder {
crate::output::get_document_analysis_output::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DetectDocumentTextOutput {
/// <p>Metadata about the document. It contains the number of pages that are detected in the
/// document.</p>
pub document_metadata: std::option::Option<crate::model::DocumentMetadata>,
/// <p>An array of <code>Block</code> objects that contain the text that's detected in the
/// document.</p>
pub blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
/// <p></p>
pub detect_document_text_model_version: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for DetectDocumentTextOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DetectDocumentTextOutput");
formatter.field("document_metadata", &self.document_metadata);
formatter.field("blocks", &self.blocks);
formatter.field(
"detect_document_text_model_version",
&self.detect_document_text_model_version,
);
formatter.finish()
}
}
/// See [`DetectDocumentTextOutput`](crate::output::DetectDocumentTextOutput)
pub mod detect_document_text_output {
/// A builder for [`DetectDocumentTextOutput`](crate::output::DetectDocumentTextOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) document_metadata: std::option::Option<crate::model::DocumentMetadata>,
pub(crate) blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
pub(crate) detect_document_text_model_version: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Metadata about the document. It contains the number of pages that are detected in the
/// document.</p>
pub fn document_metadata(mut self, input: crate::model::DocumentMetadata) -> Self {
self.document_metadata = Some(input);
self
}
pub fn | (
mut self,
input: std::option::Option<crate::model::DocumentMetadata>,
) -> Self {
self.document_metadata = input;
self
}
pub fn blocks(mut self, input: impl Into<crate::model::Block>) -> Self {
let mut v = self.blocks.unwrap_or_default();
v.push(input.into());
self.blocks = Some(v);
self
}
pub fn set_blocks(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Block>>,
) -> Self {
self.blocks = input;
self
}
/// <p></p>
pub fn detect_document_text_model_version(
mut self,
input: impl Into<std::string::String>,
) -> Self {
self.detect_document_text_model_version = Some(input.into());
self
}
pub fn set_detect_document_text_model_version(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.detect_document_text_model_version = input;
self
}
/// Consumes the builder and constructs a [`DetectDocumentTextOutput`](crate::output::DetectDocumentTextOutput)
pub fn build(self) -> crate::output::DetectDocumentTextOutput {
crate::output::DetectDocumentTextOutput {
document_metadata: self.document_metadata,
blocks: self.blocks,
detect_document_text_model_version: self.detect_document_text_model_version,
}
}
}
}
impl DetectDocumentTextOutput {
/// Creates a new builder-style object to manufacture [`DetectDocumentTextOutput`](crate::output::DetectDocumentTextOutput)
pub fn builder() -> crate::output::detect_document_text_output::Builder {
crate::output::detect_document_text_output::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AnalyzeExpenseOutput {
/// <p>Information about the input document.</p>
pub document_metadata: std::option::Option<crate::model::DocumentMetadata>,
/// <p>The expenses detected by Amazon Textract.</p>
pub expense_documents: std::option::Option<std::vec::Vec<crate::model::ExpenseDocument>>,
}
impl std::fmt::Debug for AnalyzeExpenseOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AnalyzeExpenseOutput");
formatter.field("document_metadata", &self.document_metadata);
formatter.field("expense_documents", &self.expense_documents);
formatter.finish()
}
}
/// See [`AnalyzeExpenseOutput`](crate::output::AnalyzeExpenseOutput)
pub mod analyze_expense_output {
/// A builder for [`AnalyzeExpenseOutput`](crate::output::AnalyzeExpenseOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) document_metadata: std::option::Option<crate::model::DocumentMetadata>,
pub(crate) expense_documents:
std::option::Option<std::vec::Vec<crate::model::ExpenseDocument>>,
}
impl Builder {
/// <p>Information about the input document.</p>
pub fn document_metadata(mut self, input: crate::model::DocumentMetadata) -> Self {
self.document_metadata = Some(input);
self
}
pub fn set_document_metadata(
mut self,
input: std::option::Option<crate::model::DocumentMetadata>,
) -> Self {
self.document_metadata = input;
self
}
pub fn expense_documents(
mut self,
input: impl Into<crate::model::ExpenseDocument>,
) -> Self {
let mut v = self.expense_documents.unwrap_or_default();
v.push(input.into());
self.expense_documents = Some(v);
self
}
pub fn set_expense_documents(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ExpenseDocument>>,
) -> Self {
self.expense_documents = input;
self
}
/// Consumes the builder and constructs a [`AnalyzeExpenseOutput`](crate::output::AnalyzeExpenseOutput)
pub fn build(self) -> crate::output::AnalyzeExpenseOutput {
crate::output::AnalyzeExpenseOutput {
document_metadata: self.document_metadata,
expense_documents: self.expense_documents,
}
}
}
}
impl AnalyzeExpenseOutput {
/// Creates a new builder-style object to manufacture [`AnalyzeExpenseOutput`](crate::output::AnalyzeExpenseOutput)
pub fn builder() -> crate::output::analyze_expense_output::Builder {
crate::output::analyze_expense_output::Builder::default()
}
}
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AnalyzeDocumentOutput {
/// <p>Metadata about the analyzed document. An example is the number of pages.</p>
pub document_metadata: std::option::Option<crate::model::DocumentMetadata>,
/// <p>The items that are detected and analyzed by <code>AnalyzeDocument</code>.</p>
pub blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
/// <p>Shows the results of the human in the loop evaluation.</p>
pub human_loop_activation_output: std::option::Option<crate::model::HumanLoopActivationOutput>,
/// <p>The version of the model used to analyze the document.</p>
pub analyze_document_model_version: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for AnalyzeDocumentOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AnalyzeDocumentOutput");
formatter.field("document_metadata", &self.document_metadata);
formatter.field("blocks", &self.blocks);
formatter.field(
"human_loop_activation_output",
&self.human_loop_activation_output,
);
formatter.field(
"analyze_document_model_version",
&self.analyze_document_model_version,
);
formatter.finish()
}
}
/// See [`AnalyzeDocumentOutput`](crate::output::AnalyzeDocumentOutput)
pub mod analyze_document_output {
/// A builder for [`AnalyzeDocumentOutput`](crate::output::AnalyzeDocumentOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) document_metadata: std::option::Option<crate::model::DocumentMetadata>,
pub(crate) blocks: std::option::Option<std::vec::Vec<crate::model::Block>>,
pub(crate) human_loop_activation_output:
std::option::Option<crate::model::HumanLoopActivationOutput>,
pub(crate) analyze_document_model_version: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Metadata about the analyzed document. An example is the number of pages.</p>
pub fn document_metadata(mut self, input: crate::model::DocumentMetadata) -> Self {
self.document_metadata = Some(input);
self
}
pub fn set_document_metadata(
mut self,
input: std::option::Option<crate::model::DocumentMetadata>,
) -> Self {
self.document_metadata = input;
self
}
pub fn blocks(mut self, input: impl Into<crate::model::Block>) -> Self {
let mut v = self.blocks.unwrap_or_default();
v.push(input.into());
self.blocks = Some(v);
self
}
pub fn set_blocks(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Block>>,
) -> Self {
self.blocks = input;
self
}
/// <p>Shows the results of the human in the loop evaluation.</p>
pub fn human_loop_activation_output(
mut self,
input: crate::model::HumanLoopActivationOutput,
) -> Self {
self.human_loop_activation_output = Some(input);
self
}
pub fn set_human_loop_activation_output(
mut self,
input: std::option::Option<crate::model::HumanLoopActivationOutput>,
) -> Self {
self.human_loop_activation_output = input;
self
}
/// <p>The version of the model used to analyze the document.</p>
pub fn analyze_document_model_version(
mut self,
input: impl Into<std::string::String>,
) -> Self {
self.analyze_document_model_version = Some(input.into());
self
}
pub fn set_analyze_document_model_version(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.analyze_document_model_version = input;
self
}
/// Consumes the builder and constructs a [`AnalyzeDocumentOutput`](crate::output::AnalyzeDocumentOutput)
pub fn build(self) -> crate::output::AnalyzeDocumentOutput {
crate::output::AnalyzeDocumentOutput {
document_metadata: self.document_metadata,
blocks: self.blocks,
human_loop_activation_output: self.human_loop_activation_output,
analyze_document_model_version: self.analyze_document_model_version,
}
}
}
}
impl AnalyzeDocumentOutput {
/// Creates a new builder-style object to manufacture [`AnalyzeDocumentOutput`](crate::output::AnalyzeDocumentOutput)
pub fn builder() -> crate::output::analyze_document_output::Builder {
crate::output::analyze_document_output::Builder::default()
}
}
| set_document_metadata |
transaction.py | # coding:utf-8
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, Float, DateTime
# 创建对象的基类:
Base = declarative_base()
class lianjia_transaction(Base):
# 表的名字:
__tablename__ = 'lianjia_transaction'
# 表的结构:
id = Column(Integer, primary_key=True)
transactiondate = Column(DateTime)
price = Column(Float)
avgPrice = Column(Float)
ljID = Column(Float)
address = Column(String(255))
address1 = Column(String(15))
address2 = Column(String(15)) | address7 = Column(String(15))
address8 = Column(String(15))
address9 = Column(String(15))
address10 = Column(String(15))
url=Column(String(500))
def __init__(self, data):
for key in data.keys():
if key == 'id':
self.id = data[key]
if key == 'transactiondate':
self.transactiondate = data[key]
if key == 'price':
self.price = data[key]
if key == 'avgPrice':
self.avgPrice = data[key]
if key == 'ljID':
self.ljID = data[key]
if key == 'address':
self.address = data[key]
if key == 'address1':
self.address1 = data[key]
if key == 'address2':
self.address2 = data[key]
if key == 'address3':
self.address3 = data[key]
if key == 'address4':
self.address4 = data[key]
if key == 'address5':
self.address5 = data[key]
if key == 'address6':
self.address6 = data[key]
if key == 'address7':
self.address7 = data[key]
if key == 'address8':
self.address8 = data[key]
if key == 'address9':
self.address9 = data[key]
if key == 'address10':
self.address10 = data[key]
if key == 'url':
self.url = data[key] | address3 = Column(String(15))
address4 = Column(String(15))
address5 = Column(String(15))
address6 = Column(String(15)) |
qrCodeScanner.js | /******/ (() => { // webpackBootstrap
/*!***************************************!*\
!*** ./resources/js/qrCodeScanner.js ***!
\***************************************/
var qrcode = window.qrcode;
var axentix = window.Axentix;
var video = document.createElement("video");
var canvasElement = document.getElementById("qr-canvas");
var canvas = canvasElement.getContext("2d");
var qrResult = document.getElementById("qr-result");
var outputData = document.getElementById("outputData");
var btnScanQR = document.getElementById("btn-scan-qr");
var btnStopQR = document.getElementById("btn-stop-qr");
var qrCodeResult = document.getElementById("qr-code-result");
var scanning = false;
qrcode.callback = function (res) {
if (res) {
outputData.innerText = res;
qrCodeResult.value = res;
console.log('Axentix', axentix);
axentix.updateInputs();
scanning = false;
btnScanQR.classList.remove("hide");
btnStopQR.classList.add("hide");
video.srcObject.getTracks().forEach(function (track) {
track.stop();
});
qrResult.hidden = false;
canvasElement.hidden = true;
btnScanQR.hidden = false;
}
};
btnScanQR.onclick = function () {
btnScanQR.classList.add("hide");
btnStopQR.classList.remove("hide");
navigator.mediaDevices.getUserMedia({
video: {
facingMode: "environment"
}
}).then(function (stream) {
scanning = true;
qrResult.hidden = true;
btnScanQR.hidden = true;
canvasElement.hidden = false;
video.setAttribute("playsinline", true);
video.srcObject = stream;
video.play();
tick();
scan();
});
};
btnStopQR.onclick = function () {
scanning = false;
video.srcObject.getTracks().forEach(function (track) {
track.stop();
});
qrResult.hidden = true;
canvasElement.hidden = true;
btnScanQR.classList.remove("hide");
btnStopQR.classList.add("hide");
};
function | () {
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
scanning && requestAnimationFrame(tick);
}
function scan() {
try {
qrcode.decode();
} catch (e) {
setTimeout(scan, 200);
}
}
/******/ })()
; | tick |
index.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core = require("@actions/core");
const AWS = require("aws-sdk");
const format_1 = require("./format");
const fs_1 = require("fs");
async function | () {
const region = process.env.AWS_DEFAULT_REGION;
const ssm = new AWS.SSM({ region });
try {
const ssmPath = core.getInput('ssm-path', { required: true });
const format = core.getInput('format', { required: true });
const output = core.getInput('output', { required: true });
const append = core.getInput('append');
const prefix = core.getInput('prefix');
const allParameters = [];
const withDecryption = core.getInput('decryption') === 'true';
let nextToken;
try {
do {
const result = await ssm
.getParametersByPath({
WithDecryption: withDecryption,
Path: ssmPath,
Recursive: true,
NextToken: nextToken,
})
.promise();
core.debug(`parameters length: ${result.Parameters.length}`);
nextToken = result.NextToken;
allParameters.push(...result.Parameters);
} while (nextToken);
const envs = allParameters
.map(p => ({
Value: p.Value,
Name: p.Name.split('/').pop(),
}))
.map(format_1.formatter(format)(prefix));
if (envs.length > 0) {
envs.push('\n');
}
if (fs_1.existsSync(output) && append) {
console.log(`append to ${output} file`);
fs_1.appendFileSync(output, '\n' + envs.join('\n'));
}
else {
console.log(`create ${output} file`);
fs_1.writeFileSync(output, envs.join('\n'));
}
}
catch (e) {
core.error(e);
core.setFailed(e.message);
}
}
catch (e) {
core.setFailed(e.message);
}
}
run();
| run |
listener.go | /*
Copyright AppsCode Inc. and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1alpha1
import (
"context"
"time"
v1alpha1 "kubeform.dev/provider-oci-api/apis/loadbalancer/v1alpha1"
scheme "kubeform.dev/provider-oci-api/client/clientset/versioned/scheme"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
)
// ListenersGetter has a method to return a ListenerInterface.
// A group's client should implement this interface.
type ListenersGetter interface {
Listeners(namespace string) ListenerInterface
}
// ListenerInterface has methods to work with Listener resources.
type ListenerInterface interface {
Create(ctx context.Context, listener *v1alpha1.Listener, opts v1.CreateOptions) (*v1alpha1.Listener, error)
Update(ctx context.Context, listener *v1alpha1.Listener, opts v1.UpdateOptions) (*v1alpha1.Listener, error)
UpdateStatus(ctx context.Context, listener *v1alpha1.Listener, opts v1.UpdateOptions) (*v1alpha1.Listener, error)
Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Listener, error)
List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.ListenerList, error)
Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Listener, err error)
ListenerExpansion
}
// listeners implements ListenerInterface
type listeners struct {
client rest.Interface
ns string
}
// newListeners returns a Listeners
func newListeners(c *LoadbalancerV1alpha1Client, namespace string) *listeners {
return &listeners{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the listener, and returns the corresponding listener object, and an error if there is any.
func (c *listeners) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Listener, err error) {
result = &v1alpha1.Listener{}
err = c.client.Get().
Namespace(c.ns).
Resource("listeners").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of Listeners that match those selectors.
func (c *listeners) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ListenerList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil |
result = &v1alpha1.ListenerList{}
err = c.client.Get().
Namespace(c.ns).
Resource("listeners").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested listeners.
func (c *listeners) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("listeners").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a listener and creates it. Returns the server's representation of the listener, and an error, if there is any.
func (c *listeners) Create(ctx context.Context, listener *v1alpha1.Listener, opts v1.CreateOptions) (result *v1alpha1.Listener, err error) {
result = &v1alpha1.Listener{}
err = c.client.Post().
Namespace(c.ns).
Resource("listeners").
VersionedParams(&opts, scheme.ParameterCodec).
Body(listener).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a listener and updates it. Returns the server's representation of the listener, and an error, if there is any.
func (c *listeners) Update(ctx context.Context, listener *v1alpha1.Listener, opts v1.UpdateOptions) (result *v1alpha1.Listener, err error) {
result = &v1alpha1.Listener{}
err = c.client.Put().
Namespace(c.ns).
Resource("listeners").
Name(listener.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(listener).
Do(ctx).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *listeners) UpdateStatus(ctx context.Context, listener *v1alpha1.Listener, opts v1.UpdateOptions) (result *v1alpha1.Listener, err error) {
result = &v1alpha1.Listener{}
err = c.client.Put().
Namespace(c.ns).
Resource("listeners").
Name(listener.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(listener).
Do(ctx).
Into(result)
return
}
// Delete takes name of the listener and deletes it. Returns an error if one occurs.
func (c *listeners) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("listeners").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *listeners) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("listeners").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched listener.
func (c *listeners) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Listener, err error) {
result = &v1alpha1.Listener{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("listeners").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
| {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
} |
server.js | // Load the http module to create an http server.
var http = require('http');
var steem = require('steem');
var store = require('data-store')('my-app');
var sleep = require('sleep');
var tarot = require('./tarot.js');
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: process.env.cloud_name,
api_key: process.env.api_key,
api_secret: process.env.api_secret
});
// Create a function to handle every HTTP request
function handler(req, res){
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
//console.log('test',tarot.threeCardReading());
//res.end("<html><body><h1>Hello</h1></body></html>");
var r1 = "<html><body><h1>";
var r2 = "</h1></body></html>";
var r3 = tarot.threeCardReading();
var answer = r1+r2+r3;
res.end(answer);
};
//steem test
/*
steem.api.getState('@jeaimetu',function(err, result){
console.log(err, result);
});
|
//After writing, this needs cool down time to create the block chain
function writingReply(child_permlink,pAuthor){
var private_posting_wif = process.env.pass;
var parent_author = pAuthor;
//var parent_author = '';
var parent_permlink = child_permlink;
var json_metadata = '';
//check author have . then remove that
var parent_author_permlink = pAuthor;
var dotCheck = ".";
if(pAuthor.indexOf(dotCheck) != -1){
//replace .
var parent_author_permlink = pAuthor.replace(".","dot");
}
const permlink = steem.formatter.commentPermlink(parent_author_permlink, parent_permlink)
//const permlink = steem.formatter.commentPermlink('jeaimetu', parent_permlink)
var tarotResult = tarot.randomCard();
var i = tarotResult.indexOf("##: ");
var a = tarotResult.substr(i+4,tarotResult.length-1);
a.replace(/\s/g,'');
console.log("image name :", a,":");
var b = tarotResult.substr(0,i-1);
var content = '<table><tr><td> ';
//content += cloudinary.image("00_Fool.jpg", {alt : "Test"})
console.log(cloudinary.image(a, {alt : "Test"}));
//content += cloudinary.image(a, {alt : "Test"}, {width : 50})
content += cloudinary.image(a, {width : 100, height : 200, crop : 'fit' })
content += '</td><td><p><strong>안녕하세요. 타로점 결과 입니다. 많이 사용해 주세요.</strong></p><hr><p>';
//content += tarot.randomCard();
b = b.replace("/","/\n");
content += b;
content += '</td></tr></table>';
steem.broadcast.comment (
private_posting_wif, // Steemit.com Wallet -> Permissions -> Show Private Key (for Posting)
parent_author, // empty for new blog post
parent_permlink, // main tag for new blog post
'jeaimetu', // same user the private_posting_key is for
permlink, // a slug (lowercase 'a'-'z', '0'-'9', and '-', min 1 character, max 255 characters)
'', // human-readable title
content, // body of the post or comment
json_metadata, // arbitrary metadata
function (err, result){
if(err)
console.log('Failure', err);
else
console.log('Success');
}
);
}
function checkReplies() {
steem.api.getContentReplies('jeaimetu', process.env.link, function(err, result){
//console.log(err, result);
result.forEach((num, idx)=> {
//sleep.sleep(21); //do not work what I intended
console.log(num.body);
if(num.children == 0){
var string = "타로";
if(num.body.indexOf(string) != -1){
console.log('I will make reply for this');
console.log('call writingReply for ', idx);
writingReply(num.permlink, num.author);
}
}
});
});
}
// according to steemit github
// https://github.com/steemit/steem/blob/master/libraries/protocol/include/steemit/protocol/config.hpp
// #define STEEMIT_MIN_REPLY_INTERVAL (fc::seconds(20)) // 20 seconds
// So I safely add 60secs interval consider delay time.
setInterval(checkReplies, 25000);
async function getFullAccountHistory(){
const end = 9999 * 5;
const step = 9999;
for(let start = 99999999;start >= step;start -= step){
result = await steem.api.getAccountHistoryAsync("jeaimetu", start, step);
console.log(result);
}
return result;
}
steem.api.getAccountHistory('jeaimetu',1,1,(err, result) => {
console.log("1 1 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',2,1,(err, result) => {
console.log("2 1 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',3,1,(err, result) => {
console.log("3 1 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',2,2,(err, result) => {
console.log("2 2 test");
console.log(result[0][0]);
console.log(result[0][1]);
console.log(result);
});
steem.api.getAccountHistory('jeaimetu',-1,0, (err, result) => {
limit = result[0][0];
console.log("Limit :", limit);
});
/*
getFullAccountHistory().then(v => {
console.log(v);
});
*/
/* ToDo
1. get more than 9999 records
2. extract number from "x.xxx STEEM" and convert it to number
*/
//do {
/*
async function getFullAccountHistory(){
const end = 9999 * 10;
const step = 9999;
var amount = 0;
for(let start = 0; start < end;start += step) {
await steem.api.getAccountHistoryAsync('jeaimetu', start, step).each((history: any[]) => {
const result = history;
}
//console.log(err, result);
const WALLET_FILTER = 'transfer'
let transfers = result.filter( tx => tx[1].op[0] === WALLET_FILTER )
//console.log(transfers)
transfers.forEach((tx) => {
if(tx[1].op[1].from == "upbit-exchange" || tx[1].op[1].from == "korbit2" || tx[1].op[1].from == "gopax"){
console.log(tx[1].op[0], tx[1].op[1].from, tx[1].op[1].amount)
let money = tx[1].op[1].amount.split(" ");
amount += parseInt(money[0],10);}
}
console.log("total amount from exchange", amount);
if(result.length < 1)
return;
});
} //end of for
//} while(result.length != 0)
} //end of async function
*/
//did not return all images. This may depends on the folder
//cloudinary.v2.api.resources(function(error, result){console.log(result)});
//did not return nothing
//cloudinary.v2.api.resources({type: 'upload'}, function(error, result){});
cloudinary.v2.search.expression("*00_Fool.jpg").execute(function(error, result) {
console.log("cloudinary fool search");
console.log(result)});
//getFullAccountHistory();
/* data store test
store.set('a','test string');
console.log(store.get('a'));
*/
/*
//writing reply
var private_posting_wif = process.env.pass;
var parent_author = 'jeaimetu';
var parent_permlink = 're-jeaimetu-6c1klq-stereotype-20180317t185909244z';
var json_metadata = '';
const permlink = steem.formatter.commentPermlink(parent_author, parent_permlink)
steem.broadcast.comment (
private_posting_wif, // Steemit.com Wallet -> Permissions -> Show Private Key (for Posting)
'jeaimetu', // empty for new blog post
parent_permlink, // main tag for new blog post
'jeaimetu', // same user the private_posting_key is for
permlink, // a slug (lowercase 'a'-'z', '0'-'9', and '-', min 1 character, max 255 characters)
'', // human-readable title
'Posting test through api', // body of the post or comment
json_metadata // arbitrary metadata
)
console.log('getContet test');
steem.api.getContent('jeaimetu','2-happenchange-investing-chapter-2',function(err, result){
console.log(err, result);
console.log(result.active_votes[0].voters);
});
*/
/*
console.log('getActiveVotes test');
var res;
var res_formatted = '';;
var pLink = process.env.link;
steem.api.getActiveVotes('jeaimetu',pLink, function(err, result) {
console.log(err, result);
console.log('for each test');
res = result;
res.forEach((num, index) => {
console.log(num.voter);
res_formatted += '\@';
res_formatted += num.voter;
res_formatted += '\,';
});
console.log(res_formatted);
});
*/
/* this get all replies, so does not work for me */
/*
console.log('reply retrieve test');
steem.api.getRepliesByLastUpdate('jeaimetu', 're-jeaimetu-6c1klq-stereotype-20180317t185909244z', 10, function(err, result) {
console.log(err, result);
});
*/
/*
*/
/* this only get main post except replies */
/*
console.log('getDiscussionsByAuthorBeforeDate test');
steem.api.getDiscussionsByAuthorBeforeDate('jeaimetu', '6c1klq-stereotype', "2018-03-18T11:55:18", 10, function(err, result) {
console.log(err, result);
});
*/
// Create a server that invokes the `handler` function upon receiving a request
http.createServer(handler).listen(process.env.PORT, function(err){
if(err){
console.log('Error starting http server');
} else {
console.log("Server running at http://127.0.0.1:8000/ or http://localhost:8000/");
};
}); | */ |
TimeManager.py | from direct.showbase.DirectObject import *
from pandac.PandaModules import *
from direct.task import Task
from direct.distributed import DistributedObject
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.ClockDelta import globalClockDelta
class TimeManager(DistributedObject.DistributedObject):
"""
This DistributedObject lives on the AI and on the client side, and
serves to synchronize the time between them so they both agree, to
within a few hundred milliseconds at least, what time it is.
It uses a pull model where the client can request a
synchronization check from time to time. It also employs a
round-trip measurement to minimize the effect of latency.
"""
notify = DirectNotifyGlobal.directNotify.newCategory("TimeManager")
# The number of seconds to wait between automatic
# synchronizations. Set to 0 to disable auto sync after
# startup.
updateFreq = ConfigVariableDouble('time-manager-freq', 1800).getValue()
# The minimum number of seconds to wait between two unrelated
# synchronization attempts. Increasing this number cuts down
# on frivolous synchronizations.
minWait = ConfigVariableDouble('time-manager-min-wait', 10).getValue()
# The maximum number of seconds of uncertainty to tolerate in
# the clock delta without trying again.
maxUncertainty = ConfigVariableDouble('time-manager-max-uncertainty', 1).getValue()
# The maximum number of attempts to try to get a low-latency
# time measurement before giving up and accepting whatever we
# get.
maxAttempts = ConfigVariableInt('time-manager-max-attempts', 5).getValue()
# A simulated clock skew for debugging, in seconds.
extraSkew = ConfigVariableInt('time-manager-extra-skew', 0).getValue()
if extraSkew != 0:
notify.info("Simulating clock skew of %0.3f s" % extraSkew)
reportFrameRateInterval = ConfigVariableDouble('report-frame-rate-interval', 300.0).getValue()
| self.thisContext = -1
self.nextContext = 0
self.attemptCount = 0
self.start = 0
self.lastAttempt = -self.minWait*2
### DistributedObject methods ###
def generate(self):
"""
This method is called when the DistributedObject is reintroduced
to the world, either for the first time or from the cache.
"""
DistributedObject.DistributedObject.generate(self)
self.accept('clock_error', self.handleClockError)
if self.updateFreq > 0:
self.startTask()
def announceGenerate(self):
DistributedObject.DistributedObject.announceGenerate(self)
self.cr.timeManager = self
self.synchronize("TimeManager.announceGenerate")
def disable(self):
"""
This method is called when the DistributedObject is removed from
active duty and stored in a cache.
"""
self.ignore('clock_error')
self.stopTask()
taskMgr.remove('frameRateMonitor')
if self.cr.timeManager is self:
self.cr.timeManager = None
DistributedObject.DistributedObject.disable(self)
def delete(self):
"""
This method is called when the DistributedObject is permanently
removed from the world and deleted from the cache.
"""
DistributedObject.DistributedObject.delete(self)
### Task management methods ###
def startTask(self):
self.stopTask()
taskMgr.doMethodLater(self.updateFreq, self.doUpdate, "timeMgrTask")
def stopTask(self):
taskMgr.remove("timeMgrTask")
def doUpdate(self, task):
self.synchronize("timer")
# Spawn the next one
taskMgr.doMethodLater(self.updateFreq, self.doUpdate, "timeMgrTask")
return Task.done
### Automatic clock error handling ###
def handleClockError(self):
self.synchronize("clock error")
### Synchronization methods ###
def synchronize(self, description):
"""synchronize(self, string description)
Call this function from time to time to synchronize watches
with the server. This initiates a round-trip transaction;
when the transaction completes, the time will be synced.
The description is the string that will be written to the log
file regarding the reason for this synchronization attempt.
The return value is true if the attempt is made, or false if
it is too soon since the last attempt.
"""
now = globalClock.getRealTime()
if now - self.lastAttempt < self.minWait:
self.notify.debug("Not resyncing (too soon): %s" % (description))
return 0
self.talkResult = 0
self.thisContext = self.nextContext
self.attemptCount = 0
self.nextContext = (self.nextContext + 1) & 255
self.notify.info("Clock sync: %s" % (description))
self.start = now
self.lastAttempt = now
self.sendUpdate("requestServerTime", [self.thisContext])
return 1
def serverTime(self, context, timestamp):
"""serverTime(self, int8 context, int32 timestamp)
This message is sent from the AI to the client in response to
a previous requestServerTime. It contains the time as
observed by the AI.
The client should use this, in conjunction with the time
measurement taken before calling requestServerTime (above), to
determine the clock delta between the AI and the client
machines.
"""
end = globalClock.getRealTime()
if context != self.thisContext:
self.notify.info("Ignoring TimeManager response for old context %d" % (context))
return
elapsed = end - self.start
self.attemptCount += 1
self.notify.info("Clock sync roundtrip took %0.3f ms" % (elapsed * 1000.0))
average = (self.start + end) / 2.0 - self.extraSkew
uncertainty = (end - self.start) / 2.0 + abs(self.extraSkew)
globalClockDelta.resynchronize(average, timestamp, uncertainty)
self.notify.info("Local clock uncertainty +/- %.3f s" % (globalClockDelta.getUncertainty()))
if globalClockDelta.getUncertainty() > self.maxUncertainty:
if self.attemptCount < self.maxAttempts:
self.notify.info("Uncertainty is too high, trying again.")
self.start = globalClock.getRealTime()
self.sendUpdate("requestServerTime", [self.thisContext])
return
self.notify.info("Giving up on uncertainty requirement.")
messenger.send("gotTimeSync", taskChain = 'default')
messenger.send(self.cr.uniqueName("gotTimeSync"), taskChain = 'default') | def __init__(self, cr):
DistributedObject.DistributedObject.__init__(self, cr)
|
root.go | // Copyright © 2017 Thomas Heslin <[email protected]>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
// NewRootCmd creates the main CLI command
func NewRootCmd(version string) (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "GoCLI",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) {
// fmt.Println("Welcome to GoCLI!")
// },
}
cmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.GoCLI.yaml)")
cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
cmd.AddCommand(NewVersionCmd(version))
cmd.AddCommand(NewInfoCmd())
return cmd, nil
}
func i | ) {
cobra.OnInitialize(initConfig)
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".GoCLI" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".GoCLI")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
| nit( |
user.schema.d.ts | import * as mongoose from 'mongoose';
import { Meme } from 'src/meme/schema/meme.schema';
export declare type UserDocument = User & mongoose.Document;
export declare class User {
_id: string;
username: string;
email: string;
password: string; | favourites: Meme[];
likes: Meme[];
unlikes: Meme[];
}
export declare const UserSchema: mongoose.Schema<mongoose.Document<User, any, any>, mongoose.Model<mongoose.Document<User, any, any>, any, any>, {}>; | uploadedMemes: Meme[]; |
extends.go | package baidupcs
import (
"crypto/md5"
"encoding/hex"
"errors"
"github.com/qjfoidnh/BaiduPCS-Go/baidupcs/pcserror"
"github.com/qjfoidnh/BaiduPCS-Go/pcsutil/cachepool"
"github.com/qjfoidnh/BaiduPCS-Go/pcsutil/escaper"
"github.com/qjfoidnh/BaiduPCS-Go/requester/downloader"
"io"
"mime"
"net/http"
"path"
"strconv"
"strings"
)
const (
// ShellPatternCharacters 通配符字符串
ShellPatternCharacters = "*?[]"
)
var (
// ErrFixMD5Isdir 目录不需要修复md5
ErrFixMD5Isdir = errors.New("directory not support fix md5")
// ErrFixMD5Failed 修复MD5失败, 可能服务器未刷新
ErrFixMD5Failed = errors.New("fix md5 failed")
// ErrFixMD5FileInfoNil 文件信息对象为空
ErrFixMD5FileInfoNil = errors.New("file info is nil")
// ErrMatchPathByShellPatternNotAbsPath 不是绝对路径
ErrMatchPathByShellPatternNotAbsPath = errors.New("not absolute path")
ErrContentRangeNotFound = errors.New("Content-Range not found")
ErrGetRapidUploadInfoLengthNotFound = errors.New("Content-Length not found")
ErrGetRapidUploadInfoMD5NotFound = errors.New("Content-MD5 not found")
ErrGetRapidUploadInfoCrc32NotFound = errors.New("x-bs-meta-crc32 not found")
ErrGetRapidUploadInfoFilenameNotEqual = errors.New("文件名不匹配")
ErrGetRapidUploadInfoLengthNotEqual = errors.New("Content-Length 不匹配")
ErrGetRapidUploadInfoMD5NotEqual = errors.New("Content-MD5 不匹配")
ErrGetRapidUploadInfoCrc32NotEqual = errors.New("x-bs-meta-crc32 不匹配")
ErrGetRapidUploadInfoSliceMD5NotEqual = errors.New("slice-md5 不匹配")
ErrFileTooLarge = errors.New("文件大于20GB, 无法秒传")
)
func (pcs *BaiduPCS) getLocateDownloadLink(pcspath string) (link string, pcsError pcserror.Error) {
info, pcsError := pcs.LocateDownload(pcspath)
if pcsError != nil {
return
}
u := info.SingleURL(pcs.isHTTPS)
if u == nil {
return "", &pcserror.PCSErrInfo{
Operation: OperationLocateDownload,
ErrType: pcserror.ErrTypeOthers,
Err: ErrLocateDownloadURLNotFound,
}
}
return u.String(), nil
}
// ExportByFileInfo 通过文件信息对象, 导出文件信息
func (pcs *BaiduPCS) ExportByFileInfo(finfo *FileDirectory) (rinfo *RapidUploadInfo, pcsError pcserror.Error) {
errInfo := pcserror.NewPCSErrorInfo(OperationExportFileInfo)
errInfo.ErrType = pcserror.ErrTypeOthers
if finfo.Size > MaxRapidUploadSize {
errInfo.Err = ErrFileTooLarge
return nil, errInfo
}
rinfo, pcsError = pcs.GetRapidUploadInfoByFileInfo(finfo)
if pcsError != nil {
return nil, pcsError
}
if rinfo.Filename != finfo.Filename {
baiduPCSVerbose.Infof("%s filename not equal, local: %s, remote link: %s\n", OperationExportFileInfo, finfo.Filename, rinfo.Filename)
rinfo.Filename = finfo.Filename
}
return rinfo, nil
}
// GetRapidUploadInfoByFileInfo 通过文件信息对象, 获取秒传信息
func (pcs *BaiduPCS) GetRapidUploadInfoByFileInfo(finfo *FileDirectory) (rinfo *RapidUploadInfo, pcsError pcserror.Error) {
if finfo.Size <= SliceMD5Size && len(finfo.BlockList) == 1 && finfo.BlockList[0] == finfo.MD5 {
// 可直接秒传
return &RapidUploadInfo{
Filename: finfo.Filename,
ContentLength: finfo.Size,
ContentMD5: finfo.MD5,
SliceMD5: finfo.MD5,
ContentCrc32: "0",
}, nil
}
link, pcsError := pcs.getLocateDownloadLink(finfo.Path)
if pcsError != nil {
return nil, pcsError
}
// 只有ContentLength可以比较
// finfo记录的ContentMD5不一定是正确的
// finfo记录的Filename不一定与获取到的一致
return pcs.GetRapidUploadInfoByLink(link, &RapidUploadInfo{
ContentLength: finfo.Size,
})
}
// GetRapidUploadInfoByLink 通过下载链接, 获取文件秒传信息
func (pcs *BaiduPCS) GetRapidUploadInfoByLink(link string, compareRInfo *RapidUploadInfo) (rinfo *RapidUploadInfo, pcsError pcserror.Error) {
errInfo := pcserror.NewPCSErrorInfo(OperationGetRapidUploadInfo)
errInfo.ErrType = pcserror.ErrTypeOthers
var (
header = pcs.getPanUAHeader()
isSetRange = compareRInfo != nil && compareRInfo.ContentLength > SliceMD5Size // 是否设置Range
)
if isSetRange {
header["Range"] = "bytes=0-" + strconv.FormatInt(SliceMD5Size-1, 10)
}
resp, err := pcs.client.Req(http.MethodGet, link, nil, header)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
errInfo.SetNetError(err)
return nil, errInfo
}
// 检测响应状态码
if resp.StatusCode/100 != 2 {
errInfo.SetNetError(errors.New(resp.Status))
return nil, errInfo
}
// 检测是否存在MD5
md5Str := resp.Header.Get("Content-MD5")
if md5Str == "" { // 未找到md5值, 可能是服务器未刷新
errInfo.Err = ErrGetRapidUploadInfoMD5NotFound
return nil, errInfo
}
if compareRInfo != nil && compareRInfo.ContentMD5 != "" && compareRInfo.ContentMD5 != md5Str {
errInfo.Err = ErrGetRapidUploadInfoMD5NotEqual
return nil, errInfo
}
// 获取文件名
_, params, err := mime.ParseMediaType(resp.Header.Get("Content-Disposition"))
if err != nil {
errInfo.Err = err
return nil, errInfo
}
filename := params["filename"]
if compareRInfo != nil && compareRInfo.Filename != "" && compareRInfo.Filename != filename {
errInfo.Err = ErrGetRapidUploadInfoFilenameNotEqual
return nil, errInfo
}
var (
contentLength int64
)
if isSetRange {
// 检测Content-Range
contentRange := resp.Header.Get("Content-Range")
if contentRange == "" {
errInfo.Err = ErrContentRangeNotFound
return nil, errInfo
}
contentLength = downloader.ParseContentRange(contentRange)
} else {
contentLength = resp.ContentLength
}
// 检测Content-Length
switch contentLength {
case -1:
errInfo.Err = ErrGetRapidUploadInfoLengthNotFound
return nil, errInfo
case 0:
return &RapidUploadInfo{
Filename: filename,
ContentLength: contentLength,
ContentMD5: EmptyContentMD5,
SliceMD5: EmptyContentMD5,
ContentCrc32: "0",
}, nil
default:
if compareRInfo != nil && compareRInfo.ContentLength > 0 && compareRInfo.ContentLength != contentLength {
errInfo.Err = ErrGetRapidUploadInfoLengthNotEqual
return nil, errInfo
}
}
// 检测是否存在crc32 值, 一般都会存在的
crc32Str := resp.Header.Get("x-bs-meta-crc32")
if crc32Str == "" || crc32Str == "0" {
errInfo.Err = ErrGetRapidUploadInfoCrc32NotFound
return nil, errInfo
}
if compareRInfo != nil && compareRInfo.ContentCrc32 != "" && compareRInfo.ContentCrc32 != crc32Str {
errInfo.Err = ErrGetRapidUploadInfoCrc32NotEqual
return nil, errInfo
}
// 获取slice-md5
// 忽略比较slice-md5
if contentLength <= SliceMD5Size {
return &RapidUploadInfo{
Filename: filename,
ContentLength: contentLength,
ContentMD5: md5Str,
SliceMD5: md5Str,
ContentCrc32: crc32Str,
}, nil
}
buf := cachepool.RawMallocByteSlice(int(SliceMD5Size)) | }
// 计算slice-md5
m := md5.New()
_, err = m.Write(buf)
if err != nil {
panic(err)
}
sliceMD5Str := hex.EncodeToString(m.Sum(nil))
// 检测slice-md5, 不必要的
if compareRInfo != nil && compareRInfo.SliceMD5 != "" && compareRInfo.SliceMD5 != sliceMD5Str {
errInfo.Err = ErrGetRapidUploadInfoSliceMD5NotEqual
return nil, errInfo
}
return &RapidUploadInfo{
Filename: filename,
ContentLength: contentLength,
ContentMD5: md5Str,
SliceMD5: sliceMD5Str,
ContentCrc32: crc32Str,
}, nil
}
// FixMD5ByFileInfo 尝试修复文件的md5, 通过文件信息对象
func (pcs *BaiduPCS) FixMD5ByFileInfo(finfo *FileDirectory) (pcsError pcserror.Error) {
errInfo := pcserror.NewPCSErrorInfo(OperationFixMD5)
errInfo.ErrType = pcserror.ErrTypeOthers
if finfo == nil {
errInfo.Err = ErrFixMD5FileInfoNil
return errInfo
}
if finfo.Size > MaxRapidUploadSize { // 文件大于20GB
errInfo.Err = ErrFileTooLarge
return errInfo
}
// 忽略目录
if finfo.Isdir {
errInfo.Err = ErrFixMD5Isdir
return errInfo
}
if len(finfo.BlockList) == 1 && finfo.BlockList[0] == finfo.MD5 {
// 不需要修复
return nil
}
link, pcsError := pcs.getLocateDownloadLink(finfo.Path)
if pcsError != nil {
return pcsError
}
var (
cmpInfo = &RapidUploadInfo{
Filename: finfo.Filename,
ContentLength: finfo.Size,
}
)
rinfo, pcsError := pcs.GetRapidUploadInfoByLink(link, cmpInfo)
if pcsError != nil {
switch pcsError.GetError() {
case ErrGetRapidUploadInfoMD5NotFound, ErrGetRapidUploadInfoCrc32NotFound:
errInfo.Err = ErrFixMD5Failed
default:
errInfo.Err = pcsError
}
return errInfo
}
// 开始修复
return pcs.RapidUploadNoCheckDir(finfo.Path, rinfo.ContentMD5, rinfo.SliceMD5, rinfo.ContentCrc32, rinfo.ContentLength)
}
// FixMD5 尝试修复文件的md5
func (pcs *BaiduPCS) FixMD5(pcspath string) (pcsError pcserror.Error) {
finfo, pcsError := pcs.FilesDirectoriesMeta(pcspath)
if pcsError != nil {
return
}
return pcs.FixMD5ByFileInfo(finfo)
}
func (pcs *BaiduPCS) recurseMatchPathByShellPattern(index int, patternSlice *[]string, ps *[]string, pcspaths *[]string) {
if index == len(*patternSlice) {
*pcspaths = append(*pcspaths, strings.Join(*ps, PathSeparator))
return
}
if !strings.ContainsAny((*patternSlice)[index], ShellPatternCharacters) {
(*ps)[index] = (*patternSlice)[index]
pcs.recurseMatchPathByShellPattern(index+1, patternSlice, ps, pcspaths)
return
}
fds, pcsError := pcs.FilesDirectoriesList(strings.Join((*ps)[:index], PathSeparator), DefaultOrderOptions)
if pcsError != nil {
panic(pcsError) // 抛出异常
}
for k := range fds {
if matched, _ := path.Match((*patternSlice)[index], fds[k].Filename); matched {
(*ps)[index] = fds[k].Filename
pcs.recurseMatchPathByShellPattern(index+1, patternSlice, ps, pcspaths)
}
}
return
}
// MatchPathByShellPattern 通配符匹配文件路径, pattern 为绝对路径
func (pcs *BaiduPCS) MatchPathByShellPattern(pattern string) (pcspaths []string, pcsError pcserror.Error) {
errInfo := pcserror.NewPCSErrorInfo(OperrationMatchPathByShellPattern)
errInfo.ErrType = pcserror.ErrTypeOthers
patternSlice := strings.Split(escaper.Escape(path.Clean(pattern), []rune{'['}), PathSeparator) // 转义中括号
if patternSlice[0] != "" {
errInfo.Err = ErrMatchPathByShellPatternNotAbsPath
return nil, errInfo
}
ps := make([]string, len(patternSlice))
defer func() { // 捕获异常
if err := recover(); err != nil {
pcspaths = nil
pcsError = err.(pcserror.Error)
}
}()
pcs.recurseMatchPathByShellPattern(1, &patternSlice, &ps, &pcspaths)
return pcspaths, nil
} | _, err = io.ReadFull(resp.Body, buf)
if err != nil {
errInfo.SetNetError(err)
return nil, errInfo |
JobAllowMultiCraftRequestMessage.ts | import Message from "@/protocol/network/messages/Message";
export default class | extends Message {
public enabled: boolean;
constructor(enabled = false) {
super();
this.enabled = enabled;
}
}
| JobAllowMultiCraftRequestMessage |
03_03_positional.rs | use clap::Parser;
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
struct | {
name: Option<String>,
}
fn main() {
let cli = Cli::parse();
println!("name: {:?}", cli.name.as_deref());
}
| Cli |
main.server.test.js | const request = require('supertest');
const { model, connection } = require('mongoose');
const { it, before, describe, afterEach } = require('mocha');
const User = model('User');
const { createUser } = require('@helpers/utils');
const express = require('@config/lib/express');
const { prefix } = require('@config/index');
let app;
const credentials = {
username: 'username',
password: 'jsI$Aw3$0m3',
};
let agent;
/** | before(async () => {
// Get application
app = await express.init(connection.db);
agent = request.agent(app);
});
describe('"modules:{{{lowercase name}}}" is up', () => {
it('I am not allowed to call the API if I do not have the IAM "modules:{{{lowercase name}}}:ok"', async () => {
await createUser(credentials, []);
await agent.post('/api/v1/auth/signin').send(credentials).expect(200);
await agent.get(`${prefix}/{{{lowercase name}}}/ok`).expect(403);
});
it('I am allowed to call the API if I have the IAM "modules:{{{lowercase name}}}:ok"', async () => {
await createUser(credentials, ['modules:{{{lowercase name}}}:ok']);
await agent.post('/api/v1/auth/signin').send(credentials).expect(200);
await agent.get(`${prefix}/{{{lowercase name}}}/ok`).expect(200);
});
});
afterEach(async () => {
await Promise.all([User.remove()]);
});
}); | * Sections tests
*/
describe('tests for module "modules:{{{lowercase name}}}"', () => { |
sys_control_always2d.ts | /**
* @module systems/sys_control_always2d
*/
import {Entity} from "../../common/world.js";
import {Game} from "../game.js";
import {Has} from "../world.js";
const QUERY = Has.ControlAlways2D | Has.Move2D;
export function | (game: Game, delta: number) {
for (let i = 0; i < game.World.Signature.length; i++) {
if ((game.World.Signature[i] & QUERY) === QUERY) {
update(game, i);
}
}
}
function update(game: Game, entity: Entity) {
let control = game.World.ControlAlways2D[entity];
let move = game.World.Move2D[entity];
if (control.Direction) {
move.Direction[0] = control.Direction[0];
move.Direction[1] = control.Direction[1];
game.World.Signature[entity] |= Has.Dirty;
}
if (control.Rotation) {
move.Rotation = control.Rotation;
game.World.Signature[entity] |= Has.Dirty;
}
}
| sys_control_always2d |
model_post_and_put_floating_ip_resp.go | package model
import (
"encoding/json"
"errors"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/converter"
"strings"
)
// floatingip对象
type PostAndPutFloatingIpResp struct {
// 关联端口的私有IP地址。
FixedIpAddress *string `json:"fixed_ip_address,omitempty"`
// 浮动IP地址。
FloatingIpAddress *string `json:"floating_ip_address,omitempty"`
// 外部网络的id。只能使用固定的外网,外部网络的信息请通过GET /v2.0/networks?router:external=True或GET /v2.0/networks?name={floating_network}或neutron net-external-list方式查询。
FloatingNetworkId *string `json:"floating_network_id,omitempty"`
// 浮动IP地址的id。
Id *string `json:"id,omitempty"`
// 端口id。
PortId *string `json:"port_id,omitempty"`
// 所属路由器id。
RouterId *string `json:"router_id,omitempty"`
// 网络状态,可以为ACTIVE, DOWN或ERROR。 DOWN:未绑定 ACTIVE:绑定 ERROR:异常
Status *PostAndPutFloatingIpRespStatus `json:"status,omitempty"`
// 项目id。
TenantId *string `json:"tenant_id,omitempty"`
// DNS名称(目前仅广州局点支持)
DnsName *string `json:"dns_name,omitempty"`
// DNS域地址(目前仅广州局点支持)
DnsDomain *string `json:"dns_domain,omitempty"`
}
func (o PostAndPutFloatingIpResp) String() string {
data, err := json.Marshal(o)
if err != nil {
return "PostAndPutFloatingIpResp struct{}"
}
return strings.Join([]string{"PostAndPutFloatingIpResp", string(data)}, " ")
}
type PostAndPutFloatingIpRespStatus struct {
value string
}
type PostAndPutFloatingIpRespS | spStatus
DOWN PostAndPutFloatingIpRespStatus
ERROR PostAndPutFloatingIpRespStatus
}
func GetPostAndPutFloatingIpRespStatusEnum() PostAndPutFloatingIpRespStatusEnum {
return PostAndPutFloatingIpRespStatusEnum{
ACTIVE: PostAndPutFloatingIpRespStatus{
value: "ACTIVE",
},
DOWN: PostAndPutFloatingIpRespStatus{
value: "DOWN",
},
ERROR: PostAndPutFloatingIpRespStatus{
value: "ERROR",
},
}
}
func (c PostAndPutFloatingIpRespStatus) MarshalJSON() ([]byte, error) {
return json.Marshal(c.value)
}
func (c *PostAndPutFloatingIpRespStatus) UnmarshalJSON(b []byte) error {
myConverter := converter.StringConverterFactory("string")
if myConverter != nil {
val, err := myConverter.CovertStringToInterface(strings.Trim(string(b[:]), "\""))
if err == nil {
c.value = val.(string)
return nil
}
return err
} else {
return errors.New("convert enum data to string error")
}
}
| tatusEnum struct {
ACTIVE PostAndPutFloatingIpRe |
types.py | #!/usr/bin/env python
"""Types-related part of GRR API client library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from typing import Any
from grr_api_client import errors
from grr_api_client import utils
from grr_response_proto import flows_pb2
class UnknownFlowName(errors.Error):
pass
class Types(object):
"""Object that helps users to deal with GRR type system."""
def __init__(self, context=None):
super(Types, self).__init__()
if not context:
raise ValueError("context can't be empty")
self._context = context
self._flow_descriptors = None
def CreateFlowRunnerArgs(self):
|
def CreateHuntRunnerArgs(self):
"""Creates hunt runner args object."""
return flows_pb2.HuntRunnerArgs()
# TODO: Delete this method as it is not really type-safe.
def CreateFlowArgs(self, flow_name=None) -> Any:
"""Creates flow arguments object for a flow with a given name."""
if not self._flow_descriptors:
self._flow_descriptors = {}
result = self._context.SendRequest("ListFlowDescriptors", None)
for item in result.items:
self._flow_descriptors[item.name] = item
try:
flow_descriptor = self._flow_descriptors[flow_name]
except KeyError:
raise UnknownFlowName(flow_name)
return utils.CopyProto(utils.UnpackAny(flow_descriptor.default_args))
def UnpackAny(self, proto_any):
"""Resolves the type and unpacks the given protobuf Any object."""
return utils.UnpackAny(proto_any)
| """Creates flow runner args object."""
return flows_pb2.FlowRunnerArgs() |
test_permissions.py | from django.contrib.auth.models import User
from pytest import mark
from rest_framework.test import APIClient
from rest_framework_api_key.models import APIKey
@mark.usefixtures("authorization_required")
def test_anonymous_client_cannot_access_api_without_api_key():
api_client = APIClient()
response = api_client.get("/v1/")
assert response.status_code == 403
@mark.usefixtures("no_authorization_required")
def test_anonymous_client_can_access_api_if_authorization_is_not_required():
api_client = APIClient()
response = api_client.get("/v1/")
assert response.status_code == 200
@mark.django_db
@mark.usefixtures("authorization_required")
def | ():
valid_api_key = APIKey.objects.create_key(name="test")[-1]
api_client = APIClient(HTTP_AUTHORIZATION=f"Api-Key {valid_api_key}")
response = api_client.get("/v1/")
assert response.status_code == 200
@mark.django_db
@mark.usefixtures("authorization_required")
def test_anonymous_client_cannot_access_api_with_revoked_api_key():
revoked_api_key = APIKey.objects.create_key(name="test", revoked=True)[-1]
api_client = APIClient(HTTP_AUTHORIZATION=f"Api-Key {revoked_api_key}")
response = api_client.get("/v1/")
assert response.status_code == 403
@mark.django_db
@mark.usefixtures("authorization_required")
def test_authenticated_client_can_access_api():
user = User.objects.create()
api_client = APIClient()
api_client.force_authenticate(user)
response = api_client.get("/v1/")
assert response.status_code == 200
| test_anonymous_client_can_access_api_with_valid_api_key |
task_run_cmd.go | package main
import (
"context"
"github.com/spf13/cobra"
. "github.com/yuuki0xff/clustertest/cmdutils"
"github.com/yuuki0xff/clustertest/models"
"github.com/yuuki0xff/clustertest/rpc"
"os"
)
func taskRunFn(cmd *cobra.Command, args []string) error {
c, err := rpc.NewClient()
if err != nil {
ShowError(err)
return nil
}
files, err := findConfigs(args)
if err != nil {
ShowError(err)
return nil
}
var ids []models.TaskID
for _, file := range files {
task, err := newTaskFromFile(file)
if err != nil {
ShowError(err)
return nil
}
id, err := c.Create(task)
if err != nil |
ids = append(ids, id)
}
for _, id := range ids {
err := c.Wait(id, context.Background())
if err != nil {
ShowError(err)
return nil
}
}
var render resultRender
if len(ids) > 1 {
render = &multipleResultRender{}
} else {
render = &singleResultRender{}
}
for _, id := range ids {
d, err := c.Inspect(id)
if err != nil {
ShowError(err)
return nil
}
render.Render(os.Stdout, d)
}
return nil
}
| {
ShowError(err)
return nil
} |
youtube-gen.go | // Package youtube provides access to the YouTube Data API.
//
// See https://developers.google.com/youtube/v3
//
// Usage example:
//
// import "google.golang.org/api/youtube/v3"
// ...
// youtubeService, err := youtube.New(oauthHttpClient)
package youtube // import "google.golang.org/api/youtube/v3"
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
context "golang.org/x/net/context"
ctxhttp "golang.org/x/net/context/ctxhttp"
gensupport "google.golang.org/api/gensupport"
googleapi "google.golang.org/api/googleapi"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = ctxhttp.Do
const apiId = "youtube:v3"
const apiName = "youtube"
const apiVersion = "v3"
const basePath = "https://www.googleapis.com/youtube/v3/"
// OAuth2 scopes used by this API.
const (
// Manage your YouTube account
YoutubeScope = "https://www.googleapis.com/auth/youtube"
// Manage your YouTube account
YoutubeForceSslScope = "https://www.googleapis.com/auth/youtube.force-ssl"
// View your YouTube account
YoutubeReadonlyScope = "https://www.googleapis.com/auth/youtube.readonly"
// Manage your YouTube videos
YoutubeUploadScope = "https://www.googleapis.com/auth/youtube.upload"
// View and manage your assets and associated content on YouTube
YoutubepartnerScope = "https://www.googleapis.com/auth/youtubepartner"
// View private information of your YouTube channel relevant during the
// audit process with a YouTube partner
YoutubepartnerChannelAuditScope = "https://www.googleapis.com/auth/youtubepartner-channel-audit"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Activities = NewActivitiesService(s)
s.Captions = NewCaptionsService(s)
s.ChannelBanners = NewChannelBannersService(s)
s.ChannelSections = NewChannelSectionsService(s)
s.Channels = NewChannelsService(s)
s.CommentThreads = NewCommentThreadsService(s)
s.Comments = NewCommentsService(s)
s.GuideCategories = NewGuideCategoriesService(s)
s.I18nLanguages = NewI18nLanguagesService(s)
s.I18nRegions = NewI18nRegionsService(s)
s.LiveBroadcasts = NewLiveBroadcastsService(s)
s.LiveChatBans = NewLiveChatBansService(s)
s.LiveChatMessages = NewLiveChatMessagesService(s)
s.LiveChatModerators = NewLiveChatModeratorsService(s)
s.LiveStreams = NewLiveStreamsService(s)
s.PlaylistItems = NewPlaylistItemsService(s)
s.Playlists = NewPlaylistsService(s)
s.Search = NewSearchService(s)
s.Sponsors = NewSponsorsService(s)
s.Subscriptions = NewSubscriptionsService(s)
s.SuperChatEvents = NewSuperChatEventsService(s)
s.Thumbnails = NewThumbnailsService(s)
s.VideoAbuseReportReasons = NewVideoAbuseReportReasonsService(s)
s.VideoCategories = NewVideoCategoriesService(s)
s.Videos = NewVideosService(s)
s.Watermarks = NewWatermarksService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Activities *ActivitiesService
Captions *CaptionsService
ChannelBanners *ChannelBannersService
ChannelSections *ChannelSectionsService
Channels *ChannelsService
CommentThreads *CommentThreadsService
Comments *CommentsService
GuideCategories *GuideCategoriesService
I18nLanguages *I18nLanguagesService
I18nRegions *I18nRegionsService
LiveBroadcasts *LiveBroadcastsService
LiveChatBans *LiveChatBansService
LiveChatMessages *LiveChatMessagesService
LiveChatModerators *LiveChatModeratorsService
LiveStreams *LiveStreamsService
PlaylistItems *PlaylistItemsService
Playlists *PlaylistsService
Search *SearchService
Sponsors *SponsorsService
Subscriptions *SubscriptionsService
SuperChatEvents *SuperChatEventsService
Thumbnails *ThumbnailsService
VideoAbuseReportReasons *VideoAbuseReportReasonsService
VideoCategories *VideoCategoriesService
Videos *VideosService
Watermarks *WatermarksService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewActivitiesService(s *Service) *ActivitiesService {
rs := &ActivitiesService{s: s}
return rs
}
type ActivitiesService struct {
s *Service
}
func NewCaptionsService(s *Service) *CaptionsService {
rs := &CaptionsService{s: s}
return rs
}
type CaptionsService struct {
s *Service
}
func NewChannelBannersService(s *Service) *ChannelBannersService {
rs := &ChannelBannersService{s: s}
return rs
}
type ChannelBannersService struct {
s *Service
}
func NewChannelSectionsService(s *Service) *ChannelSectionsService {
rs := &ChannelSectionsService{s: s}
return rs
}
type ChannelSectionsService struct {
s *Service
}
func NewChannelsService(s *Service) *ChannelsService {
rs := &ChannelsService{s: s}
return rs
}
type ChannelsService struct {
s *Service
}
func NewCommentThreadsService(s *Service) *CommentThreadsService {
rs := &CommentThreadsService{s: s}
return rs
}
type CommentThreadsService struct {
s *Service
}
func NewCommentsService(s *Service) *CommentsService {
rs := &CommentsService{s: s}
return rs
}
type CommentsService struct {
s *Service
}
func NewGuideCategoriesService(s *Service) *GuideCategoriesService {
rs := &GuideCategoriesService{s: s}
return rs
}
type GuideCategoriesService struct {
s *Service
}
func NewI18nLanguagesService(s *Service) *I18nLanguagesService {
rs := &I18nLanguagesService{s: s}
return rs
}
type I18nLanguagesService struct {
s *Service
}
func NewI18nRegionsService(s *Service) *I18nRegionsService {
rs := &I18nRegionsService{s: s}
return rs
}
type I18nRegionsService struct {
s *Service
}
func NewLiveBroadcastsService(s *Service) *LiveBroadcastsService {
rs := &LiveBroadcastsService{s: s}
return rs
}
type LiveBroadcastsService struct {
s *Service
}
func NewLiveChatBansService(s *Service) *LiveChatBansService {
rs := &LiveChatBansService{s: s}
return rs
}
type LiveChatBansService struct {
s *Service
}
func NewLiveChatMessagesService(s *Service) *LiveChatMessagesService {
rs := &LiveChatMessagesService{s: s}
return rs
}
type LiveChatMessagesService struct {
s *Service
}
func NewLiveChatModeratorsService(s *Service) *LiveChatModeratorsService {
rs := &LiveChatModeratorsService{s: s}
return rs
}
type LiveChatModeratorsService struct {
s *Service
}
func NewLiveStreamsService(s *Service) *LiveStreamsService |
type LiveStreamsService struct {
s *Service
}
func NewPlaylistItemsService(s *Service) *PlaylistItemsService {
rs := &PlaylistItemsService{s: s}
return rs
}
type PlaylistItemsService struct {
s *Service
}
func NewPlaylistsService(s *Service) *PlaylistsService {
rs := &PlaylistsService{s: s}
return rs
}
type PlaylistsService struct {
s *Service
}
func NewSearchService(s *Service) *SearchService {
rs := &SearchService{s: s}
return rs
}
type SearchService struct {
s *Service
}
func NewSponsorsService(s *Service) *SponsorsService {
rs := &SponsorsService{s: s}
return rs
}
type SponsorsService struct {
s *Service
}
func NewSubscriptionsService(s *Service) *SubscriptionsService {
rs := &SubscriptionsService{s: s}
return rs
}
type SubscriptionsService struct {
s *Service
}
func NewSuperChatEventsService(s *Service) *SuperChatEventsService {
rs := &SuperChatEventsService{s: s}
return rs
}
type SuperChatEventsService struct {
s *Service
}
func NewThumbnailsService(s *Service) *ThumbnailsService {
rs := &ThumbnailsService{s: s}
return rs
}
type ThumbnailsService struct {
s *Service
}
func NewVideoAbuseReportReasonsService(s *Service) *VideoAbuseReportReasonsService {
rs := &VideoAbuseReportReasonsService{s: s}
return rs
}
type VideoAbuseReportReasonsService struct {
s *Service
}
func NewVideoCategoriesService(s *Service) *VideoCategoriesService {
rs := &VideoCategoriesService{s: s}
return rs
}
type VideoCategoriesService struct {
s *Service
}
func NewVideosService(s *Service) *VideosService {
rs := &VideosService{s: s}
return rs
}
type VideosService struct {
s *Service
}
func NewWatermarksService(s *Service) *WatermarksService {
rs := &WatermarksService{s: s}
return rs
}
type WatermarksService struct {
s *Service
}
// AccessPolicy: Rights management policy for YouTube resources.
type AccessPolicy struct {
// Allowed: The value of allowed indicates whether the access to the
// policy is allowed or denied by default.
Allowed bool `json:"allowed,omitempty"`
// Exception: A list of region codes that identify countries where the
// default policy do not apply.
Exception []string `json:"exception,omitempty"`
// ForceSendFields is a list of field names (e.g. "Allowed") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Allowed") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AccessPolicy) MarshalJSON() ([]byte, error) {
type NoMethod AccessPolicy
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Activity: An activity resource contains information about an action
// that a particular channel, or user, has taken on YouTube.The actions
// reported in activity feeds include rating a video, sharing a video,
// marking a video as a favorite, commenting on a video, uploading a
// video, and so forth. Each activity resource identifies the type of
// action, the channel associated with the action, and the resource(s)
// associated with the action, such as the video that was rated or
// uploaded.
type Activity struct {
// ContentDetails: The contentDetails object contains information about
// the content associated with the activity. For example, if the
// snippet.type value is videoRated, then the contentDetails object's
// content identifies the rated video.
ContentDetails *ActivityContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the activity.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#activity".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the
// activity, including the activity's type and group ID.
Snippet *ActivitySnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ContentDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentDetails") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *Activity) MarshalJSON() ([]byte, error) {
type NoMethod Activity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetails: Details about the content of an activity: the
// video that was shared, the channel that was subscribed to, etc.
type ActivityContentDetails struct {
// Bulletin: The bulletin object contains details about a channel
// bulletin post. This object is only present if the snippet.type is
// bulletin.
Bulletin *ActivityContentDetailsBulletin `json:"bulletin,omitempty"`
// ChannelItem: The channelItem object contains details about a resource
// which was added to a channel. This property is only present if the
// snippet.type is channelItem.
ChannelItem *ActivityContentDetailsChannelItem `json:"channelItem,omitempty"`
// Comment: The comment object contains information about a resource
// that received a comment. This property is only present if the
// snippet.type is comment.
Comment *ActivityContentDetailsComment `json:"comment,omitempty"`
// Favorite: The favorite object contains information about a video that
// was marked as a favorite video. This property is only present if the
// snippet.type is favorite.
Favorite *ActivityContentDetailsFavorite `json:"favorite,omitempty"`
// Like: The like object contains information about a resource that
// received a positive (like) rating. This property is only present if
// the snippet.type is like.
Like *ActivityContentDetailsLike `json:"like,omitempty"`
// PlaylistItem: The playlistItem object contains information about a
// new playlist item. This property is only present if the snippet.type
// is playlistItem.
PlaylistItem *ActivityContentDetailsPlaylistItem `json:"playlistItem,omitempty"`
// PromotedItem: The promotedItem object contains details about a
// resource which is being promoted. This property is only present if
// the snippet.type is promotedItem.
PromotedItem *ActivityContentDetailsPromotedItem `json:"promotedItem,omitempty"`
// Recommendation: The recommendation object contains information about
// a recommended resource. This property is only present if the
// snippet.type is recommendation.
Recommendation *ActivityContentDetailsRecommendation `json:"recommendation,omitempty"`
// Social: The social object contains details about a social network
// post. This property is only present if the snippet.type is social.
Social *ActivityContentDetailsSocial `json:"social,omitempty"`
// Subscription: The subscription object contains information about a
// channel that a user subscribed to. This property is only present if
// the snippet.type is subscription.
Subscription *ActivityContentDetailsSubscription `json:"subscription,omitempty"`
// Upload: The upload object contains information about the uploaded
// video. This property is only present if the snippet.type is upload.
Upload *ActivityContentDetailsUpload `json:"upload,omitempty"`
// ForceSendFields is a list of field names (e.g. "Bulletin") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bulletin") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsBulletin: Details about a channel bulletin
// post.
type ActivityContentDetailsBulletin struct {
// ResourceId: The resourceId object contains information that
// identifies the resource associated with a bulletin post.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResourceId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResourceId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsBulletin) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsBulletin
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsChannelItem: Details about a resource which was
// added to a channel.
type ActivityContentDetailsChannelItem struct {
// ResourceId: The resourceId object contains information that
// identifies the resource that was added to the channel.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResourceId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResourceId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsChannelItem) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsChannelItem
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsComment: Information about a resource that
// received a comment.
type ActivityContentDetailsComment struct {
// ResourceId: The resourceId object contains information that
// identifies the resource associated with the comment.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResourceId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResourceId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsComment) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsComment
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsFavorite: Information about a video that was
// marked as a favorite video.
type ActivityContentDetailsFavorite struct {
// ResourceId: The resourceId object contains information that
// identifies the resource that was marked as a favorite.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResourceId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResourceId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsFavorite) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsFavorite
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsLike: Information about a resource that
// received a positive (like) rating.
type ActivityContentDetailsLike struct {
// ResourceId: The resourceId object contains information that
// identifies the rated resource.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResourceId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResourceId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsLike) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsLike
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsPlaylistItem: Information about a new playlist
// item.
type ActivityContentDetailsPlaylistItem struct {
// PlaylistId: The value that YouTube uses to uniquely identify the
// playlist.
PlaylistId string `json:"playlistId,omitempty"`
// PlaylistItemId: ID of the item within the playlist.
PlaylistItemId string `json:"playlistItemId,omitempty"`
// ResourceId: The resourceId object contains information about the
// resource that was added to the playlist.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "PlaylistId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PlaylistId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsPlaylistItem) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsPlaylistItem
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsPromotedItem: Details about a resource which is
// being promoted.
type ActivityContentDetailsPromotedItem struct {
// AdTag: The URL the client should fetch to request a promoted item.
AdTag string `json:"adTag,omitempty"`
// ClickTrackingUrl: The URL the client should ping to indicate that the
// user clicked through on this promoted item.
ClickTrackingUrl string `json:"clickTrackingUrl,omitempty"`
// CreativeViewUrl: The URL the client should ping to indicate that the
// user was shown this promoted item.
CreativeViewUrl string `json:"creativeViewUrl,omitempty"`
// CtaType: The type of call-to-action, a message to the user indicating
// action that can be taken.
//
// Possible values:
// "unspecified"
// "visitAdvertiserSite"
CtaType string `json:"ctaType,omitempty"`
// CustomCtaButtonText: The custom call-to-action button text. If
// specified, it will override the default button text for the cta_type.
CustomCtaButtonText string `json:"customCtaButtonText,omitempty"`
// DescriptionText: The text description to accompany the promoted item.
DescriptionText string `json:"descriptionText,omitempty"`
// DestinationUrl: The URL the client should direct the user to, if the
// user chooses to visit the advertiser's website.
DestinationUrl string `json:"destinationUrl,omitempty"`
// ForecastingUrl: The list of forecasting URLs. The client should ping
// all of these URLs when a promoted item is not available, to indicate
// that a promoted item could have been shown.
ForecastingUrl []string `json:"forecastingUrl,omitempty"`
// ImpressionUrl: The list of impression URLs. The client should ping
// all of these URLs to indicate that the user was shown this promoted
// item.
ImpressionUrl []string `json:"impressionUrl,omitempty"`
// VideoId: The ID that YouTube uses to uniquely identify the promoted
// video.
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "AdTag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AdTag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsPromotedItem) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsPromotedItem
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsRecommendation: Information that identifies the
// recommended resource.
type ActivityContentDetailsRecommendation struct {
// Reason: The reason that the resource is recommended to the user.
//
// Possible values:
// "unspecified"
// "videoFavorited"
// "videoLiked"
// "videoWatched"
Reason string `json:"reason,omitempty"`
// ResourceId: The resourceId object contains information that
// identifies the recommended resource.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// SeedResourceId: The seedResourceId object contains information about
// the resource that caused the recommendation.
SeedResourceId *ResourceId `json:"seedResourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Reason") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Reason") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsRecommendation) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsRecommendation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsSocial: Details about a social network post.
type ActivityContentDetailsSocial struct {
// Author: The author of the social network post.
Author string `json:"author,omitempty"`
// ImageUrl: An image of the post's author.
ImageUrl string `json:"imageUrl,omitempty"`
// ReferenceUrl: The URL of the social network post.
ReferenceUrl string `json:"referenceUrl,omitempty"`
// ResourceId: The resourceId object encapsulates information that
// identifies the resource associated with a social network post.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// Type: The name of the social network.
//
// Possible values:
// "facebook"
// "googlePlus"
// "twitter"
// "unspecified"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Author") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Author") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsSocial) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsSocial
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsSubscription: Information about a channel that
// a user subscribed to.
type ActivityContentDetailsSubscription struct {
// ResourceId: The resourceId object contains information that
// identifies the resource that the user subscribed to.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResourceId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResourceId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsSubscription) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsSubscription
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivityContentDetailsUpload: Information about the uploaded video.
type ActivityContentDetailsUpload struct {
// VideoId: The ID that YouTube uses to uniquely identify the uploaded
// video.
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "VideoId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "VideoId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityContentDetailsUpload) MarshalJSON() ([]byte, error) {
type NoMethod ActivityContentDetailsUpload
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ActivityListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of activities, or events, that match the request
// criteria.
Items []*Activity `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#activityListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivityListResponse) MarshalJSON() ([]byte, error) {
type NoMethod ActivityListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ActivitySnippet: Basic details about an activity, including title,
// description, thumbnails, activity type and group.
type ActivitySnippet struct {
// ChannelId: The ID that YouTube uses to uniquely identify the channel
// associated with the activity.
ChannelId string `json:"channelId,omitempty"`
// ChannelTitle: Channel title for the channel responsible for this
// activity
ChannelTitle string `json:"channelTitle,omitempty"`
// Description: The description of the resource primarily associated
// with the activity.
Description string `json:"description,omitempty"`
// GroupId: The group ID associated with the activity. A group ID
// identifies user events that are associated with the same user and
// resource. For example, if a user rates a video and marks the same
// video as a favorite, the entries for those events would have the same
// group ID in the user's activity feed. In your user interface, you can
// avoid repetition by grouping events with the same groupId value.
GroupId string `json:"groupId,omitempty"`
// PublishedAt: The date and time that the video was uploaded. The value
// is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// Thumbnails: A map of thumbnail images associated with the resource
// that is primarily associated with the activity. For each object in
// the map, the key is the name of the thumbnail image, and the value is
// an object that contains other information about the thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The title of the resource primarily associated with the
// activity.
Title string `json:"title,omitempty"`
// Type: The type of activity that the resource describes.
//
// Possible values:
// "bulletin"
// "channelItem"
// "comment"
// "favorite"
// "like"
// "playlistItem"
// "promotedItem"
// "recommendation"
// "social"
// "subscription"
// "upload"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ActivitySnippet) MarshalJSON() ([]byte, error) {
type NoMethod ActivitySnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Caption: A caption resource represents a YouTube caption track. A
// caption track is associated with exactly one YouTube video.
type Caption struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the caption track.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#caption".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the caption.
Snippet *CaptionSnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Caption) MarshalJSON() ([]byte, error) {
type NoMethod Caption
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type CaptionListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of captions that match the request criteria.
Items []*Caption `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#captionListResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CaptionListResponse) MarshalJSON() ([]byte, error) {
type NoMethod CaptionListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CaptionSnippet: Basic details about a caption track, such as its
// language and name.
type CaptionSnippet struct {
// AudioTrackType: The type of audio track associated with the caption
// track.
//
// Possible values:
// "commentary"
// "descriptive"
// "primary"
// "unknown"
AudioTrackType string `json:"audioTrackType,omitempty"`
// FailureReason: The reason that YouTube failed to process the caption
// track. This property is only present if the state property's value is
// failed.
//
// Possible values:
// "processingFailed"
// "unknownFormat"
// "unsupportedFormat"
FailureReason string `json:"failureReason,omitempty"`
// IsAutoSynced: Indicates whether YouTube synchronized the caption
// track to the audio track in the video. The value will be true if a
// sync was explicitly requested when the caption track was uploaded.
// For example, when calling the captions.insert or captions.update
// methods, you can set the sync parameter to true to instruct YouTube
// to sync the uploaded track to the video. If the value is false,
// YouTube uses the time codes in the uploaded caption track to
// determine when to display captions.
IsAutoSynced bool `json:"isAutoSynced,omitempty"`
// IsCC: Indicates whether the track contains closed captions for the
// deaf and hard of hearing. The default value is false.
IsCC bool `json:"isCC,omitempty"`
// IsDraft: Indicates whether the caption track is a draft. If the value
// is true, then the track is not publicly visible. The default value is
// false.
IsDraft bool `json:"isDraft,omitempty"`
// IsEasyReader: Indicates whether caption track is formatted for "easy
// reader," meaning it is at a third-grade level for language learners.
// The default value is false.
IsEasyReader bool `json:"isEasyReader,omitempty"`
// IsLarge: Indicates whether the caption track uses large text for the
// vision-impaired. The default value is false.
IsLarge bool `json:"isLarge,omitempty"`
// Language: The language of the caption track. The property value is a
// BCP-47 language tag.
Language string `json:"language,omitempty"`
// LastUpdated: The date and time when the caption track was last
// updated. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
LastUpdated string `json:"lastUpdated,omitempty"`
// Name: The name of the caption track. The name is intended to be
// visible to the user as an option during playback.
Name string `json:"name,omitempty"`
// Status: The caption track's status.
//
// Possible values:
// "failed"
// "serving"
// "syncing"
Status string `json:"status,omitempty"`
// TrackKind: The caption track's type.
//
// Possible values:
// "ASR"
// "forced"
// "standard"
TrackKind string `json:"trackKind,omitempty"`
// VideoId: The ID that YouTube uses to uniquely identify the video
// associated with the caption track.
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "AudioTrackType") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AudioTrackType") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CaptionSnippet) MarshalJSON() ([]byte, error) {
type NoMethod CaptionSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CdnSettings: Brief description of the live stream cdn settings.
type CdnSettings struct {
// Format: The format of the video stream that you are sending to
// Youtube.
Format string `json:"format,omitempty"`
// FrameRate: The frame rate of the inbound video data.
//
// Possible values:
// "30fps"
// "60fps"
// "variable"
FrameRate string `json:"frameRate,omitempty"`
// IngestionInfo: The ingestionInfo object contains information that
// YouTube provides that you need to transmit your RTMP or HTTP stream
// to YouTube.
IngestionInfo *IngestionInfo `json:"ingestionInfo,omitempty"`
// IngestionType: The method or protocol used to transmit the video
// stream.
//
// Possible values:
// "dash"
// "rtmp"
IngestionType string `json:"ingestionType,omitempty"`
// Resolution: The resolution of the inbound video data.
//
// Possible values:
// "1080p"
// "1440p"
// "2160p"
// "240p"
// "360p"
// "480p"
// "720p"
// "variable"
Resolution string `json:"resolution,omitempty"`
// ForceSendFields is a list of field names (e.g. "Format") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Format") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CdnSettings) MarshalJSON() ([]byte, error) {
type NoMethod CdnSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Channel: A channel resource contains information about a YouTube
// channel.
type Channel struct {
// AuditDetails: The auditionDetails object encapsulates channel data
// that is relevant for YouTube Partners during the audition process.
AuditDetails *ChannelAuditDetails `json:"auditDetails,omitempty"`
// BrandingSettings: The brandingSettings object encapsulates
// information about the branding of the channel.
BrandingSettings *ChannelBrandingSettings `json:"brandingSettings,omitempty"`
// ContentDetails: The contentDetails object encapsulates information
// about the channel's content.
ContentDetails *ChannelContentDetails `json:"contentDetails,omitempty"`
// ContentOwnerDetails: The contentOwnerDetails object encapsulates
// channel data that is relevant for YouTube Partners linked with the
// channel.
ContentOwnerDetails *ChannelContentOwnerDetails `json:"contentOwnerDetails,omitempty"`
// ConversionPings: The conversionPings object encapsulates information
// about conversion pings that need to be respected by the channel.
ConversionPings *ChannelConversionPings `json:"conversionPings,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the channel.
Id string `json:"id,omitempty"`
// InvideoPromotion: The invideoPromotion object encapsulates
// information about promotion campaign associated with the channel.
InvideoPromotion *InvideoPromotion `json:"invideoPromotion,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#channel".
Kind string `json:"kind,omitempty"`
// Localizations: Localizations for different languages
Localizations map[string]ChannelLocalization `json:"localizations,omitempty"`
// Snippet: The snippet object contains basic details about the channel,
// such as its title, description, and thumbnail images.
Snippet *ChannelSnippet `json:"snippet,omitempty"`
// Statistics: The statistics object encapsulates statistics for the
// channel.
Statistics *ChannelStatistics `json:"statistics,omitempty"`
// Status: The status object encapsulates information about the privacy
// status of the channel.
Status *ChannelStatus `json:"status,omitempty"`
// TopicDetails: The topicDetails object encapsulates information about
// Freebase topics associated with the channel.
TopicDetails *ChannelTopicDetails `json:"topicDetails,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "AuditDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuditDetails") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Channel) MarshalJSON() ([]byte, error) {
type NoMethod Channel
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelAuditDetails: The auditDetails object encapsulates channel
// data that is relevant for YouTube Partners during the audit process.
type ChannelAuditDetails struct {
// CommunityGuidelinesGoodStanding: Whether or not the channel respects
// the community guidelines.
CommunityGuidelinesGoodStanding bool `json:"communityGuidelinesGoodStanding,omitempty"`
// ContentIdClaimsGoodStanding: Whether or not the channel has any
// unresolved claims.
ContentIdClaimsGoodStanding bool `json:"contentIdClaimsGoodStanding,omitempty"`
// CopyrightStrikesGoodStanding: Whether or not the channel has any
// copyright strikes.
CopyrightStrikesGoodStanding bool `json:"copyrightStrikesGoodStanding,omitempty"`
// OverallGoodStanding: Describes the general state of the channel. This
// field will always show if there are any issues whatsoever with the
// channel. Currently this field represents the result of the logical
// and operation over the community guidelines good standing, the
// copyright strikes good standing and the content ID claims good
// standing, but this may change in the future.
OverallGoodStanding bool `json:"overallGoodStanding,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "CommunityGuidelinesGoodStanding") to unconditionally include in API
// requests. By default, fields with empty values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "CommunityGuidelinesGoodStanding") to include in API requests with
// the JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelAuditDetails) MarshalJSON() ([]byte, error) {
type NoMethod ChannelAuditDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelBannerResource: A channel banner returned as the response to a
// channel_banner.insert call.
type ChannelBannerResource struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#channelBannerResource".
Kind string `json:"kind,omitempty"`
// Url: The URL of this banner image.
Url string `json:"url,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelBannerResource) MarshalJSON() ([]byte, error) {
type NoMethod ChannelBannerResource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelBrandingSettings: Branding properties of a YouTube channel.
type ChannelBrandingSettings struct {
// Channel: Branding properties for the channel view.
Channel *ChannelSettings `json:"channel,omitempty"`
// Hints: Additional experimental branding properties.
Hints []*PropertyValue `json:"hints,omitempty"`
// Image: Branding properties for branding images.
Image *ImageSettings `json:"image,omitempty"`
// Watch: Branding properties for the watch page.
Watch *WatchSettings `json:"watch,omitempty"`
// ForceSendFields is a list of field names (e.g. "Channel") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Channel") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelBrandingSettings) MarshalJSON() ([]byte, error) {
type NoMethod ChannelBrandingSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelContentDetails: Details about the content of a channel.
type ChannelContentDetails struct {
RelatedPlaylists *ChannelContentDetailsRelatedPlaylists `json:"relatedPlaylists,omitempty"`
// ForceSendFields is a list of field names (e.g. "RelatedPlaylists") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "RelatedPlaylists") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ChannelContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod ChannelContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ChannelContentDetailsRelatedPlaylists struct {
// Favorites: The ID of the playlist that contains the channel"s
// favorite videos. Use the playlistItems.insert and
// playlistItems.delete to add or remove items from that list.
Favorites string `json:"favorites,omitempty"`
// Likes: The ID of the playlist that contains the channel"s liked
// videos. Use the playlistItems.insert and playlistItems.delete to
// add or remove items from that list.
Likes string `json:"likes,omitempty"`
// Uploads: The ID of the playlist that contains the channel"s uploaded
// videos. Use the videos.insert method to upload new videos and the
// videos.delete method to delete previously uploaded videos.
Uploads string `json:"uploads,omitempty"`
// WatchHistory: The ID of the playlist that contains the channel"s
// watch history. Use the playlistItems.insert and
// playlistItems.delete to add or remove items from that list.
WatchHistory string `json:"watchHistory,omitempty"`
// WatchLater: The ID of the playlist that contains the channel"s watch
// later playlist. Use the playlistItems.insert and
// playlistItems.delete to add or remove items from that list.
WatchLater string `json:"watchLater,omitempty"`
// ForceSendFields is a list of field names (e.g. "Favorites") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Favorites") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelContentDetailsRelatedPlaylists) MarshalJSON() ([]byte, error) {
type NoMethod ChannelContentDetailsRelatedPlaylists
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelContentOwnerDetails: The contentOwnerDetails object
// encapsulates channel data that is relevant for YouTube Partners
// linked with the channel.
type ChannelContentOwnerDetails struct {
// ContentOwner: The ID of the content owner linked to the channel.
ContentOwner string `json:"contentOwner,omitempty"`
// TimeLinked: The date and time of when the channel was linked to the
// content owner. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
TimeLinked string `json:"timeLinked,omitempty"`
// ForceSendFields is a list of field names (e.g. "ContentOwner") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentOwner") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelContentOwnerDetails) MarshalJSON() ([]byte, error) {
type NoMethod ChannelContentOwnerDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelConversionPing: Pings that the app shall fire (authenticated
// by biscotti cookie). Each ping has a context, in which the app must
// fire the ping, and a url identifying the ping.
type ChannelConversionPing struct {
// Context: Defines the context of the ping.
//
// Possible values:
// "cview"
// "subscribe"
// "unsubscribe"
Context string `json:"context,omitempty"`
// ConversionUrl: The url (without the schema) that the player shall
// send the ping to. It's at caller's descretion to decide which schema
// to use (http vs https) Example of a returned url:
// //googleads.g.doubleclick.net/pagead/
// viewthroughconversion/962985656/?data=path%3DtHe_path%3Btype%3D
// cview%3Butuid%3DGISQtTNGYqaYl4sKxoVvKA&labe=default The caller must
// append biscotti authentication (ms param in case of mobile, for
// example) to this ping.
ConversionUrl string `json:"conversionUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Context") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelConversionPing) MarshalJSON() ([]byte, error) {
type NoMethod ChannelConversionPing
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelConversionPings: The conversionPings object encapsulates
// information about conversion pings that need to be respected by the
// channel.
type ChannelConversionPings struct {
// Pings: Pings that the app shall fire (authenticated by biscotti
// cookie). Each ping has a context, in which the app must fire the
// ping, and a url identifying the ping.
Pings []*ChannelConversionPing `json:"pings,omitempty"`
// ForceSendFields is a list of field names (e.g. "Pings") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Pings") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelConversionPings) MarshalJSON() ([]byte, error) {
type NoMethod ChannelConversionPings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ChannelListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of channels that match the request criteria.
Items []*Channel `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#channelListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelListResponse) MarshalJSON() ([]byte, error) {
type NoMethod ChannelListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelLocalization: Channel localization setting
type ChannelLocalization struct {
// Description: The localized strings for channel's description.
Description string `json:"description,omitempty"`
// Title: The localized strings for channel's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelLocalization) MarshalJSON() ([]byte, error) {
type NoMethod ChannelLocalization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ChannelProfileDetails struct {
// ChannelId: The YouTube channel ID.
ChannelId string `json:"channelId,omitempty"`
// ChannelUrl: The channel's URL.
ChannelUrl string `json:"channelUrl,omitempty"`
// DisplayName: The channel's display name.
DisplayName string `json:"displayName,omitempty"`
// ProfileImageUrl: The channels's avatar URL.
ProfileImageUrl string `json:"profileImageUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelProfileDetails) MarshalJSON() ([]byte, error) {
type NoMethod ChannelProfileDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ChannelSection struct {
// ContentDetails: The contentDetails object contains details about the
// channel section content, such as a list of playlists or channels
// featured in the section.
ContentDetails *ChannelSectionContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the channel
// section.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#channelSection".
Kind string `json:"kind,omitempty"`
// Localizations: Localizations for different languages
Localizations map[string]ChannelSectionLocalization `json:"localizations,omitempty"`
// Snippet: The snippet object contains basic details about the channel
// section, such as its type, style and title.
Snippet *ChannelSectionSnippet `json:"snippet,omitempty"`
// Targeting: The targeting object contains basic targeting settings
// about the channel section.
Targeting *ChannelSectionTargeting `json:"targeting,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ContentDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentDetails") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ChannelSection) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelSectionContentDetails: Details about a channelsection,
// including playlists and channels.
type ChannelSectionContentDetails struct {
// Channels: The channel ids for type multiple_channels.
Channels []string `json:"channels,omitempty"`
// Playlists: The playlist ids for type single_playlist and
// multiple_playlists. For singlePlaylist, only one playlistId is
// allowed.
Playlists []string `json:"playlists,omitempty"`
// ForceSendFields is a list of field names (e.g. "Channels") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Channels") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSectionContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSectionContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ChannelSectionListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of ChannelSections that match the request criteria.
Items []*ChannelSection `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#channelSectionListResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSectionListResponse) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSectionListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelSectionLocalization: ChannelSection localization setting
type ChannelSectionLocalization struct {
// Title: The localized strings for channel section's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Title") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Title") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSectionLocalization) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSectionLocalization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelSectionSnippet: Basic details about a channel section,
// including title, style and position.
type ChannelSectionSnippet struct {
// ChannelId: The ID that YouTube uses to uniquely identify the channel
// that published the channel section.
ChannelId string `json:"channelId,omitempty"`
// DefaultLanguage: The language of the channel section's default title
// and description.
DefaultLanguage string `json:"defaultLanguage,omitempty"`
// Localized: Localized title, read-only.
Localized *ChannelSectionLocalization `json:"localized,omitempty"`
// Position: The position of the channel section in the channel.
Position *int64 `json:"position,omitempty"`
// Style: The style of the channel section.
//
// Possible values:
// "channelsectionStyleUndefined"
// "horizontalRow"
// "verticalList"
Style string `json:"style,omitempty"`
// Title: The channel section's title for multiple_playlists and
// multiple_channels.
Title string `json:"title,omitempty"`
// Type: The type of the channel section.
//
// Possible values:
// "allPlaylists"
// "channelsectionTypeUndefined"
// "completedEvents"
// "likedPlaylists"
// "likes"
// "liveEvents"
// "multipleChannels"
// "multiplePlaylists"
// "popularUploads"
// "postedPlaylists"
// "postedVideos"
// "recentActivity"
// "recentPosts"
// "recentUploads"
// "singlePlaylist"
// "subscriptions"
// "upcomingEvents"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSectionSnippet) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSectionSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelSectionTargeting: ChannelSection targeting setting.
type ChannelSectionTargeting struct {
// Countries: The country the channel section is targeting.
Countries []string `json:"countries,omitempty"`
// Languages: The language the channel section is targeting.
Languages []string `json:"languages,omitempty"`
// Regions: The region the channel section is targeting.
Regions []string `json:"regions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Countries") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Countries") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSectionTargeting) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSectionTargeting
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelSettings: Branding properties for the channel view.
type ChannelSettings struct {
// Country: The country of the channel.
Country string `json:"country,omitempty"`
DefaultLanguage string `json:"defaultLanguage,omitempty"`
// DefaultTab: Which content tab users should see when viewing the
// channel.
DefaultTab string `json:"defaultTab,omitempty"`
// Description: Specifies the channel description.
Description string `json:"description,omitempty"`
// FeaturedChannelsTitle: Title for the featured channels tab.
FeaturedChannelsTitle string `json:"featuredChannelsTitle,omitempty"`
// FeaturedChannelsUrls: The list of featured channels.
FeaturedChannelsUrls []string `json:"featuredChannelsUrls,omitempty"`
// Keywords: Lists keywords associated with the channel,
// comma-separated.
Keywords string `json:"keywords,omitempty"`
// ModerateComments: Whether user-submitted comments left on the channel
// page need to be approved by the channel owner to be publicly visible.
ModerateComments bool `json:"moderateComments,omitempty"`
// ProfileColor: A prominent color that can be rendered on this channel
// page.
ProfileColor string `json:"profileColor,omitempty"`
// ShowBrowseView: Whether the tab to browse the videos should be
// displayed.
ShowBrowseView bool `json:"showBrowseView,omitempty"`
// ShowRelatedChannels: Whether related channels should be proposed.
ShowRelatedChannels bool `json:"showRelatedChannels,omitempty"`
// Title: Specifies the channel title.
Title string `json:"title,omitempty"`
// TrackingAnalyticsAccountId: The ID for a Google Analytics account to
// track and measure traffic to the channels.
TrackingAnalyticsAccountId string `json:"trackingAnalyticsAccountId,omitempty"`
// UnsubscribedTrailer: The trailer of the channel, for users that are
// not subscribers.
UnsubscribedTrailer string `json:"unsubscribedTrailer,omitempty"`
// ForceSendFields is a list of field names (e.g. "Country") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Country") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSettings) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelSnippet: Basic details about a channel, including title,
// description and thumbnails.
type ChannelSnippet struct {
// Country: The country of the channel.
Country string `json:"country,omitempty"`
// CustomUrl: The custom url of the channel.
CustomUrl string `json:"customUrl,omitempty"`
// DefaultLanguage: The language of the channel's default title and
// description.
DefaultLanguage string `json:"defaultLanguage,omitempty"`
// Description: The description of the channel.
Description string `json:"description,omitempty"`
// Localized: Localized title and description, read-only.
Localized *ChannelLocalization `json:"localized,omitempty"`
// PublishedAt: The date and time that the channel was created. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// Thumbnails: A map of thumbnail images associated with the channel.
// For each object in the map, the key is the name of the thumbnail
// image, and the value is an object that contains other information
// about the thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The channel's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Country") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Country") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelSnippet) MarshalJSON() ([]byte, error) {
type NoMethod ChannelSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelStatistics: Statistics about a channel: number of subscribers,
// number of videos in the channel, etc.
type ChannelStatistics struct {
// CommentCount: The number of comments for the channel.
CommentCount uint64 `json:"commentCount,omitempty,string"`
// HiddenSubscriberCount: Whether or not the number of subscribers is
// shown for this user.
HiddenSubscriberCount bool `json:"hiddenSubscriberCount,omitempty"`
// SubscriberCount: The number of subscribers that the channel has.
SubscriberCount uint64 `json:"subscriberCount,omitempty,string"`
// VideoCount: The number of videos uploaded to the channel.
VideoCount uint64 `json:"videoCount,omitempty,string"`
// ViewCount: The number of times the channel has been viewed.
ViewCount uint64 `json:"viewCount,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "CommentCount") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CommentCount") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelStatistics) MarshalJSON() ([]byte, error) {
type NoMethod ChannelStatistics
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelStatus: JSON template for the status part of a channel.
type ChannelStatus struct {
// IsLinked: If true, then the user is linked to either a YouTube
// username or G+ account. Otherwise, the user doesn't have a public
// YouTube identity.
IsLinked bool `json:"isLinked,omitempty"`
// LongUploadsStatus: The long uploads status of this channel. See
//
// Possible values:
// "allowed"
// "disallowed"
// "eligible"
// "longUploadsUnspecified"
LongUploadsStatus string `json:"longUploadsStatus,omitempty"`
// PrivacyStatus: Privacy status of the channel.
//
// Possible values:
// "private"
// "public"
// "unlisted"
// "unlisted_new"
PrivacyStatus string `json:"privacyStatus,omitempty"`
// ForceSendFields is a list of field names (e.g. "IsLinked") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IsLinked") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ChannelStatus) MarshalJSON() ([]byte, error) {
type NoMethod ChannelStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ChannelTopicDetails: Freebase topic information related to the
// channel.
type ChannelTopicDetails struct {
// TopicCategories: A list of Wikipedia URLs that describe the channel's
// content.
TopicCategories []string `json:"topicCategories,omitempty"`
// TopicIds: A list of Freebase topic IDs associated with the channel.
// You can retrieve information about each topic using the Freebase
// Topic API.
TopicIds []string `json:"topicIds,omitempty"`
// ForceSendFields is a list of field names (e.g. "TopicCategories") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "TopicCategories") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ChannelTopicDetails) MarshalJSON() ([]byte, error) {
type NoMethod ChannelTopicDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Comment: A comment represents a single YouTube comment.
type Comment struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the comment.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#comment".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the comment.
Snippet *CommentSnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Comment) MarshalJSON() ([]byte, error) {
type NoMethod Comment
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type CommentListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of comments that match the request criteria.
Items []*Comment `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#commentListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CommentListResponse) MarshalJSON() ([]byte, error) {
type NoMethod CommentListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CommentSnippet: Basic details about a comment, such as its author and
// text.
type CommentSnippet struct {
// AuthorChannelId: The id of the author's YouTube channel, if any.
AuthorChannelId interface{} `json:"authorChannelId,omitempty"`
// AuthorChannelUrl: Link to the author's YouTube channel, if any.
AuthorChannelUrl string `json:"authorChannelUrl,omitempty"`
// AuthorDisplayName: The name of the user who posted the comment.
AuthorDisplayName string `json:"authorDisplayName,omitempty"`
// AuthorProfileImageUrl: The URL for the avatar of the user who posted
// the comment.
AuthorProfileImageUrl string `json:"authorProfileImageUrl,omitempty"`
// CanRate: Whether the current viewer can rate this comment.
CanRate bool `json:"canRate,omitempty"`
// ChannelId: The id of the corresponding YouTube channel. In case of a
// channel comment this is the channel the comment refers to. In case of
// a video comment it's the video's channel.
ChannelId string `json:"channelId,omitempty"`
// LikeCount: The total number of likes this comment has received.
LikeCount int64 `json:"likeCount,omitempty"`
// ModerationStatus: The comment's moderation status. Will not be set if
// the comments were requested through the id filter.
//
// Possible values:
// "heldForReview"
// "likelySpam"
// "published"
// "rejected"
ModerationStatus string `json:"moderationStatus,omitempty"`
// ParentId: The unique id of the parent comment, only set for replies.
ParentId string `json:"parentId,omitempty"`
// PublishedAt: The date and time when the comment was orignally
// published. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// TextDisplay: The comment's text. The format is either plain text or
// HTML dependent on what has been requested. Even the plain text
// representation may differ from the text originally posted in that it
// may replace video links with video titles etc.
TextDisplay string `json:"textDisplay,omitempty"`
// TextOriginal: The comment's original raw text as initially posted or
// last updated. The original text will only be returned if it is
// accessible to the viewer, which is only guaranteed if the viewer is
// the comment's author.
TextOriginal string `json:"textOriginal,omitempty"`
// UpdatedAt: The date and time when was last updated . The value is
// specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
UpdatedAt string `json:"updatedAt,omitempty"`
// VideoId: The ID of the video the comment refers to, if any.
VideoId string `json:"videoId,omitempty"`
// ViewerRating: The rating the viewer has given to this comment. For
// the time being this will never return RATE_TYPE_DISLIKE and instead
// return RATE_TYPE_NONE. This may change in the future.
//
// Possible values:
// "dislike"
// "like"
// "none"
// "unspecified"
ViewerRating string `json:"viewerRating,omitempty"`
// ForceSendFields is a list of field names (e.g. "AuthorChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuthorChannelId") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CommentSnippet) MarshalJSON() ([]byte, error) {
type NoMethod CommentSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CommentThread: A comment thread represents information that applies
// to a top level comment and all its replies. It can also include the
// top level comment itself and some of the replies.
type CommentThread struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the comment thread.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#commentThread".
Kind string `json:"kind,omitempty"`
// Replies: The replies object contains a limited number of replies (if
// any) to the top level comment found in the snippet.
Replies *CommentThreadReplies `json:"replies,omitempty"`
// Snippet: The snippet object contains basic details about the comment
// thread and also the top level comment.
Snippet *CommentThreadSnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CommentThread) MarshalJSON() ([]byte, error) {
type NoMethod CommentThread
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type CommentThreadListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of comment threads that match the request criteria.
Items []*CommentThread `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#commentThreadListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CommentThreadListResponse) MarshalJSON() ([]byte, error) {
type NoMethod CommentThreadListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CommentThreadReplies: Comments written in (direct or indirect) reply
// to the top level comment.
type CommentThreadReplies struct {
// Comments: A limited number of replies. Unless the number of replies
// returned equals total_reply_count in the snippet the returned replies
// are only a subset of the total number of replies.
Comments []*Comment `json:"comments,omitempty"`
// ForceSendFields is a list of field names (e.g. "Comments") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Comments") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CommentThreadReplies) MarshalJSON() ([]byte, error) {
type NoMethod CommentThreadReplies
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CommentThreadSnippet: Basic details about a comment thread.
type CommentThreadSnippet struct {
// CanReply: Whether the current viewer of the thread can reply to it.
// This is viewer specific - other viewers may see a different value for
// this field.
CanReply bool `json:"canReply,omitempty"`
// ChannelId: The YouTube channel the comments in the thread refer to or
// the channel with the video the comments refer to. If video_id isn't
// set the comments refer to the channel itself.
ChannelId string `json:"channelId,omitempty"`
// IsPublic: Whether the thread (and therefore all its comments) is
// visible to all YouTube users.
IsPublic bool `json:"isPublic,omitempty"`
// TopLevelComment: The top level comment of this thread.
TopLevelComment *Comment `json:"topLevelComment,omitempty"`
// TotalReplyCount: The total number of replies (not including the top
// level comment).
TotalReplyCount int64 `json:"totalReplyCount,omitempty"`
// VideoId: The ID of the video the comments refer to, if any. No
// video_id implies a channel discussion comment.
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "CanReply") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CanReply") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CommentThreadSnippet) MarshalJSON() ([]byte, error) {
type NoMethod CommentThreadSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ContentRating: Ratings schemes. The country-specific ratings are
// mostly for movies and shows. NEXT_ID: 71
type ContentRating struct {
// AcbRating: The video's Australian Classification Board (ACB) or
// Australian Communications and Media Authority (ACMA) rating. ACMA
// ratings are used to classify children's television programming.
//
// Possible values:
// "acbC"
// "acbE"
// "acbG"
// "acbM"
// "acbMa15plus"
// "acbP"
// "acbPg"
// "acbR18plus"
// "acbUnrated"
AcbRating string `json:"acbRating,omitempty"`
// AgcomRating: The video's rating from Italy's Autorità per le
// Garanzie nelle Comunicazioni (AGCOM).
//
// Possible values:
// "agcomT"
// "agcomUnrated"
// "agcomVm14"
// "agcomVm18"
AgcomRating string `json:"agcomRating,omitempty"`
// AnatelRating: The video's Anatel (Asociación Nacional de
// Televisión) rating for Chilean television.
//
// Possible values:
// "anatelA"
// "anatelF"
// "anatelI"
// "anatelI10"
// "anatelI12"
// "anatelI7"
// "anatelR"
// "anatelUnrated"
AnatelRating string `json:"anatelRating,omitempty"`
// BbfcRating: The video's British Board of Film Classification (BBFC)
// rating.
//
// Possible values:
// "bbfc12"
// "bbfc12a"
// "bbfc15"
// "bbfc18"
// "bbfcPg"
// "bbfcR18"
// "bbfcU"
// "bbfcUnrated"
BbfcRating string `json:"bbfcRating,omitempty"`
// BfvcRating: The video's rating from Thailand's Board of Film and
// Video Censors.
//
// Possible values:
// "bfvc13"
// "bfvc15"
// "bfvc18"
// "bfvc20"
// "bfvcB"
// "bfvcE"
// "bfvcG"
// "bfvcUnrated"
BfvcRating string `json:"bfvcRating,omitempty"`
// BmukkRating: The video's rating from the Austrian Board of Media
// Classification (Bundesministerium für Unterricht, Kunst und Kultur).
//
// Possible values:
// "bmukk10"
// "bmukk12"
// "bmukk14"
// "bmukk16"
// "bmukk6"
// "bmukk8"
// "bmukkAa"
// "bmukkUnrated"
BmukkRating string `json:"bmukkRating,omitempty"`
// CatvRating: Rating system for Canadian TV - Canadian TV
// Classification System The video's rating from the Canadian
// Radio-Television and Telecommunications Commission (CRTC) for
// Canadian English-language broadcasts. For more information, see the
// Canadian Broadcast Standards Council website.
//
// Possible values:
// "catv14plus"
// "catv18plus"
// "catvC"
// "catvC8"
// "catvG"
// "catvPg"
// "catvUnrated"
CatvRating string `json:"catvRating,omitempty"`
// CatvfrRating: The video's rating from the Canadian Radio-Television
// and Telecommunications Commission (CRTC) for Canadian French-language
// broadcasts. For more information, see the Canadian Broadcast
// Standards Council website.
//
// Possible values:
// "catvfr13plus"
// "catvfr16plus"
// "catvfr18plus"
// "catvfr8plus"
// "catvfrG"
// "catvfrUnrated"
CatvfrRating string `json:"catvfrRating,omitempty"`
// CbfcRating: The video's Central Board of Film Certification (CBFC -
// India) rating.
//
// Possible values:
// "cbfcA"
// "cbfcS"
// "cbfcU"
// "cbfcUA"
// "cbfcUnrated"
CbfcRating string `json:"cbfcRating,omitempty"`
// CccRating: The video's Consejo de Calificación Cinematográfica
// (Chile) rating.
//
// Possible values:
// "ccc14"
// "ccc18"
// "ccc18s"
// "ccc18v"
// "ccc6"
// "cccTe"
// "cccUnrated"
CccRating string `json:"cccRating,omitempty"`
// CceRating: The video's rating from Portugal's Comissão de
// Classificação de Espect´culos.
//
// Possible values:
// "cceM12"
// "cceM14"
// "cceM16"
// "cceM18"
// "cceM4"
// "cceM6"
// "cceUnrated"
CceRating string `json:"cceRating,omitempty"`
// ChfilmRating: The video's rating in Switzerland.
//
// Possible values:
// "chfilm0"
// "chfilm12"
// "chfilm16"
// "chfilm18"
// "chfilm6"
// "chfilmUnrated"
ChfilmRating string `json:"chfilmRating,omitempty"`
// ChvrsRating: The video's Canadian Home Video Rating System (CHVRS)
// rating.
//
// Possible values:
// "chvrs14a"
// "chvrs18a"
// "chvrsE"
// "chvrsG"
// "chvrsPg"
// "chvrsR"
// "chvrsUnrated"
ChvrsRating string `json:"chvrsRating,omitempty"`
// CicfRating: The video's rating from the Commission de Contrôle des
// Films (Belgium).
//
// Possible values:
// "cicfE"
// "cicfKntEna"
// "cicfKtEa"
// "cicfUnrated"
CicfRating string `json:"cicfRating,omitempty"`
// CnaRating: The video's rating from Romania's CONSILIUL NATIONAL AL
// AUDIOVIZUALULUI (CNA).
//
// Possible values:
// "cna12"
// "cna15"
// "cna18"
// "cna18plus"
// "cnaAp"
// "cnaUnrated"
CnaRating string `json:"cnaRating,omitempty"`
// CncRating: Rating system in France - Commission de classification
// cinematographique
//
// Possible values:
// "cnc10"
// "cnc12"
// "cnc16"
// "cnc18"
// "cncE"
// "cncT"
// "cncUnrated"
CncRating string `json:"cncRating,omitempty"`
// CsaRating: The video's rating from France's Conseil supérieur de
// l?audiovisuel, which rates broadcast content.
//
// Possible values:
// "csa10"
// "csa12"
// "csa16"
// "csa18"
// "csaInterdiction"
// "csaT"
// "csaUnrated"
CsaRating string `json:"csaRating,omitempty"`
// CscfRating: The video's rating from Luxembourg's Commission de
// surveillance de la classification des films (CSCF).
//
// Possible values:
// "cscf12"
// "cscf16"
// "cscf18"
// "cscf6"
// "cscf9"
// "cscfA"
// "cscfAl"
// "cscfUnrated"
CscfRating string `json:"cscfRating,omitempty"`
// CzfilmRating: The video's rating in the Czech Republic.
//
// Possible values:
// "czfilm12"
// "czfilm14"
// "czfilm18"
// "czfilmU"
// "czfilmUnrated"
CzfilmRating string `json:"czfilmRating,omitempty"`
// DjctqRating: The video's Departamento de Justiça, Classificação,
// Qualificação e Títulos (DJCQT - Brazil) rating.
//
// Possible values:
// "djctq10"
// "djctq12"
// "djctq14"
// "djctq16"
// "djctq18"
// "djctqL"
// "djctqUnrated"
DjctqRating string `json:"djctqRating,omitempty"`
// DjctqRatingReasons: Reasons that explain why the video received its
// DJCQT (Brazil) rating.
//
// Possible values:
// "djctqCriminalActs"
// "djctqDrugs"
// "djctqExplicitSex"
// "djctqExtremeViolence"
// "djctqIllegalDrugs"
// "djctqImpactingContent"
// "djctqInappropriateLanguage"
// "djctqLegalDrugs"
// "djctqNudity"
// "djctqSex"
// "djctqSexualContent"
// "djctqViolence"
DjctqRatingReasons []string `json:"djctqRatingReasons,omitempty"`
// EcbmctRating: Rating system in Turkey - Evaluation and Classification
// Board of the Ministry of Culture and Tourism
//
// Possible values:
// "ecbmct13a"
// "ecbmct13plus"
// "ecbmct15a"
// "ecbmct15plus"
// "ecbmct18plus"
// "ecbmct7a"
// "ecbmct7plus"
// "ecbmctG"
// "ecbmctUnrated"
EcbmctRating string `json:"ecbmctRating,omitempty"`
// EefilmRating: The video's rating in Estonia.
//
// Possible values:
// "eefilmK12"
// "eefilmK14"
// "eefilmK16"
// "eefilmK6"
// "eefilmL"
// "eefilmMs12"
// "eefilmMs6"
// "eefilmPere"
// "eefilmUnrated"
EefilmRating string `json:"eefilmRating,omitempty"`
// EgfilmRating: The video's rating in Egypt.
//
// Possible values:
// "egfilm18"
// "egfilmBn"
// "egfilmGn"
// "egfilmUnrated"
EgfilmRating string `json:"egfilmRating,omitempty"`
// EirinRating: The video's Eirin (映倫) rating. Eirin is the Japanese
// rating system.
//
// Possible values:
// "eirinG"
// "eirinPg12"
// "eirinR15plus"
// "eirinR18plus"
// "eirinUnrated"
EirinRating string `json:"eirinRating,omitempty"`
// FcbmRating: The video's rating from Malaysia's Film Censorship Board.
//
// Possible values:
// "fcbm18"
// "fcbm18pa"
// "fcbm18pl"
// "fcbm18sg"
// "fcbm18sx"
// "fcbmP13"
// "fcbmPg13"
// "fcbmU"
// "fcbmUnrated"
FcbmRating string `json:"fcbmRating,omitempty"`
// FcoRating: The video's rating from Hong Kong's Office for Film,
// Newspaper and Article Administration.
//
// Possible values:
// "fcoI"
// "fcoIi"
// "fcoIia"
// "fcoIib"
// "fcoIii"
// "fcoUnrated"
FcoRating string `json:"fcoRating,omitempty"`
// FmocRating: This property has been deprecated. Use the
// contentDetails.contentRating.cncRating instead.
//
// Possible values:
// "fmoc10"
// "fmoc12"
// "fmoc16"
// "fmoc18"
// "fmocE"
// "fmocU"
// "fmocUnrated"
FmocRating string `json:"fmocRating,omitempty"`
// FpbRating: The video's rating from South Africa's Film and
// Publication Board.
//
// Possible values:
// "fpb10"
// "fpb1012Pg"
// "fpb13"
// "fpb16"
// "fpb18"
// "fpb79Pg"
// "fpbA"
// "fpbPg"
// "fpbUnrated"
// "fpbX18"
// "fpbXx"
FpbRating string `json:"fpbRating,omitempty"`
// FpbRatingReasons: Reasons that explain why the video received its FPB
// (South Africa) rating.
//
// Possible values:
// "fpbBlasphemy"
// "fpbCriminalTechniques"
// "fpbDrugs"
// "fpbHorror"
// "fpbImitativeActsTechniques"
// "fpbLanguage"
// "fpbNudity"
// "fpbPrejudice"
// "fpbSex"
// "fpbSexualViolence"
// "fpbViolence"
FpbRatingReasons []string `json:"fpbRatingReasons,omitempty"`
// FskRating: The video's Freiwillige Selbstkontrolle der Filmwirtschaft
// (FSK - Germany) rating.
//
// Possible values:
// "fsk0"
// "fsk12"
// "fsk16"
// "fsk18"
// "fsk6"
// "fskUnrated"
FskRating string `json:"fskRating,omitempty"`
// GrfilmRating: The video's rating in Greece.
//
// Possible values:
// "grfilmE"
// "grfilmK"
// "grfilmK12"
// "grfilmK13"
// "grfilmK15"
// "grfilmK17"
// "grfilmK18"
// "grfilmUnrated"
GrfilmRating string `json:"grfilmRating,omitempty"`
// IcaaRating: The video's Instituto de la Cinematografía y de las
// Artes Audiovisuales (ICAA - Spain) rating.
//
// Possible values:
// "icaa12"
// "icaa13"
// "icaa16"
// "icaa18"
// "icaa7"
// "icaaApta"
// "icaaUnrated"
// "icaaX"
IcaaRating string `json:"icaaRating,omitempty"`
// IfcoRating: The video's Irish Film Classification Office (IFCO -
// Ireland) rating. See the IFCO website for more information.
//
// Possible values:
// "ifco12"
// "ifco12a"
// "ifco15"
// "ifco15a"
// "ifco16"
// "ifco18"
// "ifcoG"
// "ifcoPg"
// "ifcoUnrated"
IfcoRating string `json:"ifcoRating,omitempty"`
// IlfilmRating: The video's rating in Israel.
//
// Possible values:
// "ilfilm12"
// "ilfilm14"
// "ilfilm16"
// "ilfilm18"
// "ilfilmAa"
// "ilfilmUnrated"
IlfilmRating string `json:"ilfilmRating,omitempty"`
// IncaaRating: The video's INCAA (Instituto Nacional de Cine y Artes
// Audiovisuales - Argentina) rating.
//
// Possible values:
// "incaaAtp"
// "incaaC"
// "incaaSam13"
// "incaaSam16"
// "incaaSam18"
// "incaaUnrated"
IncaaRating string `json:"incaaRating,omitempty"`
// KfcbRating: The video's rating from the Kenya Film Classification
// Board.
//
// Possible values:
// "kfcb16plus"
// "kfcbG"
// "kfcbPg"
// "kfcbR"
// "kfcbUnrated"
KfcbRating string `json:"kfcbRating,omitempty"`
// KijkwijzerRating: voor de Classificatie van Audiovisuele Media
// (Netherlands).
//
// Possible values:
// "kijkwijzer12"
// "kijkwijzer16"
// "kijkwijzer18"
// "kijkwijzer6"
// "kijkwijzer9"
// "kijkwijzerAl"
// "kijkwijzerUnrated"
KijkwijzerRating string `json:"kijkwijzerRating,omitempty"`
// KmrbRating: The video's Korea Media Rating Board
// (영상물등급위원회) rating. The KMRB rates videos in South
// Korea.
//
// Possible values:
// "kmrb12plus"
// "kmrb15plus"
// "kmrbAll"
// "kmrbR"
// "kmrbTeenr"
// "kmrbUnrated"
KmrbRating string `json:"kmrbRating,omitempty"`
// LsfRating: The video's rating from Indonesia's Lembaga Sensor Film.
//
// Possible values:
// "lsf13"
// "lsf17"
// "lsf21"
// "lsfA"
// "lsfBo"
// "lsfD"
// "lsfR"
// "lsfSu"
// "lsfUnrated"
LsfRating string `json:"lsfRating,omitempty"`
// MccaaRating: The video's rating from Malta's Film Age-Classification
// Board.
//
// Possible values:
// "mccaa12"
// "mccaa12a"
// "mccaa14"
// "mccaa15"
// "mccaa16"
// "mccaa18"
// "mccaaPg"
// "mccaaU"
// "mccaaUnrated"
MccaaRating string `json:"mccaaRating,omitempty"`
// MccypRating: The video's rating from the Danish Film Institute's (Det
// Danske Filminstitut) Media Council for Children and Young People.
//
// Possible values:
// "mccyp11"
// "mccyp15"
// "mccyp7"
// "mccypA"
// "mccypUnrated"
MccypRating string `json:"mccypRating,omitempty"`
// McstRating: The video's rating system for Vietnam - MCST
//
// Possible values:
// "mcst0"
// "mcst16plus"
// "mcstC13"
// "mcstC16"
// "mcstC18"
// "mcstGPg"
// "mcstP"
// "mcstUnrated"
McstRating string `json:"mcstRating,omitempty"`
// MdaRating: The video's rating from Singapore's Media Development
// Authority (MDA) and, specifically, it's Board of Film Censors (BFC).
//
// Possible values:
// "mdaG"
// "mdaM18"
// "mdaNc16"
// "mdaPg"
// "mdaPg13"
// "mdaR21"
// "mdaUnrated"
MdaRating string `json:"mdaRating,omitempty"`
// MedietilsynetRating: The video's rating from Medietilsynet, the
// Norwegian Media Authority.
//
// Possible values:
// "medietilsynet11"
// "medietilsynet12"
// "medietilsynet15"
// "medietilsynet18"
// "medietilsynet6"
// "medietilsynet7"
// "medietilsynet9"
// "medietilsynetA"
// "medietilsynetUnrated"
MedietilsynetRating string `json:"medietilsynetRating,omitempty"`
// MekuRating: The video's rating from Finland's Kansallinen
// Audiovisuaalinen Instituutti (National Audiovisual Institute).
//
// Possible values:
// "meku12"
// "meku16"
// "meku18"
// "meku7"
// "mekuS"
// "mekuUnrated"
MekuRating string `json:"mekuRating,omitempty"`
// MenaMpaaRating: The rating system for MENA countries, a clone of
// MPAA. It is needed to
//
// Possible values:
// "menaMpaaG"
// "menaMpaaPg"
// "menaMpaaPg13"
// "menaMpaaR"
// "menaMpaaUnrated"
MenaMpaaRating string `json:"menaMpaaRating,omitempty"`
// MibacRating: The video's rating from the Ministero dei Beni e delle
// Attività Culturali e del Turismo (Italy).
//
// Possible values:
// "mibacT"
// "mibacUnrated"
// "mibacVap"
// "mibacVm12"
// "mibacVm14"
// "mibacVm18"
MibacRating string `json:"mibacRating,omitempty"`
// MocRating: The video's Ministerio de Cultura (Colombia) rating.
//
// Possible values:
// "moc12"
// "moc15"
// "moc18"
// "moc7"
// "mocBanned"
// "mocE"
// "mocT"
// "mocUnrated"
// "mocX"
MocRating string `json:"mocRating,omitempty"`
// MoctwRating: The video's rating from Taiwan's Ministry of Culture
// (文化部).
//
// Possible values:
// "moctwG"
// "moctwP"
// "moctwPg"
// "moctwR"
// "moctwR12"
// "moctwR15"
// "moctwUnrated"
MoctwRating string `json:"moctwRating,omitempty"`
// MpaaRating: The video's Motion Picture Association of America (MPAA)
// rating.
//
// Possible values:
// "mpaaG"
// "mpaaNc17"
// "mpaaPg"
// "mpaaPg13"
// "mpaaR"
// "mpaaUnrated"
MpaaRating string `json:"mpaaRating,omitempty"`
// MpaatRating: The rating system for trailer, DVD, and Ad in the US.
// See http://movielabs.com/md/ratings/v2.3/html/US_MPAAT_Ratings.html.
//
// Possible values:
// "mpaatGb"
// "mpaatRb"
MpaatRating string `json:"mpaatRating,omitempty"`
// MtrcbRating: The video's rating from the Movie and Television Review
// and Classification Board (Philippines).
//
// Possible values:
// "mtrcbG"
// "mtrcbPg"
// "mtrcbR13"
// "mtrcbR16"
// "mtrcbR18"
// "mtrcbUnrated"
// "mtrcbX"
MtrcbRating string `json:"mtrcbRating,omitempty"`
// NbcRating: The video's rating from the Maldives National Bureau of
// Classification.
//
// Possible values:
// "nbc12plus"
// "nbc15plus"
// "nbc18plus"
// "nbc18plusr"
// "nbcG"
// "nbcPg"
// "nbcPu"
// "nbcUnrated"
NbcRating string `json:"nbcRating,omitempty"`
// NbcplRating: The video's rating in Poland.
//
// Possible values:
// "nbcpl18plus"
// "nbcplI"
// "nbcplIi"
// "nbcplIii"
// "nbcplIv"
// "nbcplUnrated"
NbcplRating string `json:"nbcplRating,omitempty"`
// NfrcRating: The video's rating from the Bulgarian National Film
// Center.
//
// Possible values:
// "nfrcA"
// "nfrcB"
// "nfrcC"
// "nfrcD"
// "nfrcUnrated"
// "nfrcX"
NfrcRating string `json:"nfrcRating,omitempty"`
// NfvcbRating: The video's rating from Nigeria's National Film and
// Video Censors Board.
//
// Possible values:
// "nfvcb12"
// "nfvcb12a"
// "nfvcb15"
// "nfvcb18"
// "nfvcbG"
// "nfvcbPg"
// "nfvcbRe"
// "nfvcbUnrated"
NfvcbRating string `json:"nfvcbRating,omitempty"`
// NkclvRating: The video's rating from the Nacionãlais Kino centrs
// (National Film Centre of Latvia).
//
// Possible values:
// "nkclv12plus"
// "nkclv18plus"
// "nkclv7plus"
// "nkclvU"
// "nkclvUnrated"
NkclvRating string `json:"nkclvRating,omitempty"`
// OflcRating: The video's Office of Film and Literature Classification
// (OFLC - New Zealand) rating.
//
// Possible values:
// "oflcG"
// "oflcM"
// "oflcPg"
// "oflcR13"
// "oflcR15"
// "oflcR16"
// "oflcR18"
// "oflcRp13"
// "oflcRp16"
// "oflcRp18"
// "oflcUnrated"
OflcRating string `json:"oflcRating,omitempty"`
// PefilmRating: The video's rating in Peru.
//
// Possible values:
// "pefilm14"
// "pefilm18"
// "pefilmPg"
// "pefilmPt"
// "pefilmUnrated"
PefilmRating string `json:"pefilmRating,omitempty"`
// RcnofRating: The video's rating from the Hungarian Nemzeti Filmiroda,
// the Rating Committee of the National Office of Film.
//
// Possible values:
// "rcnofI"
// "rcnofIi"
// "rcnofIii"
// "rcnofIv"
// "rcnofUnrated"
// "rcnofV"
// "rcnofVi"
RcnofRating string `json:"rcnofRating,omitempty"`
// ResorteviolenciaRating: The video's rating in Venezuela.
//
// Possible values:
// "resorteviolenciaA"
// "resorteviolenciaB"
// "resorteviolenciaC"
// "resorteviolenciaD"
// "resorteviolenciaE"
// "resorteviolenciaUnrated"
ResorteviolenciaRating string `json:"resorteviolenciaRating,omitempty"`
// RtcRating: The video's General Directorate of Radio, Television and
// Cinematography (Mexico) rating.
//
// Possible values:
// "rtcA"
// "rtcAa"
// "rtcB"
// "rtcB15"
// "rtcC"
// "rtcD"
// "rtcUnrated"
RtcRating string `json:"rtcRating,omitempty"`
// RteRating: The video's rating from Ireland's Raidió Teilifís
// Éireann.
//
// Possible values:
// "rteCh"
// "rteGa"
// "rteMa"
// "rtePs"
// "rteUnrated"
RteRating string `json:"rteRating,omitempty"`
// RussiaRating: The video's National Film Registry of the Russian
// Federation (MKRF - Russia) rating.
//
// Possible values:
// "russia0"
// "russia12"
// "russia16"
// "russia18"
// "russia6"
// "russiaUnrated"
RussiaRating string `json:"russiaRating,omitempty"`
// SkfilmRating: The video's rating in Slovakia.
//
// Possible values:
// "skfilmG"
// "skfilmP2"
// "skfilmP5"
// "skfilmP8"
// "skfilmUnrated"
SkfilmRating string `json:"skfilmRating,omitempty"`
// SmaisRating: The video's rating in Iceland.
//
// Possible values:
// "smais12"
// "smais14"
// "smais16"
// "smais18"
// "smais7"
// "smaisL"
// "smaisUnrated"
SmaisRating string `json:"smaisRating,omitempty"`
// SmsaRating: The video's rating from Statens medieråd (Sweden's
// National Media Council).
//
// Possible values:
// "smsa11"
// "smsa15"
// "smsa7"
// "smsaA"
// "smsaUnrated"
SmsaRating string `json:"smsaRating,omitempty"`
// TvpgRating: The video's TV Parental Guidelines (TVPG) rating.
//
// Possible values:
// "pg14"
// "tvpgG"
// "tvpgMa"
// "tvpgPg"
// "tvpgUnrated"
// "tvpgY"
// "tvpgY7"
// "tvpgY7Fv"
TvpgRating string `json:"tvpgRating,omitempty"`
// YtRating: A rating that YouTube uses to identify age-restricted
// content.
//
// Possible values:
// "ytAgeRestricted"
YtRating string `json:"ytRating,omitempty"`
// ForceSendFields is a list of field names (e.g. "AcbRating") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AcbRating") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ContentRating) MarshalJSON() ([]byte, error) {
type NoMethod ContentRating
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GeoPoint: Geographical coordinates of a point, in WGS84.
type GeoPoint struct {
// Altitude: Altitude above the reference ellipsoid, in meters.
Altitude float64 `json:"altitude,omitempty"`
// Latitude: Latitude in degrees.
Latitude float64 `json:"latitude,omitempty"`
// Longitude: Longitude in degrees.
Longitude float64 `json:"longitude,omitempty"`
// ForceSendFields is a list of field names (e.g. "Altitude") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Altitude") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GeoPoint) MarshalJSON() ([]byte, error) {
type NoMethod GeoPoint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GeoPoint) UnmarshalJSON(data []byte) error {
type NoMethod GeoPoint
var s1 struct {
Altitude gensupport.JSONFloat64 `json:"altitude"`
Latitude gensupport.JSONFloat64 `json:"latitude"`
Longitude gensupport.JSONFloat64 `json:"longitude"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Altitude = float64(s1.Altitude)
s.Latitude = float64(s1.Latitude)
s.Longitude = float64(s1.Longitude)
return nil
}
// GuideCategory: A guideCategory resource identifies a category that
// YouTube algorithmically assigns based on a channel's content or other
// indicators, such as the channel's popularity. The list is similar to
// video categories, with the difference being that a video's uploader
// can assign a video category but only YouTube can assign a channel
// category.
type GuideCategory struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the guide category.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#guideCategory".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the
// category, such as its title.
Snippet *GuideCategorySnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GuideCategory) MarshalJSON() ([]byte, error) {
type NoMethod GuideCategory
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type GuideCategoryListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of categories that can be associated with YouTube
// channels. In this map, the category ID is the map key, and its value
// is the corresponding guideCategory resource.
Items []*GuideCategory `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#guideCategoryListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GuideCategoryListResponse) MarshalJSON() ([]byte, error) {
type NoMethod GuideCategoryListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GuideCategorySnippet: Basic details about a guide category.
type GuideCategorySnippet struct {
ChannelId string `json:"channelId,omitempty"`
// Title: Description of the guide category.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GuideCategorySnippet) MarshalJSON() ([]byte, error) {
type NoMethod GuideCategorySnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// I18nLanguage: An i18nLanguage resource identifies a UI language
// currently supported by YouTube.
type I18nLanguage struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the i18n language.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#i18nLanguage".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the i18n
// language, such as language code and human-readable name.
Snippet *I18nLanguageSnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *I18nLanguage) MarshalJSON() ([]byte, error) {
type NoMethod I18nLanguage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type I18nLanguageListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of supported i18n languages. In this map, the i18n
// language ID is the map key, and its value is the corresponding
// i18nLanguage resource.
Items []*I18nLanguage `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#i18nLanguageListResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *I18nLanguageListResponse) MarshalJSON() ([]byte, error) {
type NoMethod I18nLanguageListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// I18nLanguageSnippet: Basic details about an i18n language, such as
// language code and human-readable name.
type I18nLanguageSnippet struct {
// Hl: A short BCP-47 code that uniquely identifies a language.
Hl string `json:"hl,omitempty"`
// Name: The human-readable name of the language in the language itself.
Name string `json:"name,omitempty"`
// ForceSendFields is a list of field names (e.g. "Hl") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Hl") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *I18nLanguageSnippet) MarshalJSON() ([]byte, error) {
type NoMethod I18nLanguageSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// I18nRegion: A i18nRegion resource identifies a region where YouTube
// is available.
type I18nRegion struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the i18n region.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#i18nRegion".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the i18n
// region, such as region code and human-readable name.
Snippet *I18nRegionSnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *I18nRegion) MarshalJSON() ([]byte, error) {
type NoMethod I18nRegion
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type I18nRegionListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of regions where YouTube is available. In this map, the
// i18n region ID is the map key, and its value is the corresponding
// i18nRegion resource.
Items []*I18nRegion `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#i18nRegionListResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *I18nRegionListResponse) MarshalJSON() ([]byte, error) {
type NoMethod I18nRegionListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// I18nRegionSnippet: Basic details about an i18n region, such as region
// code and human-readable name.
type I18nRegionSnippet struct {
// Gl: The region code as a 2-letter ISO country code.
Gl string `json:"gl,omitempty"`
// Name: The human-readable name of the region.
Name string `json:"name,omitempty"`
// ForceSendFields is a list of field names (e.g. "Gl") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Gl") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *I18nRegionSnippet) MarshalJSON() ([]byte, error) {
type NoMethod I18nRegionSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImageSettings: Branding properties for images associated with the
// channel.
type ImageSettings struct {
// BackgroundImageUrl: The URL for the background image shown on the
// video watch page. The image should be 1200px by 615px, with a maximum
// file size of 128k.
BackgroundImageUrl *LocalizedProperty `json:"backgroundImageUrl,omitempty"`
// BannerExternalUrl: This is used only in update requests; if it's set,
// we use this URL to generate all of the above banner URLs.
BannerExternalUrl string `json:"bannerExternalUrl,omitempty"`
// BannerImageUrl: Banner image. Desktop size (1060x175).
BannerImageUrl string `json:"bannerImageUrl,omitempty"`
// BannerMobileExtraHdImageUrl: Banner image. Mobile size high
// resolution (1440x395).
BannerMobileExtraHdImageUrl string `json:"bannerMobileExtraHdImageUrl,omitempty"`
// BannerMobileHdImageUrl: Banner image. Mobile size high resolution
// (1280x360).
BannerMobileHdImageUrl string `json:"bannerMobileHdImageUrl,omitempty"`
// BannerMobileImageUrl: Banner image. Mobile size (640x175).
BannerMobileImageUrl string `json:"bannerMobileImageUrl,omitempty"`
// BannerMobileLowImageUrl: Banner image. Mobile size low resolution
// (320x88).
BannerMobileLowImageUrl string `json:"bannerMobileLowImageUrl,omitempty"`
// BannerMobileMediumHdImageUrl: Banner image. Mobile size medium/high
// resolution (960x263).
BannerMobileMediumHdImageUrl string `json:"bannerMobileMediumHdImageUrl,omitempty"`
// BannerTabletExtraHdImageUrl: Banner image. Tablet size extra high
// resolution (2560x424).
BannerTabletExtraHdImageUrl string `json:"bannerTabletExtraHdImageUrl,omitempty"`
// BannerTabletHdImageUrl: Banner image. Tablet size high resolution
// (2276x377).
BannerTabletHdImageUrl string `json:"bannerTabletHdImageUrl,omitempty"`
// BannerTabletImageUrl: Banner image. Tablet size (1707x283).
BannerTabletImageUrl string `json:"bannerTabletImageUrl,omitempty"`
// BannerTabletLowImageUrl: Banner image. Tablet size low resolution
// (1138x188).
BannerTabletLowImageUrl string `json:"bannerTabletLowImageUrl,omitempty"`
// BannerTvHighImageUrl: Banner image. TV size high resolution
// (1920x1080).
BannerTvHighImageUrl string `json:"bannerTvHighImageUrl,omitempty"`
// BannerTvImageUrl: Banner image. TV size extra high resolution
// (2120x1192).
BannerTvImageUrl string `json:"bannerTvImageUrl,omitempty"`
// BannerTvLowImageUrl: Banner image. TV size low resolution (854x480).
BannerTvLowImageUrl string `json:"bannerTvLowImageUrl,omitempty"`
// BannerTvMediumImageUrl: Banner image. TV size medium resolution
// (1280x720).
BannerTvMediumImageUrl string `json:"bannerTvMediumImageUrl,omitempty"`
// LargeBrandedBannerImageImapScript: The image map script for the large
// banner image.
LargeBrandedBannerImageImapScript *LocalizedProperty `json:"largeBrandedBannerImageImapScript,omitempty"`
// LargeBrandedBannerImageUrl: The URL for the 854px by 70px image that
// appears below the video player in the expanded video view of the
// video watch page.
LargeBrandedBannerImageUrl *LocalizedProperty `json:"largeBrandedBannerImageUrl,omitempty"`
// SmallBrandedBannerImageImapScript: The image map script for the small
// banner image.
SmallBrandedBannerImageImapScript *LocalizedProperty `json:"smallBrandedBannerImageImapScript,omitempty"`
// SmallBrandedBannerImageUrl: The URL for the 640px by 70px banner
// image that appears below the video player in the default view of the
// video watch page.
SmallBrandedBannerImageUrl *LocalizedProperty `json:"smallBrandedBannerImageUrl,omitempty"`
// TrackingImageUrl: The URL for a 1px by 1px tracking pixel that can be
// used to collect statistics for views of the channel or video pages.
TrackingImageUrl string `json:"trackingImageUrl,omitempty"`
// WatchIconImageUrl: The URL for the image that appears above the
// top-left corner of the video player. This is a 25-pixel-high image
// with a flexible width that cannot exceed 170 pixels.
WatchIconImageUrl string `json:"watchIconImageUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "BackgroundImageUrl")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BackgroundImageUrl") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ImageSettings) MarshalJSON() ([]byte, error) {
type NoMethod ImageSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// IngestionInfo: Describes information necessary for ingesting an RTMP
// or an HTTP stream.
type IngestionInfo struct {
// BackupIngestionAddress: The backup ingestion URL that you should use
// to stream video to YouTube. You have the option of simultaneously
// streaming the content that you are sending to the ingestionAddress to
// this URL.
BackupIngestionAddress string `json:"backupIngestionAddress,omitempty"`
// IngestionAddress: The primary ingestion URL that you should use to
// stream video to YouTube. You must stream video to this
// URL.
//
// Depending on which application or tool you use to encode your video
// stream, you may need to enter the stream URL and stream name
// separately or you may need to concatenate them in the following
// format:
//
// STREAM_URL/STREAM_NAME
IngestionAddress string `json:"ingestionAddress,omitempty"`
// StreamName: The HTTP or RTMP stream name that YouTube assigns to the
// video stream.
StreamName string `json:"streamName,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "BackupIngestionAddress") to unconditionally include in API requests.
// By default, fields with empty values are omitted from API requests.
// However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BackupIngestionAddress")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *IngestionInfo) MarshalJSON() ([]byte, error) {
type NoMethod IngestionInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type InvideoBranding struct {
ImageBytes string `json:"imageBytes,omitempty"`
ImageUrl string `json:"imageUrl,omitempty"`
Position *InvideoPosition `json:"position,omitempty"`
TargetChannelId string `json:"targetChannelId,omitempty"`
Timing *InvideoTiming `json:"timing,omitempty"`
// ForceSendFields is a list of field names (e.g. "ImageBytes") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ImageBytes") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *InvideoBranding) MarshalJSON() ([]byte, error) {
type NoMethod InvideoBranding
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// InvideoPosition: Describes the spatial position of a visual widget
// inside a video. It is a union of various position types, out of which
// only will be set one.
type InvideoPosition struct {
// CornerPosition: Describes in which corner of the video the visual
// widget will appear.
//
// Possible values:
// "bottomLeft"
// "bottomRight"
// "topLeft"
// "topRight"
CornerPosition string `json:"cornerPosition,omitempty"`
// Type: Defines the position type.
//
// Possible values:
// "corner"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "CornerPosition") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CornerPosition") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *InvideoPosition) MarshalJSON() ([]byte, error) {
type NoMethod InvideoPosition
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// InvideoPromotion: Describes an invideo promotion campaign consisting
// of multiple promoted items. A campaign belongs to a single
// channel_id.
type InvideoPromotion struct {
// DefaultTiming: The default temporal position within the video where
// the promoted item will be displayed. Can be overriden by more
// specific timing in the item.
DefaultTiming *InvideoTiming `json:"defaultTiming,omitempty"`
// Items: List of promoted items in decreasing priority.
Items []*PromotedItem `json:"items,omitempty"`
// Position: The spatial position within the video where the promoted
// item will be displayed.
Position *InvideoPosition `json:"position,omitempty"`
// UseSmartTiming: Indicates whether the channel's promotional campaign
// uses "smart timing." This feature attempts to show promotions at a
// point in the video when they are more likely to be clicked and less
// likely to disrupt the viewing experience. This feature also picks up
// a single promotion to show on each video.
UseSmartTiming bool `json:"useSmartTiming,omitempty"`
// ForceSendFields is a list of field names (e.g. "DefaultTiming") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DefaultTiming") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *InvideoPromotion) MarshalJSON() ([]byte, error) {
type NoMethod InvideoPromotion
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// InvideoTiming: Describes a temporal position of a visual widget
// inside a video.
type InvideoTiming struct {
// DurationMs: Defines the duration in milliseconds for which the
// promotion should be displayed. If missing, the client should use the
// default.
DurationMs uint64 `json:"durationMs,omitempty,string"`
// OffsetMs: Defines the time at which the promotion will appear.
// Depending on the value of type the value of the offsetMs field will
// represent a time offset from the start or from the end of the video,
// expressed in milliseconds.
OffsetMs uint64 `json:"offsetMs,omitempty,string"`
// Type: Describes a timing type. If the value is offsetFromStart, then
// the offsetMs field represents an offset from the start of the video.
// If the value is offsetFromEnd, then the offsetMs field represents an
// offset from the end of the video.
//
// Possible values:
// "offsetFromEnd"
// "offsetFromStart"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "DurationMs") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DurationMs") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *InvideoTiming) MarshalJSON() ([]byte, error) {
type NoMethod InvideoTiming
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LanguageTag struct {
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Value") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Value") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LanguageTag) MarshalJSON() ([]byte, error) {
type NoMethod LanguageTag
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveBroadcast: A liveBroadcast resource represents an event that will
// be streamed, via live video, on YouTube.
type LiveBroadcast struct {
// ContentDetails: The contentDetails object contains information about
// the event's video content, such as whether the content can be shown
// in an embedded video player or if it will be archived and therefore
// available for viewing after the event has concluded.
ContentDetails *LiveBroadcastContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube assigns to uniquely identify the broadcast.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveBroadcast".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the event,
// including its title, description, start time, and end time.
Snippet *LiveBroadcastSnippet `json:"snippet,omitempty"`
// Statistics: The statistics object contains info about the event's
// current stats. These include concurrent viewers and total chat count.
// Statistics can change (in either direction) during the lifetime of an
// event. Statistics are only returned while the event is live.
Statistics *LiveBroadcastStatistics `json:"statistics,omitempty"`
// Status: The status object contains information about the event's
// status.
Status *LiveBroadcastStatus `json:"status,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ContentDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentDetails") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveBroadcast) MarshalJSON() ([]byte, error) {
type NoMethod LiveBroadcast
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveBroadcastContentDetails: Detailed settings of a broadcast.
type LiveBroadcastContentDetails struct {
// BoundStreamId: This value uniquely identifies the live stream bound
// to the broadcast.
BoundStreamId string `json:"boundStreamId,omitempty"`
// BoundStreamLastUpdateTimeMs: The date and time that the live stream
// referenced by boundStreamId was last updated.
BoundStreamLastUpdateTimeMs string `json:"boundStreamLastUpdateTimeMs,omitempty"`
// Possible values:
// "closedCaptionsDisabled"
// "closedCaptionsEmbedded"
// "closedCaptionsHttpPost"
ClosedCaptionsType string `json:"closedCaptionsType,omitempty"`
// EnableAutoStart: This setting indicates whether auto start is enabled
// for this broadcast.
EnableAutoStart bool `json:"enableAutoStart,omitempty"`
// EnableClosedCaptions: This setting indicates whether HTTP POST closed
// captioning is enabled for this broadcast. The ingestion URL of the
// closed captions is returned through the liveStreams API. This is
// mutually exclusive with using the closed_captions_type property, and
// is equivalent to setting closed_captions_type to
// CLOSED_CAPTIONS_HTTP_POST.
EnableClosedCaptions bool `json:"enableClosedCaptions,omitempty"`
// EnableContentEncryption: This setting indicates whether YouTube
// should enable content encryption for the broadcast.
EnableContentEncryption bool `json:"enableContentEncryption,omitempty"`
// EnableDvr: This setting determines whether viewers can access DVR
// controls while watching the video. DVR controls enable the viewer to
// control the video playback experience by pausing, rewinding, or fast
// forwarding content. The default value for this property is
// true.
//
//
//
// Important: You must set the value to true and also set the
// enableArchive property's value to true if you want to make playback
// available immediately after the broadcast ends.
EnableDvr bool `json:"enableDvr,omitempty"`
// EnableEmbed: This setting indicates whether the broadcast video can
// be played in an embedded player. If you choose to archive the video
// (using the enableArchive property), this setting will also apply to
// the archived video.
EnableEmbed bool `json:"enableEmbed,omitempty"`
// EnableLowLatency: Indicates whether this broadcast has low latency
// enabled.
EnableLowLatency bool `json:"enableLowLatency,omitempty"`
// LatencyPreference: If both this and enable_low_latency are set, they
// must match. LATENCY_NORMAL should match enable_low_latency=false
// LATENCY_LOW should match enable_low_latency=true LATENCY_ULTRA_LOW
// should have enable_low_latency omitted.
//
// Possible values:
// "low"
// "normal"
// "ultraLow"
LatencyPreference string `json:"latencyPreference,omitempty"`
Mesh string `json:"mesh,omitempty"`
// MonitorStream: The monitorStream object contains information about
// the monitor stream, which the broadcaster can use to review the event
// content before the broadcast stream is shown publicly.
MonitorStream *MonitorStreamInfo `json:"monitorStream,omitempty"`
// Projection: The projection format of this broadcast. This defaults to
// rectangular.
//
// Possible values:
// "360"
// "mesh"
// "rectangular"
Projection string `json:"projection,omitempty"`
// RecordFromStart: Automatically start recording after the event goes
// live. The default value for this property is true.
//
//
//
// Important: You must also set the enableDvr property's value to true
// if you want the playback to be available immediately after the
// broadcast ends. If you set this property's value to true but do not
// also set the enableDvr property to true, there may be a delay of
// around one day before the archived video will be available for
// playback.
RecordFromStart bool `json:"recordFromStart,omitempty"`
// StartWithSlate: This setting indicates whether the broadcast should
// automatically begin with an in-stream slate when you update the
// broadcast's status to live. After updating the status, you then need
// to send a liveCuepoints.insert request that sets the cuepoint's
// eventState to end to remove the in-stream slate and make your
// broadcast stream visible to viewers.
StartWithSlate bool `json:"startWithSlate,omitempty"`
// Possible values:
// "left_right"
// "mono"
// "top_bottom"
StereoLayout string `json:"stereoLayout,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundStreamId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundStreamId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveBroadcastContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveBroadcastContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveBroadcastListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of broadcasts that match the request criteria.
Items []*LiveBroadcast `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveBroadcastListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveBroadcastListResponse) MarshalJSON() ([]byte, error) {
type NoMethod LiveBroadcastListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveBroadcastSnippet struct {
// ActualEndTime: The date and time that the broadcast actually ended.
// This information is only available once the broadcast's state is
// complete. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
ActualEndTime string `json:"actualEndTime,omitempty"`
// ActualStartTime: The date and time that the broadcast actually
// started. This information is only available once the broadcast's
// state is live. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
ActualStartTime string `json:"actualStartTime,omitempty"`
// ChannelId: The ID that YouTube uses to uniquely identify the channel
// that is publishing the broadcast.
ChannelId string `json:"channelId,omitempty"`
// Description: The broadcast's description. As with the title, you can
// set this field by modifying the broadcast resource or by setting the
// description field of the corresponding video resource.
Description string `json:"description,omitempty"`
IsDefaultBroadcast bool `json:"isDefaultBroadcast,omitempty"`
// LiveChatId: The id of the live chat for this broadcast.
LiveChatId string `json:"liveChatId,omitempty"`
// PublishedAt: The date and time that the broadcast was added to
// YouTube's live broadcast schedule. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// ScheduledEndTime: The date and time that the broadcast is scheduled
// to end. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
ScheduledEndTime string `json:"scheduledEndTime,omitempty"`
// ScheduledStartTime: The date and time that the broadcast is scheduled
// to start. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
ScheduledStartTime string `json:"scheduledStartTime,omitempty"`
// Thumbnails: A map of thumbnail images associated with the broadcast.
// For each nested object in this object, the key is the name of the
// thumbnail image, and the value is an object that contains other
// information about the thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The broadcast's title. Note that the broadcast represents
// exactly one YouTube video. You can set this field by modifying the
// broadcast resource or by setting the title field of the corresponding
// video resource.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ActualEndTime") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ActualEndTime") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveBroadcastSnippet) MarshalJSON() ([]byte, error) {
type NoMethod LiveBroadcastSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveBroadcastStatistics: Statistics about the live broadcast. These
// represent a snapshot of the values at the time of the request.
// Statistics are only returned for live broadcasts.
type LiveBroadcastStatistics struct {
// ConcurrentViewers: The number of viewers currently watching the
// broadcast. The property and its value will be present if the
// broadcast has current viewers and the broadcast owner has not hidden
// the viewcount for the video. Note that YouTube stops tracking the
// number of concurrent viewers for a broadcast when the broadcast ends.
// So, this property would not identify the number of viewers watching
// an archived video of a live broadcast that already ended.
ConcurrentViewers uint64 `json:"concurrentViewers,omitempty,string"`
// TotalChatCount: The total number of live chat messages currently on
// the broadcast. The property and its value will be present if the
// broadcast is public, has the live chat feature enabled, and has at
// least one message. Note that this field will not be filled after the
// broadcast ends. So this property would not identify the number of
// chat messages for an archived video of a completed live broadcast.
TotalChatCount uint64 `json:"totalChatCount,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "ConcurrentViewers")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ConcurrentViewers") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveBroadcastStatistics) MarshalJSON() ([]byte, error) {
type NoMethod LiveBroadcastStatistics
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveBroadcastStatus struct {
// LifeCycleStatus: The broadcast's status. The status can be updated
// using the API's liveBroadcasts.transition method.
//
// Possible values:
// "abandoned"
// "complete"
// "completeStarting"
// "created"
// "live"
// "liveStarting"
// "ready"
// "reclaimed"
// "revoked"
// "testStarting"
// "testing"
LifeCycleStatus string `json:"lifeCycleStatus,omitempty"`
// LiveBroadcastPriority: Priority of the live broadcast event (internal
// state).
//
// Possible values:
// "high"
// "low"
// "normal"
LiveBroadcastPriority string `json:"liveBroadcastPriority,omitempty"`
// PrivacyStatus: The broadcast's privacy status. Note that the
// broadcast represents exactly one YouTube video, so the privacy
// settings are identical to those supported for videos. In addition,
// you can set this field by modifying the broadcast resource or by
// setting the privacyStatus field of the corresponding video resource.
//
// Possible values:
// "private"
// "public"
// "unlisted"
// "unlisted_new"
PrivacyStatus string `json:"privacyStatus,omitempty"`
// RecordingStatus: The broadcast's recording status.
//
// Possible values:
// "notRecording"
// "recorded"
// "recording"
RecordingStatus string `json:"recordingStatus,omitempty"`
// ForceSendFields is a list of field names (e.g. "LifeCycleStatus") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LifeCycleStatus") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveBroadcastStatus) MarshalJSON() ([]byte, error) {
type NoMethod LiveBroadcastStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveChatBan: A liveChatBan resource represents a ban for a YouTube
// live chat.
type LiveChatBan struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube assigns to uniquely identify the ban.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveChatBan".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the ban.
Snippet *LiveChatBanSnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatBan) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatBan
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatBanSnippet struct {
// BanDurationSeconds: The duration of a ban, only filled if the ban has
// type TEMPORARY.
BanDurationSeconds uint64 `json:"banDurationSeconds,omitempty,string"`
BannedUserDetails *ChannelProfileDetails `json:"bannedUserDetails,omitempty"`
// LiveChatId: The chat this ban is pertinent to.
LiveChatId string `json:"liveChatId,omitempty"`
// Type: The type of ban.
//
// Possible values:
// "permanent"
// "temporary"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "BanDurationSeconds")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BanDurationSeconds") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatBanSnippet) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatBanSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatFanFundingEventDetails struct {
// AmountDisplayString: A rendered string that displays the fund amount
// and currency to the user.
AmountDisplayString string `json:"amountDisplayString,omitempty"`
// AmountMicros: The amount of the fund.
AmountMicros uint64 `json:"amountMicros,omitempty,string"`
// Currency: The currency in which the fund was made.
Currency string `json:"currency,omitempty"`
// UserComment: The comment added by the user to this fan funding event.
UserComment string `json:"userComment,omitempty"`
// ForceSendFields is a list of field names (e.g. "AmountDisplayString")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AmountDisplayString") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatFanFundingEventDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatFanFundingEventDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveChatMessage: A liveChatMessage resource represents a chat message
// in a YouTube Live Chat.
type LiveChatMessage struct {
// AuthorDetails: The authorDetails object contains basic details about
// the user that posted this message.
AuthorDetails *LiveChatMessageAuthorDetails `json:"authorDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube assigns to uniquely identify the message.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveChatMessage".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the message.
Snippet *LiveChatMessageSnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "AuthorDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuthorDetails") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatMessage) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatMessage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatMessageAuthorDetails struct {
// ChannelId: The YouTube channel ID.
ChannelId string `json:"channelId,omitempty"`
// ChannelUrl: The channel's URL.
ChannelUrl string `json:"channelUrl,omitempty"`
// DisplayName: The channel's display name.
DisplayName string `json:"displayName,omitempty"`
// IsChatModerator: Whether the author is a moderator of the live chat.
IsChatModerator bool `json:"isChatModerator,omitempty"`
// IsChatOwner: Whether the author is the owner of the live chat.
IsChatOwner bool `json:"isChatOwner,omitempty"`
// IsChatSponsor: Whether the author is a sponsor of the live chat.
IsChatSponsor bool `json:"isChatSponsor,omitempty"`
// IsVerified: Whether the author's identity has been verified by
// YouTube.
IsVerified bool `json:"isVerified,omitempty"`
// ProfileImageUrl: The channels's avatar URL.
ProfileImageUrl string `json:"profileImageUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatMessageAuthorDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatMessageAuthorDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatMessageDeletedDetails struct {
DeletedMessageId string `json:"deletedMessageId,omitempty"`
// ForceSendFields is a list of field names (e.g. "DeletedMessageId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DeletedMessageId") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatMessageDeletedDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatMessageDeletedDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatMessageListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of live chat messages.
Items []*LiveChatMessage `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveChatMessageListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
// OfflineAt: The date and time when the underlying stream went offline.
// The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
OfflineAt string `json:"offlineAt,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PollingIntervalMillis: The amount of time the client should wait
// before polling again.
PollingIntervalMillis int64 `json:"pollingIntervalMillis,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatMessageListResponse) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatMessageListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatMessageRetractedDetails struct {
RetractedMessageId string `json:"retractedMessageId,omitempty"`
// ForceSendFields is a list of field names (e.g. "RetractedMessageId")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "RetractedMessageId") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatMessageRetractedDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatMessageRetractedDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatMessageSnippet struct {
// AuthorChannelId: The ID of the user that authored this message, this
// field is not always filled. textMessageEvent - the user that wrote
// the message fanFundingEvent - the user that funded the broadcast
// newSponsorEvent - the user that just became a sponsor
// messageDeletedEvent - the moderator that took the action
// messageRetractedEvent - the author that retracted their message
// userBannedEvent - the moderator that took the action superChatEvent -
// the user that made the purchase
AuthorChannelId string `json:"authorChannelId,omitempty"`
// DisplayMessage: Contains a string that can be displayed to the user.
// If this field is not present the message is silent, at the moment
// only messages of type TOMBSTONE and CHAT_ENDED_EVENT are silent.
DisplayMessage string `json:"displayMessage,omitempty"`
// FanFundingEventDetails: Details about the funding event, this is only
// set if the type is 'fanFundingEvent'.
FanFundingEventDetails *LiveChatFanFundingEventDetails `json:"fanFundingEventDetails,omitempty"`
// HasDisplayContent: Whether the message has display content that
// should be displayed to users.
HasDisplayContent bool `json:"hasDisplayContent,omitempty"`
LiveChatId string `json:"liveChatId,omitempty"`
MessageDeletedDetails *LiveChatMessageDeletedDetails `json:"messageDeletedDetails,omitempty"`
MessageRetractedDetails *LiveChatMessageRetractedDetails `json:"messageRetractedDetails,omitempty"`
PollClosedDetails *LiveChatPollClosedDetails `json:"pollClosedDetails,omitempty"`
PollEditedDetails *LiveChatPollEditedDetails `json:"pollEditedDetails,omitempty"`
PollOpenedDetails *LiveChatPollOpenedDetails `json:"pollOpenedDetails,omitempty"`
PollVotedDetails *LiveChatPollVotedDetails `json:"pollVotedDetails,omitempty"`
// PublishedAt: The date and time when the message was orignally
// published. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// SuperChatDetails: Details about the Super Chat event, this is only
// set if the type is 'superChatEvent'.
SuperChatDetails *LiveChatSuperChatDetails `json:"superChatDetails,omitempty"`
// TextMessageDetails: Details about the text message, this is only set
// if the type is 'textMessageEvent'.
TextMessageDetails *LiveChatTextMessageDetails `json:"textMessageDetails,omitempty"`
// Type: The type of message, this will always be present, it determines
// the contents of the message as well as which fields will be present.
//
// Possible values:
// "chatEndedEvent"
// "fanFundingEvent"
// "messageDeletedEvent"
// "messageRetractedEvent"
// "newSponsorEvent"
// "pollClosedEvent"
// "pollEditedEvent"
// "pollOpenedEvent"
// "pollVotedEvent"
// "sponsorOnlyModeEndedEvent"
// "sponsorOnlyModeStartedEvent"
// "superChatEvent"
// "textMessageEvent"
// "tombstone"
// "userBannedEvent"
Type string `json:"type,omitempty"`
UserBannedDetails *LiveChatUserBannedMessageDetails `json:"userBannedDetails,omitempty"`
// ForceSendFields is a list of field names (e.g. "AuthorChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuthorChannelId") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatMessageSnippet) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatMessageSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveChatModerator: A liveChatModerator resource represents a
// moderator for a YouTube live chat. A chat moderator has the ability
// to ban/unban users from a chat, remove message, etc.
type LiveChatModerator struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube assigns to uniquely identify the moderator.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveChatModerator".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the
// moderator.
Snippet *LiveChatModeratorSnippet `json:"snippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatModerator) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatModerator
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatModeratorListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of moderators that match the request criteria.
Items []*LiveChatModerator `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveChatModeratorListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatModeratorListResponse) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatModeratorListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatModeratorSnippet struct {
// LiveChatId: The ID of the live chat this moderator can act on.
LiveChatId string `json:"liveChatId,omitempty"`
// ModeratorDetails: Details about the moderator.
ModeratorDetails *ChannelProfileDetails `json:"moderatorDetails,omitempty"`
// ForceSendFields is a list of field names (e.g. "LiveChatId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LiveChatId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatModeratorSnippet) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatModeratorSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatPollClosedDetails struct {
// PollId: The id of the poll that was closed.
PollId string `json:"pollId,omitempty"`
// ForceSendFields is a list of field names (e.g. "PollId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PollId") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatPollClosedDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatPollClosedDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatPollEditedDetails struct {
Id string `json:"id,omitempty"`
Items []*LiveChatPollItem `json:"items,omitempty"`
Prompt string `json:"prompt,omitempty"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Id") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatPollEditedDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatPollEditedDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatPollItem struct {
// Description: Plain text description of the item.
Description string `json:"description,omitempty"`
ItemId string `json:"itemId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatPollItem) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatPollItem
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatPollOpenedDetails struct {
Id string `json:"id,omitempty"`
Items []*LiveChatPollItem `json:"items,omitempty"`
Prompt string `json:"prompt,omitempty"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Id") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatPollOpenedDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatPollOpenedDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatPollVotedDetails struct {
// ItemId: The poll item the user chose.
ItemId string `json:"itemId,omitempty"`
// PollId: The poll the user voted on.
PollId string `json:"pollId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ItemId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ItemId") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatPollVotedDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatPollVotedDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatSuperChatDetails struct {
// AmountDisplayString: A rendered string that displays the fund amount
// and currency to the user.
AmountDisplayString string `json:"amountDisplayString,omitempty"`
// AmountMicros: The amount purchased by the user, in micros (1,750,000
// micros = 1.75).
AmountMicros uint64 `json:"amountMicros,omitempty,string"`
// Currency: The currency in which the purchase was made.
Currency string `json:"currency,omitempty"`
// Tier: The tier in which the amount belongs to. Lower amounts belong
// to lower tiers. Starts at 1.
Tier int64 `json:"tier,omitempty"`
// UserComment: The comment added by the user to this Super Chat event.
UserComment string `json:"userComment,omitempty"`
// ForceSendFields is a list of field names (e.g. "AmountDisplayString")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AmountDisplayString") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatSuperChatDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatSuperChatDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatTextMessageDetails struct {
// MessageText: The user's message.
MessageText string `json:"messageText,omitempty"`
// ForceSendFields is a list of field names (e.g. "MessageText") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MessageText") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveChatTextMessageDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatTextMessageDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveChatUserBannedMessageDetails struct {
// BanDurationSeconds: The duration of the ban. This property is only
// present if the banType is temporary.
BanDurationSeconds uint64 `json:"banDurationSeconds,omitempty,string"`
// BanType: The type of ban.
//
// Possible values:
// "permanent"
// "temporary"
BanType string `json:"banType,omitempty"`
// BannedUserDetails: The details of the user that was banned.
BannedUserDetails *ChannelProfileDetails `json:"bannedUserDetails,omitempty"`
// ForceSendFields is a list of field names (e.g. "BanDurationSeconds")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BanDurationSeconds") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveChatUserBannedMessageDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveChatUserBannedMessageDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveStream: A live stream describes a live ingestion point.
type LiveStream struct {
// Cdn: The cdn object defines the live stream's content delivery
// network (CDN) settings. These settings provide details about the
// manner in which you stream your content to YouTube.
Cdn *CdnSettings `json:"cdn,omitempty"`
// ContentDetails: The content_details object contains information about
// the stream, including the closed captions ingestion URL.
ContentDetails *LiveStreamContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube assigns to uniquely identify the stream.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveStream".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the stream,
// including its channel, title, and description.
Snippet *LiveStreamSnippet `json:"snippet,omitempty"`
// Status: The status object contains information about live stream's
// status.
Status *LiveStreamStatus `json:"status,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Cdn") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Cdn") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveStream) MarshalJSON() ([]byte, error) {
type NoMethod LiveStream
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveStreamConfigurationIssue struct {
// Description: The long-form description of the issue and how to
// resolve it.
Description string `json:"description,omitempty"`
// Reason: The short-form reason for this issue.
Reason string `json:"reason,omitempty"`
// Severity: How severe this issue is to the stream.
//
// Possible values:
// "error"
// "info"
// "warning"
Severity string `json:"severity,omitempty"`
// Type: The kind of error happening.
//
// Possible values:
// "audioBitrateHigh"
// "audioBitrateLow"
// "audioBitrateMismatch"
// "audioCodec"
// "audioCodecMismatch"
// "audioSampleRate"
// "audioSampleRateMismatch"
// "audioStereoMismatch"
// "audioTooManyChannels"
// "badContainer"
// "bitrateHigh"
// "bitrateLow"
// "frameRateHigh"
// "framerateMismatch"
// "gopMismatch"
// "gopSizeLong"
// "gopSizeOver"
// "gopSizeShort"
// "interlacedVideo"
// "multipleAudioStreams"
// "multipleVideoStreams"
// "noAudioStream"
// "noVideoStream"
// "openGop"
// "resolutionMismatch"
// "videoBitrateMismatch"
// "videoCodec"
// "videoCodecMismatch"
// "videoIngestionFasterThanRealtime"
// "videoIngestionStarved"
// "videoInterlaceMismatch"
// "videoProfileMismatch"
// "videoResolutionSuboptimal"
// "videoResolutionUnsupported"
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveStreamConfigurationIssue) MarshalJSON() ([]byte, error) {
type NoMethod LiveStreamConfigurationIssue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveStreamContentDetails: Detailed settings of a stream.
type LiveStreamContentDetails struct {
// ClosedCaptionsIngestionUrl: The ingestion URL where the closed
// captions of this stream are sent.
ClosedCaptionsIngestionUrl string `json:"closedCaptionsIngestionUrl,omitempty"`
// IsReusable: Indicates whether the stream is reusable, which means
// that it can be bound to multiple broadcasts. It is common for
// broadcasters to reuse the same stream for many different broadcasts
// if those broadcasts occur at different times.
//
// If you set this value to false, then the stream will not be reusable,
// which means that it can only be bound to one broadcast. Non-reusable
// streams differ from reusable streams in the following ways:
// - A non-reusable stream can only be bound to one broadcast.
// - A non-reusable stream might be deleted by an automated process
// after the broadcast ends.
// - The liveStreams.list method does not list non-reusable streams if
// you call the method and set the mine parameter to true. The only way
// to use that method to retrieve the resource for a non-reusable stream
// is to use the id parameter to identify the stream.
IsReusable bool `json:"isReusable,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "ClosedCaptionsIngestionUrl") to unconditionally include in API
// requests. By default, fields with empty values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "ClosedCaptionsIngestionUrl") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveStreamContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod LiveStreamContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveStreamHealthStatus struct {
// ConfigurationIssues: The configurations issues on this stream
ConfigurationIssues []*LiveStreamConfigurationIssue `json:"configurationIssues,omitempty"`
// LastUpdateTimeSeconds: The last time this status was updated (in
// seconds)
LastUpdateTimeSeconds uint64 `json:"lastUpdateTimeSeconds,omitempty,string"`
// Status: The status code of this stream
//
// Possible values:
// "bad"
// "good"
// "noData"
// "ok"
// "revoked"
Status string `json:"status,omitempty"`
// ForceSendFields is a list of field names (e.g. "ConfigurationIssues")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ConfigurationIssues") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *LiveStreamHealthStatus) MarshalJSON() ([]byte, error) {
type NoMethod LiveStreamHealthStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveStreamListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of live streams that match the request criteria.
Items []*LiveStream `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#liveStreamListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveStreamListResponse) MarshalJSON() ([]byte, error) {
type NoMethod LiveStreamListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LiveStreamSnippet struct {
// ChannelId: The ID that YouTube uses to uniquely identify the channel
// that is transmitting the stream.
ChannelId string `json:"channelId,omitempty"`
// Description: The stream's description. The value cannot be longer
// than 10000 characters.
Description string `json:"description,omitempty"`
IsDefaultStream bool `json:"isDefaultStream,omitempty"`
// PublishedAt: The date and time that the stream was created. The value
// is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// Title: The stream's title. The value must be between 1 and 128
// characters long.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveStreamSnippet) MarshalJSON() ([]byte, error) {
type NoMethod LiveStreamSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LiveStreamStatus: Brief description of the live stream status.
type LiveStreamStatus struct {
// HealthStatus: The health status of the stream.
HealthStatus *LiveStreamHealthStatus `json:"healthStatus,omitempty"`
// Possible values:
// "active"
// "created"
// "error"
// "inactive"
// "ready"
StreamStatus string `json:"streamStatus,omitempty"`
// ForceSendFields is a list of field names (e.g. "HealthStatus") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "HealthStatus") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LiveStreamStatus) MarshalJSON() ([]byte, error) {
type NoMethod LiveStreamStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LocalizedProperty struct {
Default string `json:"default,omitempty"`
// DefaultLanguage: The language of the default property.
DefaultLanguage *LanguageTag `json:"defaultLanguage,omitempty"`
Localized []*LocalizedString `json:"localized,omitempty"`
// ForceSendFields is a list of field names (e.g. "Default") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Default") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LocalizedProperty) MarshalJSON() ([]byte, error) {
type NoMethod LocalizedProperty
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type LocalizedString struct {
Language string `json:"language,omitempty"`
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Language") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Language") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LocalizedString) MarshalJSON() ([]byte, error) {
type NoMethod LocalizedString
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// MonitorStreamInfo: Settings and Info of the monitor stream
type MonitorStreamInfo struct {
// BroadcastStreamDelayMs: If you have set the enableMonitorStream
// property to true, then this property determines the length of the
// live broadcast delay.
BroadcastStreamDelayMs int64 `json:"broadcastStreamDelayMs,omitempty"`
// EmbedHtml: HTML code that embeds a player that plays the monitor
// stream.
EmbedHtml string `json:"embedHtml,omitempty"`
// EnableMonitorStream: This value determines whether the monitor stream
// is enabled for the broadcast. If the monitor stream is enabled, then
// YouTube will broadcast the event content on a special stream intended
// only for the broadcaster's consumption. The broadcaster can use the
// stream to review the event content and also to identify the optimal
// times to insert cuepoints.
//
// You need to set this value to true if you intend to have a broadcast
// delay for your event.
//
// Note: This property cannot be updated once the broadcast is in the
// testing or live state.
EnableMonitorStream bool `json:"enableMonitorStream,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "BroadcastStreamDelayMs") to unconditionally include in API requests.
// By default, fields with empty values are omitted from API requests.
// However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BroadcastStreamDelayMs")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *MonitorStreamInfo) MarshalJSON() ([]byte, error) {
type NoMethod MonitorStreamInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Nonprofit: Nonprofit information.
type Nonprofit struct {
// NonprofitId: Id of the nonprofit.
NonprofitId *NonprofitId `json:"nonprofitId,omitempty"`
// NonprofitLegalName: Legal name of the nonprofit.
NonprofitLegalName string `json:"nonprofitLegalName,omitempty"`
// ForceSendFields is a list of field names (e.g. "NonprofitId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NonprofitId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Nonprofit) MarshalJSON() ([]byte, error) {
type NoMethod Nonprofit
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type NonprofitId struct {
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Value") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Value") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *NonprofitId) MarshalJSON() ([]byte, error) {
type NoMethod NonprofitId
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PageInfo: Paging details for lists of resources, including total
// number of items available and number of resources returned in a
// single page.
type PageInfo struct {
// ResultsPerPage: The number of results included in the API response.
ResultsPerPage int64 `json:"resultsPerPage,omitempty"`
// TotalResults: The total number of results in the result set.
TotalResults int64 `json:"totalResults,omitempty"`
// ForceSendFields is a list of field names (e.g. "ResultsPerPage") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ResultsPerPage") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *PageInfo) MarshalJSON() ([]byte, error) {
type NoMethod PageInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Playlist: A playlist resource represents a YouTube playlist. A
// playlist is a collection of videos that can be viewed sequentially
// and shared with other users. A playlist can contain up to 200 videos,
// and YouTube does not limit the number of playlists that each user
// creates. By default, playlists are publicly visible to other users,
// but playlists can be public or private.
//
// YouTube also uses playlists to identify special collections of videos
// for a channel, such as:
// - uploaded videos
// - favorite videos
// - positively rated (liked) videos
// - watch history
// - watch later To be more specific, these lists are associated with a
// channel, which is a collection of a person, group, or company's
// videos, playlists, and other YouTube information. You can retrieve
// the playlist IDs for each of these lists from the channel resource
// for a given channel.
//
// You can then use the playlistItems.list method to retrieve any of
// those lists. You can also add or remove items from those lists by
// calling the playlistItems.insert and playlistItems.delete
// methods.
type Playlist struct {
// ContentDetails: The contentDetails object contains information like
// video count.
ContentDetails *PlaylistContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the playlist.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#playlist".
Kind string `json:"kind,omitempty"`
// Localizations: Localizations for different languages
Localizations map[string]PlaylistLocalization `json:"localizations,omitempty"`
// Player: The player object contains information that you would use to
// play the playlist in an embedded player.
Player *PlaylistPlayer `json:"player,omitempty"`
// Snippet: The snippet object contains basic details about the
// playlist, such as its title and description.
Snippet *PlaylistSnippet `json:"snippet,omitempty"`
// Status: The status object contains status information for the
// playlist.
Status *PlaylistStatus `json:"status,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ContentDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentDetails") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *Playlist) MarshalJSON() ([]byte, error) {
type NoMethod Playlist
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PlaylistContentDetails struct {
// ItemCount: The number of videos in the playlist.
ItemCount int64 `json:"itemCount,omitempty"`
// ForceSendFields is a list of field names (e.g. "ItemCount") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ItemCount") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PlaylistItem: A playlistItem resource identifies another resource,
// such as a video, that is included in a playlist. In addition, the
// playlistItem resource contains details about the included resource
// that pertain specifically to how that resource is used in that
// playlist.
//
// YouTube uses playlists to identify special collections of videos for
// a channel, such as:
// - uploaded videos
// - favorite videos
// - positively rated (liked) videos
// - watch history
// - watch later To be more specific, these lists are associated with a
// channel, which is a collection of a person, group, or company's
// videos, playlists, and other YouTube information.
//
// You can retrieve the playlist IDs for each of these lists from the
// channel resource for a given channel. You can then use the
// playlistItems.list method to retrieve any of those lists. You can
// also add or remove items from those lists by calling the
// playlistItems.insert and playlistItems.delete methods. For example,
// if a user gives a positive rating to a video, you would insert that
// video into the liked videos playlist for that user's channel.
type PlaylistItem struct {
// ContentDetails: The contentDetails object is included in the resource
// if the included item is a YouTube video. The object contains
// additional information about the video.
ContentDetails *PlaylistItemContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the playlist item.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#playlistItem".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the playlist
// item, such as its title and position in the playlist.
Snippet *PlaylistItemSnippet `json:"snippet,omitempty"`
// Status: The status object contains information about the playlist
// item's privacy status.
Status *PlaylistItemStatus `json:"status,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ContentDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentDetails") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *PlaylistItem) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistItem
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PlaylistItemContentDetails struct {
// EndAt: The time, measured in seconds from the start of the video,
// when the video should stop playing. (The playlist owner can specify
// the times when the video should start and stop playing when the video
// is played in the context of the playlist.) By default, assume that
// the video.endTime is the end of the video.
EndAt string `json:"endAt,omitempty"`
// Note: A user-generated note for this item.
Note string `json:"note,omitempty"`
// StartAt: The time, measured in seconds from the start of the video,
// when the video should start playing. (The playlist owner can specify
// the times when the video should start and stop playing when the video
// is played in the context of the playlist.) The default value is 0.
StartAt string `json:"startAt,omitempty"`
// VideoId: The ID that YouTube uses to uniquely identify a video. To
// retrieve the video resource, set the id query parameter to this value
// in your API request.
VideoId string `json:"videoId,omitempty"`
// VideoPublishedAt: The date and time that the video was published to
// YouTube. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
VideoPublishedAt string `json:"videoPublishedAt,omitempty"`
// ForceSendFields is a list of field names (e.g. "EndAt") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EndAt") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistItemContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistItemContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PlaylistItemListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of playlist items that match the request criteria.
Items []*PlaylistItem `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#playlistItemListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistItemListResponse) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistItemListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PlaylistItemSnippet: Basic details about a playlist, including title,
// description and thumbnails.
type PlaylistItemSnippet struct {
// ChannelId: The ID that YouTube uses to uniquely identify the user
// that added the item to the playlist.
ChannelId string `json:"channelId,omitempty"`
// ChannelTitle: Channel title for the channel that the playlist item
// belongs to.
ChannelTitle string `json:"channelTitle,omitempty"`
// Description: The item's description.
Description string `json:"description,omitempty"`
// PlaylistId: The ID that YouTube uses to uniquely identify the
// playlist that the playlist item is in.
PlaylistId string `json:"playlistId,omitempty"`
// Position: The order in which the item appears in the playlist. The
// value uses a zero-based index, so the first item has a position of 0,
// the second item has a position of 1, and so forth.
Position int64 `json:"position,omitempty"`
// PublishedAt: The date and time that the item was added to the
// playlist. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
PublishedAt string `json:"publishedAt,omitempty"`
// ResourceId: The id object contains information that can be used to
// uniquely identify the resource that is included in the playlist as
// the playlist item.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// Thumbnails: A map of thumbnail images associated with the playlist
// item. For each object in the map, the key is the name of the
// thumbnail image, and the value is an object that contains other
// information about the thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The item's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistItemSnippet) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistItemSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PlaylistItemStatus: Information about the playlist item's privacy
// status.
type PlaylistItemStatus struct {
// PrivacyStatus: This resource's privacy status.
//
// Possible values:
// "private"
// "public"
// "unlisted"
// "unlisted_new"
PrivacyStatus string `json:"privacyStatus,omitempty"`
// ForceSendFields is a list of field names (e.g. "PrivacyStatus") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PrivacyStatus") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistItemStatus) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistItemStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PlaylistListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of playlists that match the request criteria.
Items []*Playlist `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#playlistListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistListResponse) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PlaylistLocalization: Playlist localization setting
type PlaylistLocalization struct {
// Description: The localized strings for playlist's description.
Description string `json:"description,omitempty"`
// Title: The localized strings for playlist's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistLocalization) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistLocalization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PlaylistPlayer struct {
// EmbedHtml: An <iframe> tag that embeds a player that will play the
// playlist.
EmbedHtml string `json:"embedHtml,omitempty"`
// ForceSendFields is a list of field names (e.g. "EmbedHtml") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EmbedHtml") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistPlayer) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistPlayer
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PlaylistSnippet: Basic details about a playlist, including title,
// description and thumbnails.
type PlaylistSnippet struct {
// ChannelId: The ID that YouTube uses to uniquely identify the channel
// that published the playlist.
ChannelId string `json:"channelId,omitempty"`
// ChannelTitle: The channel title of the channel that the video belongs
// to.
ChannelTitle string `json:"channelTitle,omitempty"`
// DefaultLanguage: The language of the playlist's default title and
// description.
DefaultLanguage string `json:"defaultLanguage,omitempty"`
// Description: The playlist's description.
Description string `json:"description,omitempty"`
// Localized: Localized title and description, read-only.
Localized *PlaylistLocalization `json:"localized,omitempty"`
// PublishedAt: The date and time that the playlist was created. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// Tags: Keyword tags associated with the playlist.
Tags []string `json:"tags,omitempty"`
// Thumbnails: A map of thumbnail images associated with the playlist.
// For each object in the map, the key is the name of the thumbnail
// image, and the value is an object that contains other information
// about the thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The playlist's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistSnippet) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PlaylistStatus struct {
// PrivacyStatus: The playlist's privacy status.
//
// Possible values:
// "private"
// "public"
// "unlisted"
// "unlisted_new"
PrivacyStatus string `json:"privacyStatus,omitempty"`
// ForceSendFields is a list of field names (e.g. "PrivacyStatus") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PrivacyStatus") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PlaylistStatus) MarshalJSON() ([]byte, error) {
type NoMethod PlaylistStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PromotedItem: Describes a single promoted item.
type PromotedItem struct {
// CustomMessage: A custom message to display for this promotion. This
// field is currently ignored unless the promoted item is a website.
CustomMessage string `json:"customMessage,omitempty"`
// Id: Identifies the promoted item.
Id *PromotedItemId `json:"id,omitempty"`
// PromotedByContentOwner: If true, the content owner's name will be
// used when displaying the promotion. This field can only be set when
// the update is made on behalf of the content owner.
PromotedByContentOwner bool `json:"promotedByContentOwner,omitempty"`
// Timing: The temporal position within the video where the promoted
// item will be displayed. If present, it overrides the default timing.
Timing *InvideoTiming `json:"timing,omitempty"`
// ForceSendFields is a list of field names (e.g. "CustomMessage") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CustomMessage") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PromotedItem) MarshalJSON() ([]byte, error) {
type NoMethod PromotedItem
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PromotedItemId: Describes a single promoted item id. It is a union of
// various possible types.
type PromotedItemId struct {
// RecentlyUploadedBy: If type is recentUpload, this field identifies
// the channel from which to take the recent upload. If missing, the
// channel is assumed to be the same channel for which the
// invideoPromotion is set.
RecentlyUploadedBy string `json:"recentlyUploadedBy,omitempty"`
// Type: Describes the type of the promoted item.
//
// Possible values:
// "recentUpload"
// "video"
// "website"
Type string `json:"type,omitempty"`
// VideoId: If the promoted item represents a video, this field
// represents the unique YouTube ID identifying it. This field will be
// present only if type has the value video.
VideoId string `json:"videoId,omitempty"`
// WebsiteUrl: If the promoted item represents a website, this field
// represents the url pointing to the website. This field will be
// present only if type has the value website.
WebsiteUrl string `json:"websiteUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "RecentlyUploadedBy")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "RecentlyUploadedBy") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *PromotedItemId) MarshalJSON() ([]byte, error) {
type NoMethod PromotedItemId
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PropertyValue: A pair Property / Value.
type PropertyValue struct {
// Property: A property.
Property string `json:"property,omitempty"`
// Value: The property's value.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Property") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Property") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PropertyValue) MarshalJSON() ([]byte, error) {
type NoMethod PropertyValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ResourceId: A resource id is a generic reference that points to
// another YouTube resource.
type ResourceId struct {
// ChannelId: The ID that YouTube uses to uniquely identify the referred
// resource, if that resource is a channel. This property is only
// present if the resourceId.kind value is youtube#channel.
ChannelId string `json:"channelId,omitempty"`
// Kind: The type of the API resource.
Kind string `json:"kind,omitempty"`
// PlaylistId: The ID that YouTube uses to uniquely identify the
// referred resource, if that resource is a playlist. This property is
// only present if the resourceId.kind value is youtube#playlist.
PlaylistId string `json:"playlistId,omitempty"`
// VideoId: The ID that YouTube uses to uniquely identify the referred
// resource, if that resource is a video. This property is only present
// if the resourceId.kind value is youtube#video.
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ResourceId) MarshalJSON() ([]byte, error) {
type NoMethod ResourceId
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type SearchListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of results that match the search criteria.
Items []*SearchResult `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#searchListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
RegionCode string `json:"regionCode,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SearchListResponse) MarshalJSON() ([]byte, error) {
type NoMethod SearchListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SearchResult: A search result contains information about a YouTube
// video, channel, or playlist that matches the search parameters
// specified in an API request. While a search result points to a
// uniquely identifiable resource, like a video, it does not have its
// own persistent data.
type SearchResult struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The id object contains information that can be used to uniquely
// identify the resource that matches the search request.
Id *ResourceId `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#searchResult".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about a search
// result, such as its title or description. For example, if the search
// result is a video, then the title will be the video's title and the
// description will be the video's description.
Snippet *SearchResultSnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SearchResult) MarshalJSON() ([]byte, error) {
type NoMethod SearchResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SearchResultSnippet: Basic details about a search result, including
// title, description and thumbnails of the item referenced by the
// search result.
type SearchResultSnippet struct {
// ChannelId: The value that YouTube uses to uniquely identify the
// channel that published the resource that the search result
// identifies.
ChannelId string `json:"channelId,omitempty"`
// ChannelTitle: The title of the channel that published the resource
// that the search result identifies.
ChannelTitle string `json:"channelTitle,omitempty"`
// Description: A description of the search result.
Description string `json:"description,omitempty"`
// LiveBroadcastContent: It indicates if the resource (video or channel)
// has upcoming/active live broadcast content. Or it's "none" if there
// is not any upcoming/active live broadcasts.
//
// Possible values:
// "live"
// "none"
// "upcoming"
LiveBroadcastContent string `json:"liveBroadcastContent,omitempty"`
// PublishedAt: The creation date and time of the resource that the
// search result identifies. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// Thumbnails: A map of thumbnail images associated with the search
// result. For each object in the map, the key is the name of the
// thumbnail image, and the value is an object that contains other
// information about the thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The title of the search result.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SearchResultSnippet) MarshalJSON() ([]byte, error) {
type NoMethod SearchResultSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Sponsor: A sponsor resource represents a sponsor for a YouTube
// channel. A sponsor provides recurring monetary support to a creator
// and receives special benefits.
type Sponsor struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#sponsor".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the sponsor.
Snippet *SponsorSnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Sponsor) MarshalJSON() ([]byte, error) {
type NoMethod Sponsor
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type SponsorListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of sponsors that match the request criteria.
Items []*Sponsor `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#sponsorListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SponsorListResponse) MarshalJSON() ([]byte, error) {
type NoMethod SponsorListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type SponsorSnippet struct {
// ChannelId: The id of the channel being sponsored.
ChannelId string `json:"channelId,omitempty"`
// CumulativeDurationMonths: The cumulative time a user has been a
// sponsor in months.
CumulativeDurationMonths int64 `json:"cumulativeDurationMonths,omitempty"`
// SponsorDetails: Details about the sponsor.
SponsorDetails *ChannelProfileDetails `json:"sponsorDetails,omitempty"`
// SponsorSince: The date and time when the user became a sponsor. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
SponsorSince string `json:"sponsorSince,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SponsorSnippet) MarshalJSON() ([]byte, error) {
type NoMethod SponsorSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Subscription: A subscription resource contains information about a
// YouTube user subscription. A subscription notifies a user when new
// videos are added to a channel or when another user takes one of
// several actions on YouTube, such as uploading a video, rating a
// video, or commenting on a video.
type Subscription struct {
// ContentDetails: The contentDetails object contains basic statistics
// about the subscription.
ContentDetails *SubscriptionContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the subscription.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#subscription".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the
// subscription, including its title and the channel that the user
// subscribed to.
Snippet *SubscriptionSnippet `json:"snippet,omitempty"`
// SubscriberSnippet: The subscriberSnippet object contains basic
// details about the sbuscriber.
SubscriberSnippet *SubscriptionSubscriberSnippet `json:"subscriberSnippet,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ContentDetails") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ContentDetails") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *Subscription) MarshalJSON() ([]byte, error) {
type NoMethod Subscription
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SubscriptionContentDetails: Details about the content to witch a
// subscription refers.
type SubscriptionContentDetails struct {
// ActivityType: The type of activity this subscription is for (only
// uploads, everything).
//
// Possible values:
// "all"
// "uploads"
ActivityType string `json:"activityType,omitempty"`
// NewItemCount: The number of new items in the subscription since its
// content was last read.
NewItemCount int64 `json:"newItemCount,omitempty"`
// TotalItemCount: The approximate number of items that the subscription
// points to.
TotalItemCount int64 `json:"totalItemCount,omitempty"`
// ForceSendFields is a list of field names (e.g. "ActivityType") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ActivityType") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SubscriptionContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod SubscriptionContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type SubscriptionListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of subscriptions that match the request criteria.
Items []*Subscription `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#subscriptionListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SubscriptionListResponse) MarshalJSON() ([]byte, error) {
type NoMethod SubscriptionListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SubscriptionSnippet: Basic details about a subscription, including
// title, description and thumbnails of the subscribed item.
type SubscriptionSnippet struct {
// ChannelId: The ID that YouTube uses to uniquely identify the
// subscriber's channel.
ChannelId string `json:"channelId,omitempty"`
// ChannelTitle: Channel title for the channel that the subscription
// belongs to.
ChannelTitle string `json:"channelTitle,omitempty"`
// Description: The subscription's details.
Description string `json:"description,omitempty"`
// PublishedAt: The date and time that the subscription was created. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// ResourceId: The id object contains information about the channel that
// the user subscribed to.
ResourceId *ResourceId `json:"resourceId,omitempty"`
// Thumbnails: A map of thumbnail images associated with the video. For
// each object in the map, the key is the name of the thumbnail image,
// and the value is an object that contains other information about the
// thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The subscription's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SubscriptionSnippet) MarshalJSON() ([]byte, error) {
type NoMethod SubscriptionSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SubscriptionSubscriberSnippet: Basic details about a subscription's
// subscriber including title, description, channel ID and thumbnails.
type SubscriptionSubscriberSnippet struct {
// ChannelId: The channel ID of the subscriber.
ChannelId string `json:"channelId,omitempty"`
// Description: The description of the subscriber.
Description string `json:"description,omitempty"`
// Thumbnails: Thumbnails for this subscriber.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The title of the subscriber.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChannelId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChannelId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SubscriptionSubscriberSnippet) MarshalJSON() ([]byte, error) {
type NoMethod SubscriptionSubscriberSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SuperChatEvent: A superChatEvent resource represents a Super Chat
// purchase on a YouTube channel.
type SuperChatEvent struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube assigns to uniquely identify the Super Chat
// event.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#superChatEvent".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the Super
// Chat event.
Snippet *SuperChatEventSnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SuperChatEvent) MarshalJSON() ([]byte, error) {
type NoMethod SuperChatEvent
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type SuperChatEventListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of Super Chat purchases that match the request
// criteria.
Items []*SuperChatEvent `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#superChatEventListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SuperChatEventListResponse) MarshalJSON() ([]byte, error) {
type NoMethod SuperChatEventListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type SuperChatEventSnippet struct {
// AmountMicros: The purchase amount, in micros of the purchase
// currency. e.g., 1 is represented as 1000000.
AmountMicros uint64 `json:"amountMicros,omitempty,string"`
// ChannelId: Channel id where the event occurred.
ChannelId string `json:"channelId,omitempty"`
// CommentText: The text contents of the comment left by the user.
CommentText string `json:"commentText,omitempty"`
// CreatedAt: The date and time when the event occurred. The value is
// specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
CreatedAt string `json:"createdAt,omitempty"`
// Currency: The currency in which the purchase was made. ISO 4217.
Currency string `json:"currency,omitempty"`
// DisplayString: A rendered string that displays the purchase amount
// and currency (e.g., "$1.00"). The string is rendered for the given
// language.
DisplayString string `json:"displayString,omitempty"`
// IsSuperChatForGood: True if this event is a Super Chat for Good
// purchase.
IsSuperChatForGood bool `json:"isSuperChatForGood,omitempty"`
// MessageType: The tier for the paid message, which is based on the
// amount of money spent to purchase the message.
MessageType int64 `json:"messageType,omitempty"`
// Nonprofit: If this event is a Super Chat for Good purchase, this
// field will contain information about the charity the purchase is
// donated to.
Nonprofit *Nonprofit `json:"nonprofit,omitempty"`
// SupporterDetails: Details about the supporter.
SupporterDetails *ChannelProfileDetails `json:"supporterDetails,omitempty"`
// ForceSendFields is a list of field names (e.g. "AmountMicros") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AmountMicros") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SuperChatEventSnippet) MarshalJSON() ([]byte, error) {
type NoMethod SuperChatEventSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Thumbnail: A thumbnail is an image representing a YouTube resource.
type Thumbnail struct {
// Height: (Optional) Height of the thumbnail image.
Height int64 `json:"height,omitempty"`
// Url: The thumbnail image's URL.
Url string `json:"url,omitempty"`
// Width: (Optional) Width of the thumbnail image.
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Height") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Height") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Thumbnail) MarshalJSON() ([]byte, error) {
type NoMethod Thumbnail
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ThumbnailDetails: Internal representation of thumbnails for a YouTube
// resource.
type ThumbnailDetails struct {
// Default: The default image for this resource.
Default *Thumbnail `json:"default,omitempty"`
// High: The high quality image for this resource.
High *Thumbnail `json:"high,omitempty"`
// Maxres: The maximum resolution quality image for this resource.
Maxres *Thumbnail `json:"maxres,omitempty"`
// Medium: The medium quality image for this resource.
Medium *Thumbnail `json:"medium,omitempty"`
// Standard: The standard quality image for this resource.
Standard *Thumbnail `json:"standard,omitempty"`
// ForceSendFields is a list of field names (e.g. "Default") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Default") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ThumbnailDetails) MarshalJSON() ([]byte, error) {
type NoMethod ThumbnailDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ThumbnailSetResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of thumbnails.
Items []*ThumbnailDetails `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#thumbnailSetResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ThumbnailSetResponse) MarshalJSON() ([]byte, error) {
type NoMethod ThumbnailSetResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TokenPagination: Stub token pagination template to suppress results.
type TokenPagination struct {
}
// Video: A video resource represents a YouTube video.
type Video struct {
// AgeGating: Age restriction details related to a video. This data can
// only be retrieved by the video owner.
AgeGating *VideoAgeGating `json:"ageGating,omitempty"`
// ContentDetails: The contentDetails object contains information about
// the video content, including the length of the video and its aspect
// ratio.
ContentDetails *VideoContentDetails `json:"contentDetails,omitempty"`
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// FileDetails: The fileDetails object encapsulates information about
// the video file that was uploaded to YouTube, including the file's
// resolution, duration, audio and video codecs, stream bitrates, and
// more. This data can only be retrieved by the video owner.
FileDetails *VideoFileDetails `json:"fileDetails,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the video.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#video".
Kind string `json:"kind,omitempty"`
// LiveStreamingDetails: The liveStreamingDetails object contains
// metadata about a live video broadcast. The object will only be
// present in a video resource if the video is an upcoming, live, or
// completed live broadcast.
LiveStreamingDetails *VideoLiveStreamingDetails `json:"liveStreamingDetails,omitempty"`
// Localizations: List with all localizations.
Localizations map[string]VideoLocalization `json:"localizations,omitempty"`
// MonetizationDetails: The monetizationDetails object encapsulates
// information about the monetization status of the video.
MonetizationDetails *VideoMonetizationDetails `json:"monetizationDetails,omitempty"`
// Player: The player object contains information that you would use to
// play the video in an embedded player.
Player *VideoPlayer `json:"player,omitempty"`
// ProcessingDetails: The processingDetails object encapsulates
// information about YouTube's progress in processing the uploaded video
// file. The properties in the object identify the current processing
// status and an estimate of the time remaining until YouTube finishes
// processing the video. This part also indicates whether different
// types of data or content, such as file details or thumbnail images,
// are available for the video.
//
// The processingProgress object is designed to be polled so that the
// video uploaded can track the progress that YouTube has made in
// processing the uploaded video file. This data can only be retrieved
// by the video owner.
ProcessingDetails *VideoProcessingDetails `json:"processingDetails,omitempty"`
// ProjectDetails: The projectDetails object contains information about
// the project specific video metadata.
ProjectDetails *VideoProjectDetails `json:"projectDetails,omitempty"`
// RecordingDetails: The recordingDetails object encapsulates
// information about the location, date and address where the video was
// recorded.
RecordingDetails *VideoRecordingDetails `json:"recordingDetails,omitempty"`
// Snippet: The snippet object contains basic details about the video,
// such as its title, description, and category.
Snippet *VideoSnippet `json:"snippet,omitempty"`
// Statistics: The statistics object contains statistics about the
// video.
Statistics *VideoStatistics `json:"statistics,omitempty"`
// Status: The status object contains information about the video's
// uploading, processing, and privacy statuses.
Status *VideoStatus `json:"status,omitempty"`
// Suggestions: The suggestions object encapsulates suggestions that
// identify opportunities to improve the video quality or the metadata
// for the uploaded video. This data can only be retrieved by the video
// owner.
Suggestions *VideoSuggestions `json:"suggestions,omitempty"`
// TopicDetails: The topicDetails object encapsulates information about
// Freebase topics associated with the video.
TopicDetails *VideoTopicDetails `json:"topicDetails,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "AgeGating") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AgeGating") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Video) MarshalJSON() ([]byte, error) {
type NoMethod Video
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoAbuseReport struct {
// Comments: Additional comments regarding the abuse report.
Comments string `json:"comments,omitempty"`
// Language: The language that the content was viewed in.
Language string `json:"language,omitempty"`
// ReasonId: The high-level, or primary, reason that the content is
// abusive. The value is an abuse report reason ID.
ReasonId string `json:"reasonId,omitempty"`
// SecondaryReasonId: The specific, or secondary, reason that this
// content is abusive (if available). The value is an abuse report
// reason ID that is a valid secondary reason for the primary reason.
SecondaryReasonId string `json:"secondaryReasonId,omitempty"`
// VideoId: The ID that YouTube uses to uniquely identify the video.
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Comments") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Comments") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoAbuseReport) MarshalJSON() ([]byte, error) {
type NoMethod VideoAbuseReport
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoAbuseReportReason: A videoAbuseReportReason resource identifies
// a reason that a video could be reported as abusive. Video abuse
// report reasons are used with video.ReportAbuse.
type VideoAbuseReportReason struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID of this abuse report reason.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#videoAbuseReportReason".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the abuse
// report reason.
Snippet *VideoAbuseReportReasonSnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoAbuseReportReason) MarshalJSON() ([]byte, error) {
type NoMethod VideoAbuseReportReason
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoAbuseReportReasonListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of valid abuse reasons that are used with
// video.ReportAbuse.
Items []*VideoAbuseReportReason `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#videoAbuseReportReasonListResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoAbuseReportReasonListResponse) MarshalJSON() ([]byte, error) {
type NoMethod VideoAbuseReportReasonListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoAbuseReportReasonSnippet: Basic details about a video category,
// such as its localized title.
type VideoAbuseReportReasonSnippet struct {
// Label: The localized label belonging to this abuse report reason.
Label string `json:"label,omitempty"`
// SecondaryReasons: The secondary reasons associated with this reason,
// if any are available. (There might be 0 or more.)
SecondaryReasons []*VideoAbuseReportSecondaryReason `json:"secondaryReasons,omitempty"`
// ForceSendFields is a list of field names (e.g. "Label") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Label") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoAbuseReportReasonSnippet) MarshalJSON() ([]byte, error) {
type NoMethod VideoAbuseReportReasonSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoAbuseReportSecondaryReason struct {
// Id: The ID of this abuse report secondary reason.
Id string `json:"id,omitempty"`
// Label: The localized label for this abuse report secondary reason.
Label string `json:"label,omitempty"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Id") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoAbuseReportSecondaryReason) MarshalJSON() ([]byte, error) {
type NoMethod VideoAbuseReportSecondaryReason
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoAgeGating struct {
// AlcoholContent: Indicates whether or not the video has alcoholic
// beverage content. Only users of legal purchasing age in a particular
// country, as identified by ICAP, can view the content.
AlcoholContent bool `json:"alcoholContent,omitempty"`
// Restricted: Age-restricted trailers. For redband trailers and
// adult-rated video-games. Only users aged 18+ can view the content.
// The the field is true the content is restricted to viewers aged 18+.
// Otherwise The field won't be present.
Restricted bool `json:"restricted,omitempty"`
// VideoGameRating: Video game rating, if any.
//
// Possible values:
// "anyone"
// "m15Plus"
// "m16Plus"
// "m17Plus"
VideoGameRating string `json:"videoGameRating,omitempty"`
// ForceSendFields is a list of field names (e.g. "AlcoholContent") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AlcoholContent") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *VideoAgeGating) MarshalJSON() ([]byte, error) {
type NoMethod VideoAgeGating
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoCategory: A videoCategory resource identifies a category that
// has been or could be associated with uploaded videos.
type VideoCategory struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// Id: The ID that YouTube uses to uniquely identify the video category.
Id string `json:"id,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#videoCategory".
Kind string `json:"kind,omitempty"`
// Snippet: The snippet object contains basic details about the video
// category, including its title.
Snippet *VideoCategorySnippet `json:"snippet,omitempty"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoCategory) MarshalJSON() ([]byte, error) {
type NoMethod VideoCategory
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoCategoryListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of video categories that can be associated with YouTube
// videos. In this map, the video category ID is the map key, and its
// value is the corresponding videoCategory resource.
Items []*VideoCategory `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#videoCategoryListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoCategoryListResponse) MarshalJSON() ([]byte, error) {
type NoMethod VideoCategoryListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoCategorySnippet: Basic details about a video category, such as
// its localized title.
type VideoCategorySnippet struct {
Assignable bool `json:"assignable,omitempty"`
// ChannelId: The YouTube channel that created the video category.
ChannelId string `json:"channelId,omitempty"`
// Title: The video category's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Assignable") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Assignable") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoCategorySnippet) MarshalJSON() ([]byte, error) {
type NoMethod VideoCategorySnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoContentDetails: Details about the content of a YouTube Video.
type VideoContentDetails struct {
// Caption: The value of captions indicates whether the video has
// captions or not.
//
// Possible values:
// "false"
// "true"
Caption string `json:"caption,omitempty"`
// ContentRating: Specifies the ratings that the video received under
// various rating schemes.
ContentRating *ContentRating `json:"contentRating,omitempty"`
// CountryRestriction: The countryRestriction object contains
// information about the countries where a video is (or is not)
// viewable.
CountryRestriction *AccessPolicy `json:"countryRestriction,omitempty"`
// Definition: The value of definition indicates whether the video is
// available in high definition or only in standard definition.
//
// Possible values:
// "hd"
// "sd"
Definition string `json:"definition,omitempty"`
// Dimension: The value of dimension indicates whether the video is
// available in 3D or in 2D.
Dimension string `json:"dimension,omitempty"`
// Duration: The length of the video. The tag value is an ISO 8601
// duration in the format PT#M#S, in which the letters PT indicate that
// the value specifies a period of time, and the letters M and S refer
// to length in minutes and seconds, respectively. The # characters
// preceding the M and S letters are both integers that specify the
// number of minutes (or seconds) of the video. For example, a value of
// PT15M51S indicates that the video is 15 minutes and 51 seconds long.
Duration string `json:"duration,omitempty"`
// HasCustomThumbnail: Indicates whether the video uploader has provided
// a custom thumbnail image for the video. This property is only visible
// to the video uploader.
HasCustomThumbnail bool `json:"hasCustomThumbnail,omitempty"`
// LicensedContent: The value of is_license_content indicates whether
// the video is licensed content.
LicensedContent bool `json:"licensedContent,omitempty"`
// Projection: Specifies the projection format of the video.
//
// Possible values:
// "360"
// "rectangular"
Projection string `json:"projection,omitempty"`
// RegionRestriction: The regionRestriction object contains information
// about the countries where a video is (or is not) viewable. The object
// will contain either the contentDetails.regionRestriction.allowed
// property or the contentDetails.regionRestriction.blocked property.
RegionRestriction *VideoContentDetailsRegionRestriction `json:"regionRestriction,omitempty"`
// ForceSendFields is a list of field names (e.g. "Caption") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Caption") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoContentDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoContentDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoContentDetailsRegionRestriction: DEPRECATED Region restriction
// of the video.
type VideoContentDetailsRegionRestriction struct {
// Allowed: A list of region codes that identify countries where the
// video is viewable. If this property is present and a country is not
// listed in its value, then the video is blocked from appearing in that
// country. If this property is present and contains an empty list, the
// video is blocked in all countries.
Allowed []string `json:"allowed,omitempty"`
// Blocked: A list of region codes that identify countries where the
// video is blocked. If this property is present and a country is not
// listed in its value, then the video is viewable in that country. If
// this property is present and contains an empty list, the video is
// viewable in all countries.
Blocked []string `json:"blocked,omitempty"`
// ForceSendFields is a list of field names (e.g. "Allowed") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Allowed") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoContentDetailsRegionRestriction) MarshalJSON() ([]byte, error) {
type NoMethod VideoContentDetailsRegionRestriction
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoFileDetails: Describes original video file properties, including
// technical details about audio and video streams, but also metadata
// information like content length, digitization time, or geotagging
// information.
type VideoFileDetails struct {
// AudioStreams: A list of audio streams contained in the uploaded video
// file. Each item in the list contains detailed metadata about an audio
// stream.
AudioStreams []*VideoFileDetailsAudioStream `json:"audioStreams,omitempty"`
// BitrateBps: The uploaded video file's combined (video and audio)
// bitrate in bits per second.
BitrateBps uint64 `json:"bitrateBps,omitempty,string"`
// Container: The uploaded video file's container format.
Container string `json:"container,omitempty"`
// CreationTime: The date and time when the uploaded video file was
// created. The value is specified in ISO 8601 format. Currently, the
// following ISO 8601 formats are supported:
// - Date only: YYYY-MM-DD
// - Naive time: YYYY-MM-DDTHH:MM:SS
// - Time with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM
CreationTime string `json:"creationTime,omitempty"`
// DurationMs: The length of the uploaded video in milliseconds.
DurationMs uint64 `json:"durationMs,omitempty,string"`
// FileName: The uploaded file's name. This field is present whether a
// video file or another type of file was uploaded.
FileName string `json:"fileName,omitempty"`
// FileSize: The uploaded file's size in bytes. This field is present
// whether a video file or another type of file was uploaded.
FileSize uint64 `json:"fileSize,omitempty,string"`
// FileType: The uploaded file's type as detected by YouTube's video
// processing engine. Currently, YouTube only processes video files, but
// this field is present whether a video file or another type of file
// was uploaded.
//
// Possible values:
// "archive"
// "audio"
// "document"
// "image"
// "other"
// "project"
// "video"
FileType string `json:"fileType,omitempty"`
// VideoStreams: A list of video streams contained in the uploaded video
// file. Each item in the list contains detailed metadata about a video
// stream.
VideoStreams []*VideoFileDetailsVideoStream `json:"videoStreams,omitempty"`
// ForceSendFields is a list of field names (e.g. "AudioStreams") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AudioStreams") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoFileDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoFileDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoFileDetailsAudioStream: Information about an audio stream.
type VideoFileDetailsAudioStream struct {
// BitrateBps: The audio stream's bitrate, in bits per second.
BitrateBps uint64 `json:"bitrateBps,omitempty,string"`
// ChannelCount: The number of audio channels that the stream contains.
ChannelCount int64 `json:"channelCount,omitempty"`
// Codec: The audio codec that the stream uses.
Codec string `json:"codec,omitempty"`
// Vendor: A value that uniquely identifies a video vendor. Typically,
// the value is a four-letter vendor code.
Vendor string `json:"vendor,omitempty"`
// ForceSendFields is a list of field names (e.g. "BitrateBps") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BitrateBps") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoFileDetailsAudioStream) MarshalJSON() ([]byte, error) {
type NoMethod VideoFileDetailsAudioStream
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoFileDetailsVideoStream: Information about a video stream.
type VideoFileDetailsVideoStream struct {
// AspectRatio: The video content's display aspect ratio, which
// specifies the aspect ratio in which the video should be displayed.
AspectRatio float64 `json:"aspectRatio,omitempty"`
// BitrateBps: The video stream's bitrate, in bits per second.
BitrateBps uint64 `json:"bitrateBps,omitempty,string"`
// Codec: The video codec that the stream uses.
Codec string `json:"codec,omitempty"`
// FrameRateFps: The video stream's frame rate, in frames per second.
FrameRateFps float64 `json:"frameRateFps,omitempty"`
// HeightPixels: The encoded video content's height in pixels.
HeightPixels int64 `json:"heightPixels,omitempty"`
// Rotation: The amount that YouTube needs to rotate the original source
// content to properly display the video.
//
// Possible values:
// "clockwise"
// "counterClockwise"
// "none"
// "other"
// "upsideDown"
Rotation string `json:"rotation,omitempty"`
// Vendor: A value that uniquely identifies a video vendor. Typically,
// the value is a four-letter vendor code.
Vendor string `json:"vendor,omitempty"`
// WidthPixels: The encoded video content's width in pixels. You can
// calculate the video's encoding aspect ratio as
// width_pixels / height_pixels.
WidthPixels int64 `json:"widthPixels,omitempty"`
// ForceSendFields is a list of field names (e.g. "AspectRatio") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AspectRatio") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoFileDetailsVideoStream) MarshalJSON() ([]byte, error) {
type NoMethod VideoFileDetailsVideoStream
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *VideoFileDetailsVideoStream) UnmarshalJSON(data []byte) error {
type NoMethod VideoFileDetailsVideoStream
var s1 struct {
AspectRatio gensupport.JSONFloat64 `json:"aspectRatio"`
FrameRateFps gensupport.JSONFloat64 `json:"frameRateFps"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.AspectRatio = float64(s1.AspectRatio)
s.FrameRateFps = float64(s1.FrameRateFps)
return nil
}
type VideoGetRatingResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of ratings that match the request criteria.
Items []*VideoRating `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#videoGetRatingResponse".
Kind string `json:"kind,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoGetRatingResponse) MarshalJSON() ([]byte, error) {
type NoMethod VideoGetRatingResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoListResponse struct {
// Etag: Etag of this resource.
Etag string `json:"etag,omitempty"`
// EventId: Serialized EventId of the request which produced this
// response.
EventId string `json:"eventId,omitempty"`
// Items: A list of videos that match the request criteria.
Items []*Video `json:"items,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "youtube#videoListResponse".
Kind string `json:"kind,omitempty"`
// NextPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the next page in the result set.
NextPageToken string `json:"nextPageToken,omitempty"`
PageInfo *PageInfo `json:"pageInfo,omitempty"`
// PrevPageToken: The token that can be used as the value of the
// pageToken parameter to retrieve the previous page in the result set.
PrevPageToken string `json:"prevPageToken,omitempty"`
TokenPagination *TokenPagination `json:"tokenPagination,omitempty"`
// VisitorId: The visitorId identifies the visitor.
VisitorId string `json:"visitorId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Etag") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Etag") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoListResponse) MarshalJSON() ([]byte, error) {
type NoMethod VideoListResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoLiveStreamingDetails: Details about the live streaming metadata.
type VideoLiveStreamingDetails struct {
// ActiveLiveChatId: The ID of the currently active live chat attached
// to this video. This field is filled only if the video is a currently
// live broadcast that has live chat. Once the broadcast transitions to
// complete this field will be removed and the live chat closed down.
// For persistent broadcasts that live chat id will no longer be tied to
// this video but rather to the new video being displayed at the
// persistent page.
ActiveLiveChatId string `json:"activeLiveChatId,omitempty"`
// ActualEndTime: The time that the broadcast actually ended. The value
// is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. This value
// will not be available until the broadcast is over.
ActualEndTime string `json:"actualEndTime,omitempty"`
// ActualStartTime: The time that the broadcast actually started. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. This
// value will not be available until the broadcast begins.
ActualStartTime string `json:"actualStartTime,omitempty"`
// ConcurrentViewers: The number of viewers currently watching the
// broadcast. The property and its value will be present if the
// broadcast has current viewers and the broadcast owner has not hidden
// the viewcount for the video. Note that YouTube stops tracking the
// number of concurrent viewers for a broadcast when the broadcast ends.
// So, this property would not identify the number of viewers watching
// an archived video of a live broadcast that already ended.
ConcurrentViewers uint64 `json:"concurrentViewers,omitempty,string"`
// ScheduledEndTime: The time that the broadcast is scheduled to end.
// The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
// If the value is empty or the property is not present, then the
// broadcast is scheduled to continue indefinitely.
ScheduledEndTime string `json:"scheduledEndTime,omitempty"`
// ScheduledStartTime: The time that the broadcast is scheduled to
// begin. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ)
// format.
ScheduledStartTime string `json:"scheduledStartTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "ActiveLiveChatId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ActiveLiveChatId") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *VideoLiveStreamingDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoLiveStreamingDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoLocalization: Localized versions of certain video properties
// (e.g. title).
type VideoLocalization struct {
// Description: Localized version of the video's description.
Description string `json:"description,omitempty"`
// Title: Localized version of the video's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoLocalization) MarshalJSON() ([]byte, error) {
type NoMethod VideoLocalization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoMonetizationDetails: Details about monetization of a YouTube
// Video.
type VideoMonetizationDetails struct {
// Access: The value of access indicates whether the video can be
// monetized or not.
Access *AccessPolicy `json:"access,omitempty"`
// ForceSendFields is a list of field names (e.g. "Access") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Access") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoMonetizationDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoMonetizationDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoPlayer: Player to be used for a video playback.
type VideoPlayer struct {
EmbedHeight int64 `json:"embedHeight,omitempty,string"`
// EmbedHtml: An <iframe> tag that embeds a player that will play the
// video.
EmbedHtml string `json:"embedHtml,omitempty"`
// EmbedWidth: The embed width
EmbedWidth int64 `json:"embedWidth,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "EmbedHeight") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EmbedHeight") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoPlayer) MarshalJSON() ([]byte, error) {
type NoMethod VideoPlayer
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoProcessingDetails: Describes processing status and progress and
// availability of some other Video resource parts.
type VideoProcessingDetails struct {
// EditorSuggestionsAvailability: This value indicates whether video
// editing suggestions, which might improve video quality or the
// playback experience, are available for the video. You can retrieve
// these suggestions by requesting the suggestions part in your
// videos.list() request.
EditorSuggestionsAvailability string `json:"editorSuggestionsAvailability,omitempty"`
// FileDetailsAvailability: This value indicates whether file details
// are available for the uploaded video. You can retrieve a video's file
// details by requesting the fileDetails part in your videos.list()
// request.
FileDetailsAvailability string `json:"fileDetailsAvailability,omitempty"`
// ProcessingFailureReason: The reason that YouTube failed to process
// the video. This property will only have a value if the
// processingStatus property's value is failed.
//
// Possible values:
// "other"
// "streamingFailed"
// "transcodeFailed"
// "uploadFailed"
ProcessingFailureReason string `json:"processingFailureReason,omitempty"`
// ProcessingIssuesAvailability: This value indicates whether the video
// processing engine has generated suggestions that might improve
// YouTube's ability to process the the video, warnings that explain
// video processing problems, or errors that cause video processing
// problems. You can retrieve these suggestions by requesting the
// suggestions part in your videos.list() request.
ProcessingIssuesAvailability string `json:"processingIssuesAvailability,omitempty"`
// ProcessingProgress: The processingProgress object contains
// information about the progress YouTube has made in processing the
// video. The values are really only relevant if the video's processing
// status is processing.
ProcessingProgress *VideoProcessingDetailsProcessingProgress `json:"processingProgress,omitempty"`
// ProcessingStatus: The video's processing status. This value indicates
// whether YouTube was able to process the video or if the video is
// still being processed.
//
// Possible values:
// "failed"
// "processing"
// "succeeded"
// "terminated"
ProcessingStatus string `json:"processingStatus,omitempty"`
// TagSuggestionsAvailability: This value indicates whether keyword
// (tag) suggestions are available for the video. Tags can be added to a
// video's metadata to make it easier for other users to find the video.
// You can retrieve these suggestions by requesting the suggestions part
// in your videos.list() request.
TagSuggestionsAvailability string `json:"tagSuggestionsAvailability,omitempty"`
// ThumbnailsAvailability: This value indicates whether thumbnail images
// have been generated for the video.
ThumbnailsAvailability string `json:"thumbnailsAvailability,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "EditorSuggestionsAvailability") to unconditionally include in API
// requests. By default, fields with empty values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "EditorSuggestionsAvailability") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoProcessingDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoProcessingDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoProcessingDetailsProcessingProgress: Video processing progress
// and completion time estimate.
type VideoProcessingDetailsProcessingProgress struct {
// PartsProcessed: The number of parts of the video that YouTube has
// already processed. You can estimate the percentage of the video that
// YouTube has already processed by calculating:
// 100 * parts_processed / parts_total
//
// Note that since the estimated number of parts could increase without
// a corresponding increase in the number of parts that have already
// been processed, it is possible that the calculated progress could
// periodically decrease while YouTube processes a video.
PartsProcessed uint64 `json:"partsProcessed,omitempty,string"`
// PartsTotal: An estimate of the total number of parts that need to be
// processed for the video. The number may be updated with more precise
// estimates while YouTube processes the video.
PartsTotal uint64 `json:"partsTotal,omitempty,string"`
// TimeLeftMs: An estimate of the amount of time, in millseconds, that
// YouTube needs to finish processing the video.
TimeLeftMs uint64 `json:"timeLeftMs,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "PartsProcessed") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PartsProcessed") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *VideoProcessingDetailsProcessingProgress) MarshalJSON() ([]byte, error) {
type NoMethod VideoProcessingDetailsProcessingProgress
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoProjectDetails: Project specific details about the content of a
// YouTube Video.
type VideoProjectDetails struct {
// Tags: A list of project tags associated with the video during the
// upload.
Tags []string `json:"tags,omitempty"`
// ForceSendFields is a list of field names (e.g. "Tags") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Tags") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoProjectDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoProjectDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type VideoRating struct {
// Possible values:
// "dislike"
// "like"
// "none"
// "unspecified"
Rating string `json:"rating,omitempty"`
VideoId string `json:"videoId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Rating") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Rating") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoRating) MarshalJSON() ([]byte, error) {
type NoMethod VideoRating
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoRecordingDetails: Recording information associated with the
// video.
type VideoRecordingDetails struct {
// Location: The geolocation information associated with the video.
Location *GeoPoint `json:"location,omitempty"`
// LocationDescription: The text description of the location where the
// video was recorded.
LocationDescription string `json:"locationDescription,omitempty"`
// RecordingDate: The date and time when the video was recorded. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sssZ) format.
RecordingDate string `json:"recordingDate,omitempty"`
// ForceSendFields is a list of field names (e.g. "Location") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Location") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoRecordingDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoRecordingDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoSnippet: Basic details about a video, including title,
// description, uploader, thumbnails and category.
type VideoSnippet struct {
// CategoryId: The YouTube video category associated with the video.
CategoryId string `json:"categoryId,omitempty"`
// ChannelId: The ID that YouTube uses to uniquely identify the channel
// that the video was uploaded to.
ChannelId string `json:"channelId,omitempty"`
// ChannelTitle: Channel title for the channel that the video belongs
// to.
ChannelTitle string `json:"channelTitle,omitempty"`
// DefaultAudioLanguage: The default_audio_language property specifies
// the language spoken in the video's default audio track.
DefaultAudioLanguage string `json:"defaultAudioLanguage,omitempty"`
// DefaultLanguage: The language of the videos's default snippet.
DefaultLanguage string `json:"defaultLanguage,omitempty"`
// Description: The video's description.
Description string `json:"description,omitempty"`
// LiveBroadcastContent: Indicates if the video is an upcoming/active
// live broadcast. Or it's "none" if the video is not an upcoming/active
// live broadcast.
//
// Possible values:
// "live"
// "none"
// "upcoming"
LiveBroadcastContent string `json:"liveBroadcastContent,omitempty"`
// Localized: Localized snippet selected with the hl parameter. If no
// such localization exists, this field is populated with the default
// snippet. (Read-only)
Localized *VideoLocalization `json:"localized,omitempty"`
// PublishedAt: The date and time that the video was uploaded. The value
// is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishedAt string `json:"publishedAt,omitempty"`
// Tags: A list of keyword tags associated with the video. Tags may
// contain spaces.
Tags []string `json:"tags,omitempty"`
// Thumbnails: A map of thumbnail images associated with the video. For
// each object in the map, the key is the name of the thumbnail image,
// and the value is an object that contains other information about the
// thumbnail.
Thumbnails *ThumbnailDetails `json:"thumbnails,omitempty"`
// Title: The video's title.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "CategoryId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CategoryId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoSnippet) MarshalJSON() ([]byte, error) {
type NoMethod VideoSnippet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoStatistics: Statistics about the video, such as the number of
// times the video was viewed or liked.
type VideoStatistics struct {
// CommentCount: The number of comments for the video.
CommentCount uint64 `json:"commentCount,omitempty,string"`
// DislikeCount: The number of users who have indicated that they
// disliked the video by giving it a negative rating.
DislikeCount uint64 `json:"dislikeCount,omitempty,string"`
// FavoriteCount: The number of users who currently have the video
// marked as a favorite video.
FavoriteCount uint64 `json:"favoriteCount,omitempty,string"`
// LikeCount: The number of users who have indicated that they liked the
// video by giving it a positive rating.
LikeCount uint64 `json:"likeCount,omitempty,string"`
// ViewCount: The number of times the video has been viewed.
ViewCount uint64 `json:"viewCount,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "CommentCount") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CommentCount") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoStatistics) MarshalJSON() ([]byte, error) {
type NoMethod VideoStatistics
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoStatus: Basic details about a video category, such as its
// localized title.
type VideoStatus struct {
// Embeddable: This value indicates if the video can be embedded on
// another website.
Embeddable bool `json:"embeddable,omitempty"`
// FailureReason: This value explains why a video failed to upload. This
// property is only present if the uploadStatus property indicates that
// the upload failed.
//
// Possible values:
// "codec"
// "conversion"
// "emptyFile"
// "invalidFile"
// "tooSmall"
// "uploadAborted"
FailureReason string `json:"failureReason,omitempty"`
// License: The video's license.
//
// Possible values:
// "creativeCommon"
// "youtube"
License string `json:"license,omitempty"`
// PrivacyStatus: The video's privacy status.
//
// Possible values:
// "private"
// "public"
// "unlisted"
// "unlisted_new"
PrivacyStatus string `json:"privacyStatus,omitempty"`
// PublicStatsViewable: This value indicates if the extended video
// statistics on the watch page can be viewed by everyone. Note that the
// view count, likes, etc will still be visible if this is disabled.
PublicStatsViewable bool `json:"publicStatsViewable,omitempty"`
// PublishAt: The date and time when the video is scheduled to publish.
// It can be set only if the privacy status of the video is private. The
// value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
PublishAt string `json:"publishAt,omitempty"`
// RejectionReason: This value explains why YouTube rejected an uploaded
// video. This property is only present if the uploadStatus property
// indicates that the upload was rejected.
//
// Possible values:
// "claim"
// "copyright"
// "duplicate"
// "inappropriate"
// "legal"
// "length"
// "termsOfUse"
// "trademark"
// "uploaderAccountClosed"
// "uploaderAccountSuspended"
RejectionReason string `json:"rejectionReason,omitempty"`
// UploadStatus: The status of the uploaded video.
//
// Possible values:
// "deleted"
// "failed"
// "processed"
// "rejected"
// "uploaded"
UploadStatus string `json:"uploadStatus,omitempty"`
// ForceSendFields is a list of field names (e.g. "Embeddable") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Embeddable") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VideoStatus) MarshalJSON() ([]byte, error) {
type NoMethod VideoStatus
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoSuggestions: Specifies suggestions on how to improve video
// content, including encoding hints, tag suggestions, and editor
// suggestions.
type VideoSuggestions struct {
// EditorSuggestions: A list of video editing operations that might
// improve the video quality or playback experience of the uploaded
// video.
//
// Possible values:
// "audioQuietAudioSwap"
// "videoAutoLevels"
// "videoCrop"
// "videoStabilize"
EditorSuggestions []string `json:"editorSuggestions,omitempty"`
// ProcessingErrors: A list of errors that will prevent YouTube from
// successfully processing the uploaded video video. These errors
// indicate that, regardless of the video's current processing status,
// eventually, that status will almost certainly be failed.
//
// Possible values:
// "archiveFile"
// "audioFile"
// "docFile"
// "imageFile"
// "notAVideoFile"
// "projectFile"
// "unsupportedSpatialAudioLayout"
ProcessingErrors []string `json:"processingErrors,omitempty"`
// ProcessingHints: A list of suggestions that may improve YouTube's
// ability to process the video.
//
// Possible values:
// "hdrVideo"
// "nonStreamableMov"
// "sendBestQualityVideo"
// "spatialAudio"
// "sphericalVideo"
// "vrVideo"
ProcessingHints []string `json:"processingHints,omitempty"`
// ProcessingWarnings: A list of reasons why YouTube may have difficulty
// transcoding the uploaded video or that might result in an erroneous
// transcoding. These warnings are generated before YouTube actually
// processes the uploaded video file. In addition, they identify issues
// that are unlikely to cause the video processing to fail but that
// might cause problems such as sync issues, video artifacts, or a
// missing audio track.
//
// Possible values:
// "hasEditlist"
// "inconsistentResolution"
// "problematicAudioCodec"
// "problematicHdrLookupTable"
// "problematicVideoCodec"
// "unknownAudioCodec"
// "unknownContainer"
// "unknownVideoCodec"
// "unsupportedHdrColorMetadata"
// "unsupportedHdrPixelFormat"
// "unsupportedSphericalProjectionType"
// "unsupportedVrStereoMode"
ProcessingWarnings []string `json:"processingWarnings,omitempty"`
// TagSuggestions: A list of keyword tags that could be added to the
// video's metadata to increase the likelihood that users will locate
// your video when searching or browsing on YouTube.
TagSuggestions []*VideoSuggestionsTagSuggestion `json:"tagSuggestions,omitempty"`
// ForceSendFields is a list of field names (e.g. "EditorSuggestions")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EditorSuggestions") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *VideoSuggestions) MarshalJSON() ([]byte, error) {
type NoMethod VideoSuggestions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoSuggestionsTagSuggestion: A single tag suggestion with it's
// relevance information.
type VideoSuggestionsTagSuggestion struct {
// CategoryRestricts: A set of video categories for which the tag is
// relevant. You can use this information to display appropriate tag
// suggestions based on the video category that the video uploader
// associates with the video. By default, tag suggestions are relevant
// for all categories if there are no restricts defined for the keyword.
CategoryRestricts []string `json:"categoryRestricts,omitempty"`
// Tag: The keyword tag suggested for the video.
Tag string `json:"tag,omitempty"`
// ForceSendFields is a list of field names (e.g. "CategoryRestricts")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CategoryRestricts") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *VideoSuggestionsTagSuggestion) MarshalJSON() ([]byte, error) {
type NoMethod VideoSuggestionsTagSuggestion
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// VideoTopicDetails: Freebase topic information related to the video.
type VideoTopicDetails struct {
// RelevantTopicIds: Similar to topic_id, except that these topics are
// merely relevant to the video. These are topics that may be mentioned
// in, or appear in the video. You can retrieve information about each
// topic using Freebase Topic API.
RelevantTopicIds []string `json:"relevantTopicIds,omitempty"`
// TopicCategories: A list of Wikipedia URLs that provide a high-level
// description of the video's content.
TopicCategories []string `json:"topicCategories,omitempty"`
// TopicIds: A list of Freebase topic IDs that are centrally associated
// with the video. These are topics that are centrally featured in the
// video, and it can be said that the video is mainly about each of
// these. You can retrieve information about each topic using the
// Freebase Topic API.
TopicIds []string `json:"topicIds,omitempty"`
// ForceSendFields is a list of field names (e.g. "RelevantTopicIds") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "RelevantTopicIds") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *VideoTopicDetails) MarshalJSON() ([]byte, error) {
type NoMethod VideoTopicDetails
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// WatchSettings: Branding properties for the watch. All deprecated.
type WatchSettings struct {
// BackgroundColor: The text color for the video watch page's branded
// area.
BackgroundColor string `json:"backgroundColor,omitempty"`
// FeaturedPlaylistId: An ID that uniquely identifies a playlist that
// displays next to the video player.
FeaturedPlaylistId string `json:"featuredPlaylistId,omitempty"`
// TextColor: The background color for the video watch page's branded
// area.
TextColor string `json:"textColor,omitempty"`
// ForceSendFields is a list of field names (e.g. "BackgroundColor") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BackgroundColor") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *WatchSettings) MarshalJSON() ([]byte, error) {
type NoMethod WatchSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// method id "youtube.activities.insert":
type ActivitiesInsertCall struct {
s *Service
activity *Activity
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Posts a bulletin for a specific channel. (The user submitting
// the request must be authorized to act on the channel's
// behalf.)
//
// Note: Even though an activity resource can contain information about
// actions like a user rating a video or marking a video as a favorite,
// you need to use other API methods to generate those activity
// resources. For example, you would use the API's videos.rate() method
// to rate a video and the playlistItems.insert() method to mark a video
// as a favorite.
func (r *ActivitiesService) Insert(part string, activity *Activity) *ActivitiesInsertCall {
c := &ActivitiesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.activity = activity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ActivitiesInsertCall) Fields(s ...googleapi.Field) *ActivitiesInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ActivitiesInsertCall) Context(ctx context.Context) *ActivitiesInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ActivitiesInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ActivitiesInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.activity)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "activities")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.activities.insert" call.
// Exactly one of *Activity or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Activity.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ActivitiesInsertCall) Do(opts ...googleapi.CallOption) (*Activity, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Activity{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Posts a bulletin for a specific channel. (The user submitting the request must be authorized to act on the channel's behalf.)\n\nNote: Even though an activity resource can contain information about actions like a user rating a video or marking a video as a favorite, you need to use other API methods to generate those activity resources. For example, you would use the API's videos.rate() method to rate a video and the playlistItems.insert() method to mark a video as a favorite.",
// "httpMethod": "POST",
// "id": "youtube.activities.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "activities",
// "request": {
// "$ref": "Activity"
// },
// "response": {
// "$ref": "Activity"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.activities.list":
type ActivitiesListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of channel activity events that match the
// request criteria. For example, you can retrieve events associated
// with a particular channel, events associated with the user's
// subscriptions and Google+ friends, or the YouTube home page feed,
// which is customized for each user.
func (r *ActivitiesService) List(part string) *ActivitiesListCall {
c := &ActivitiesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// ChannelId sets the optional parameter "channelId": The channelId
// parameter specifies a unique YouTube channel ID. The API will then
// return a list of that channel's activities.
func (c *ActivitiesListCall) ChannelId(channelId string) *ActivitiesListCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// Home sets the optional parameter "home": Set this parameter's value
// to true to retrieve the activity feed that displays on the YouTube
// home page for the currently authenticated user.
func (c *ActivitiesListCall) Home(home bool) *ActivitiesListCall {
c.urlParams_.Set("home", fmt.Sprint(home))
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *ActivitiesListCall) MaxResults(maxResults int64) *ActivitiesListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// Mine sets the optional parameter "mine": Set this parameter's value
// to true to retrieve a feed of the authenticated user's activities.
func (c *ActivitiesListCall) Mine(mine bool) *ActivitiesListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *ActivitiesListCall) PageToken(pageToken string) *ActivitiesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// PublishedAfter sets the optional parameter "publishedAfter": The
// publishedAfter parameter specifies the earliest date and time that an
// activity could have occurred for that activity to be included in the
// API response. If the parameter value specifies a day, but not a time,
// then any activities that occurred that day will be included in the
// result set. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
func (c *ActivitiesListCall) PublishedAfter(publishedAfter string) *ActivitiesListCall {
c.urlParams_.Set("publishedAfter", publishedAfter)
return c
}
// PublishedBefore sets the optional parameter "publishedBefore": The
// publishedBefore parameter specifies the date and time before which an
// activity must have occurred for that activity to be included in the
// API response. If the parameter value specifies a day, but not a time,
// then any activities that occurred that day will be excluded from the
// result set. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sZ) format.
func (c *ActivitiesListCall) PublishedBefore(publishedBefore string) *ActivitiesListCall {
c.urlParams_.Set("publishedBefore", publishedBefore)
return c
}
// RegionCode sets the optional parameter "regionCode": The regionCode
// parameter instructs the API to return results for the specified
// country. The parameter value is an ISO 3166-1 alpha-2 country code.
// YouTube uses this value when the authorized user's previous activity
// on YouTube does not provide enough information to generate the
// activity feed.
func (c *ActivitiesListCall) RegionCode(regionCode string) *ActivitiesListCall {
c.urlParams_.Set("regionCode", regionCode)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ActivitiesListCall) Fields(s ...googleapi.Field) *ActivitiesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ActivitiesListCall) IfNoneMatch(entityTag string) *ActivitiesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ActivitiesListCall) Context(ctx context.Context) *ActivitiesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ActivitiesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ActivitiesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "activities")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.activities.list" call.
// Exactly one of *ActivityListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ActivityListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ActivitiesListCall) Do(opts ...googleapi.CallOption) (*ActivityListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ActivityListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of channel activity events that match the request criteria. For example, you can retrieve events associated with a particular channel, events associated with the user's subscriptions and Google+ friends, or the YouTube home page feed, which is customized for each user.",
// "httpMethod": "GET",
// "id": "youtube.activities.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "channelId": {
// "description": "The channelId parameter specifies a unique YouTube channel ID. The API will then return a list of that channel's activities.",
// "location": "query",
// "type": "string"
// },
// "home": {
// "description": "Set this parameter's value to true to retrieve the activity feed that displays on the YouTube home page for the currently authenticated user.",
// "location": "query",
// "type": "boolean"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "mine": {
// "description": "Set this parameter's value to true to retrieve a feed of the authenticated user's activities.",
// "location": "query",
// "type": "boolean"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more activity resource properties that the API response will include.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in an activity resource, the snippet property contains other properties that identify the type of activity, a display title for the activity, and so forth. If you set part=snippet, the API response will also contain all of those nested properties.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "publishedAfter": {
// "description": "The publishedAfter parameter specifies the earliest date and time that an activity could have occurred for that activity to be included in the API response. If the parameter value specifies a day, but not a time, then any activities that occurred that day will be included in the result set. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "publishedBefore": {
// "description": "The publishedBefore parameter specifies the date and time before which an activity must have occurred for that activity to be included in the API response. If the parameter value specifies a day, but not a time, then any activities that occurred that day will be excluded from the result set. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "regionCode": {
// "description": "The regionCode parameter instructs the API to return results for the specified country. The parameter value is an ISO 3166-1 alpha-2 country code. YouTube uses this value when the authorized user's previous activity on YouTube does not provide enough information to generate the activity feed.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "activities",
// "response": {
// "$ref": "ActivityListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ActivitiesListCall) Pages(ctx context.Context, f func(*ActivityListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.captions.delete":
type CaptionsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a specified caption track.
func (r *CaptionsService) Delete(id string) *CaptionsDeleteCall {
c := &CaptionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOf sets the optional parameter "onBehalfOf": ID of the
// Google+ Page for the channel that the request is be on behalf of
func (c *CaptionsDeleteCall) OnBehalfOf(onBehalfOf string) *CaptionsDeleteCall {
c.urlParams_.Set("onBehalfOf", onBehalfOf)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *CaptionsDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *CaptionsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CaptionsDeleteCall) Fields(s ...googleapi.Field) *CaptionsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CaptionsDeleteCall) Context(ctx context.Context) *CaptionsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CaptionsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CaptionsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "captions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.captions.delete" call.
func (c *CaptionsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a specified caption track.",
// "httpMethod": "DELETE",
// "id": "youtube.captions.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter identifies the caption track that is being deleted. The value is a caption track ID as identified by the id property in a caption resource.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOf": {
// "description": "ID of the Google+ Page for the channel that the request is be on behalf of",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "captions",
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.captions.download":
type CaptionsDownloadCall struct {
s *Service
id string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Download: Downloads a caption track. The caption track is returned in
// its original format unless the request specifies a value for the tfmt
// parameter and in its original language unless the request specifies a
// value for the tlang parameter.
func (r *CaptionsService) Download(id string) *CaptionsDownloadCall {
c := &CaptionsDownloadCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.id = id
return c
}
// OnBehalfOf sets the optional parameter "onBehalfOf": ID of the
// Google+ Page for the channel that the request is be on behalf of
func (c *CaptionsDownloadCall) OnBehalfOf(onBehalfOf string) *CaptionsDownloadCall {
c.urlParams_.Set("onBehalfOf", onBehalfOf)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *CaptionsDownloadCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *CaptionsDownloadCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Tfmt sets the optional parameter "tfmt": The tfmt parameter specifies
// that the caption track should be returned in a specific format. If
// the parameter is not included in the request, the track is returned
// in its original format.
//
// Possible values:
// "sbv" - SubViewer subtitle.
// "scc" - Scenarist Closed Caption format.
// "srt" - SubRip subtitle.
// "ttml" - Timed Text Markup Language caption.
// "vtt" - Web Video Text Tracks caption.
func (c *CaptionsDownloadCall) Tfmt(tfmt string) *CaptionsDownloadCall {
c.urlParams_.Set("tfmt", tfmt)
return c
}
// Tlang sets the optional parameter "tlang": The tlang parameter
// specifies that the API response should return a translation of the
// specified caption track. The parameter value is an ISO 639-1
// two-letter language code that identifies the desired caption
// language. The translation is generated by using machine translation,
// such as Google Translate.
func (c *CaptionsDownloadCall) Tlang(tlang string) *CaptionsDownloadCall {
c.urlParams_.Set("tlang", tlang)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CaptionsDownloadCall) Fields(s ...googleapi.Field) *CaptionsDownloadCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *CaptionsDownloadCall) IfNoneMatch(entityTag string) *CaptionsDownloadCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *CaptionsDownloadCall) Context(ctx context.Context) *CaptionsDownloadCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CaptionsDownloadCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CaptionsDownloadCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "captions/{id}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"id": c.id,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *CaptionsDownloadCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "youtube.captions.download" call.
func (c *CaptionsDownloadCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Downloads a caption track. The caption track is returned in its original format unless the request specifies a value for the tfmt parameter and in its original language unless the request specifies a value for the tlang parameter.",
// "httpMethod": "GET",
// "id": "youtube.captions.download",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter identifies the caption track that is being retrieved. The value is a caption track ID as identified by the id property in a caption resource.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "onBehalfOf": {
// "description": "ID of the Google+ Page for the channel that the request is be on behalf of",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "tfmt": {
// "description": "The tfmt parameter specifies that the caption track should be returned in a specific format. If the parameter is not included in the request, the track is returned in its original format.",
// "enum": [
// "sbv",
// "scc",
// "srt",
// "ttml",
// "vtt"
// ],
// "enumDescriptions": [
// "SubViewer subtitle.",
// "Scenarist Closed Caption format.",
// "SubRip subtitle.",
// "Timed Text Markup Language caption.",
// "Web Video Text Tracks caption."
// ],
// "location": "query",
// "type": "string"
// },
// "tlang": {
// "description": "The tlang parameter specifies that the API response should return a translation of the specified caption track. The parameter value is an ISO 639-1 two-letter language code that identifies the desired caption language. The translation is generated by using machine translation, such as Google Translate.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "captions/{id}",
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsMediaDownload": true
// }
}
// method id "youtube.captions.insert":
type CaptionsInsertCall struct {
s *Service
caption *Caption
urlParams_ gensupport.URLParams
mediaInfo_ *gensupport.MediaInfo
ctx_ context.Context
header_ http.Header
}
// Insert: Uploads a caption track.
func (r *CaptionsService) Insert(part string, caption *Caption) *CaptionsInsertCall {
c := &CaptionsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.caption = caption
return c
}
// OnBehalfOf sets the optional parameter "onBehalfOf": ID of the
// Google+ Page for the channel that the request is be on behalf of
func (c *CaptionsInsertCall) OnBehalfOf(onBehalfOf string) *CaptionsInsertCall {
c.urlParams_.Set("onBehalfOf", onBehalfOf)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *CaptionsInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *CaptionsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Sync sets the optional parameter "sync": The sync parameter indicates
// whether YouTube should automatically synchronize the caption file
// with the audio track of the video. If you set the value to true,
// YouTube will disregard any time codes that are in the uploaded
// caption file and generate new time codes for the captions.
//
// You should set the sync parameter to true if you are uploading a
// transcript, which has no time codes, or if you suspect the time codes
// in your file are incorrect and want YouTube to try to fix them.
func (c *CaptionsInsertCall) Sync(sync bool) *CaptionsInsertCall {
c.urlParams_.Set("sync", fmt.Sprint(sync))
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *CaptionsInsertCall) Media(r io.Reader, options ...googleapi.MediaOption) *CaptionsInsertCall {
c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *CaptionsInsertCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *CaptionsInsertCall {
c.ctx_ = ctx
c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *CaptionsInsertCall) ProgressUpdater(pu googleapi.ProgressUpdater) *CaptionsInsertCall {
c.mediaInfo_.SetProgressUpdater(pu)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CaptionsInsertCall) Fields(s ...googleapi.Field) *CaptionsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *CaptionsInsertCall) Context(ctx context.Context) *CaptionsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CaptionsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CaptionsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.caption)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "captions")
if c.mediaInfo_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)
defer cleanup()
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
gensupport.SetGetBody(req, getBody)
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.captions.insert" call.
// Exactly one of *Caption or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Caption.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *CaptionsInsertCall) Do(opts ...googleapi.CallOption) (*Caption, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))
if rx != nil {
rx.Client = c.s.client
rx.UserAgent = c.s.userAgent()
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &Caption{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Uploads a caption track.",
// "httpMethod": "POST",
// "id": "youtube.captions.insert",
// "mediaUpload": {
// "accept": [
// "*/*",
// "application/octet-stream",
// "text/xml"
// ],
// "maxSize": "100MB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/youtube/v3/captions"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/youtube/v3/captions"
// }
// }
// },
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOf": {
// "description": "ID of the Google+ Page for the channel that the request is be on behalf of",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the caption resource parts that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "sync": {
// "description": "The sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will disregard any time codes that are in the uploaded caption file and generate new time codes for the captions.\n\nYou should set the sync parameter to true if you are uploading a transcript, which has no time codes, or if you suspect the time codes in your file are incorrect and want YouTube to try to fix them.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "captions",
// "request": {
// "$ref": "Caption"
// },
// "response": {
// "$ref": "Caption"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsMediaUpload": true
// }
}
// method id "youtube.captions.list":
type CaptionsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of caption tracks that are associated with a
// specified video. Note that the API response does not contain the
// actual captions and that the captions.download method provides the
// ability to retrieve a caption track.
func (r *CaptionsService) List(part string, videoId string) *CaptionsListCall {
c := &CaptionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.urlParams_.Set("videoId", videoId)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of IDs that identify the caption resources that
// should be retrieved. Each ID must identify a caption track associated
// with the specified video.
func (c *CaptionsListCall) Id(id string) *CaptionsListCall {
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOf sets the optional parameter "onBehalfOf": ID of the
// Google+ Page for the channel that the request is on behalf of.
func (c *CaptionsListCall) OnBehalfOf(onBehalfOf string) *CaptionsListCall {
c.urlParams_.Set("onBehalfOf", onBehalfOf)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *CaptionsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *CaptionsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CaptionsListCall) Fields(s ...googleapi.Field) *CaptionsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *CaptionsListCall) IfNoneMatch(entityTag string) *CaptionsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CaptionsListCall) Context(ctx context.Context) *CaptionsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CaptionsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CaptionsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "captions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.captions.list" call.
// Exactly one of *CaptionListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *CaptionListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *CaptionsListCall) Do(opts ...googleapi.CallOption) (*CaptionListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &CaptionListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of caption tracks that are associated with a specified video. Note that the API response does not contain the actual captions and that the captions.download method provides the ability to retrieve a caption track.",
// "httpMethod": "GET",
// "id": "youtube.captions.list",
// "parameterOrder": [
// "part",
// "videoId"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies a comma-separated list of IDs that identify the caption resources that should be retrieved. Each ID must identify a caption track associated with the specified video.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOf": {
// "description": "ID of the Google+ Page for the channel that the request is on behalf of.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more caption resource parts that the API response will include. The part names that you can include in the parameter value are id and snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "videoId": {
// "description": "The videoId parameter specifies the YouTube video ID of the video for which the API should return caption tracks.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "captions",
// "response": {
// "$ref": "CaptionListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.captions.update":
type CaptionsUpdateCall struct {
s *Service
caption *Caption
urlParams_ gensupport.URLParams
mediaInfo_ *gensupport.MediaInfo
ctx_ context.Context
header_ http.Header
}
// Update: Updates a caption track. When updating a caption track, you
// can change the track's draft status, upload a new caption file for
// the track, or both.
func (r *CaptionsService) Update(part string, caption *Caption) *CaptionsUpdateCall {
c := &CaptionsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.caption = caption
return c
}
// OnBehalfOf sets the optional parameter "onBehalfOf": ID of the
// Google+ Page for the channel that the request is be on behalf of
func (c *CaptionsUpdateCall) OnBehalfOf(onBehalfOf string) *CaptionsUpdateCall {
c.urlParams_.Set("onBehalfOf", onBehalfOf)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *CaptionsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *CaptionsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Sync sets the optional parameter "sync": Note: The API server only
// processes the parameter value if the request contains an updated
// caption file.
//
// The sync parameter indicates whether YouTube should automatically
// synchronize the caption file with the audio track of the video. If
// you set the value to true, YouTube will automatically synchronize the
// caption track with the audio track.
func (c *CaptionsUpdateCall) Sync(sync bool) *CaptionsUpdateCall {
c.urlParams_.Set("sync", fmt.Sprint(sync))
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *CaptionsUpdateCall) Media(r io.Reader, options ...googleapi.MediaOption) *CaptionsUpdateCall {
c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *CaptionsUpdateCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *CaptionsUpdateCall {
c.ctx_ = ctx
c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *CaptionsUpdateCall) ProgressUpdater(pu googleapi.ProgressUpdater) *CaptionsUpdateCall {
c.mediaInfo_.SetProgressUpdater(pu)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CaptionsUpdateCall) Fields(s ...googleapi.Field) *CaptionsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *CaptionsUpdateCall) Context(ctx context.Context) *CaptionsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CaptionsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CaptionsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.caption)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "captions")
if c.mediaInfo_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)
defer cleanup()
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
gensupport.SetGetBody(req, getBody)
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.captions.update" call.
// Exactly one of *Caption or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Caption.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *CaptionsUpdateCall) Do(opts ...googleapi.CallOption) (*Caption, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))
if rx != nil {
rx.Client = c.s.client
rx.UserAgent = c.s.userAgent()
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &Caption{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a caption track. When updating a caption track, you can change the track's draft status, upload a new caption file for the track, or both.",
// "httpMethod": "PUT",
// "id": "youtube.captions.update",
// "mediaUpload": {
// "accept": [
// "*/*",
// "application/octet-stream",
// "text/xml"
// ],
// "maxSize": "100MB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/youtube/v3/captions"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/youtube/v3/captions"
// }
// }
// },
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOf": {
// "description": "ID of the Google+ Page for the channel that the request is be on behalf of",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the property value to snippet if you are updating the track's draft status. Otherwise, set the property value to id.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "sync": {
// "description": "Note: The API server only processes the parameter value if the request contains an updated caption file.\n\nThe sync parameter indicates whether YouTube should automatically synchronize the caption file with the audio track of the video. If you set the value to true, YouTube will automatically synchronize the caption track with the audio track.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "captions",
// "request": {
// "$ref": "Caption"
// },
// "response": {
// "$ref": "Caption"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsMediaUpload": true
// }
}
// method id "youtube.channelBanners.insert":
type ChannelBannersInsertCall struct {
s *Service
channelbannerresource *ChannelBannerResource
urlParams_ gensupport.URLParams
mediaInfo_ *gensupport.MediaInfo
ctx_ context.Context
header_ http.Header
}
// Insert: Uploads a channel banner image to YouTube. This method
// represents the first two steps in a three-step process to update the
// banner image for a channel:
//
// - Call the channelBanners.insert method to upload the binary image
// data to YouTube. The image must have a 16:9 aspect ratio and be at
// least 2120x1192 pixels.
// - Extract the url property's value from the response that the API
// returns for step 1.
// - Call the channels.update method to update the channel's branding
// settings. Set the brandingSettings.image.bannerExternalUrl property's
// value to the URL obtained in step 2.
func (r *ChannelBannersService) Insert(channelbannerresource *ChannelBannerResource) *ChannelBannersInsertCall {
c := &ChannelBannersInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.channelbannerresource = channelbannerresource
return c
}
// ChannelId sets the optional parameter "channelId": The channelId
// parameter identifies the YouTube channel to which the banner is
// uploaded. The channelId parameter was introduced as a required
// parameter in May 2017. As this was a backward-incompatible change,
// channelBanners.insert requests that do not specify this parameter
// will not return an error until six months have passed from the time
// that the parameter was introduced. Please see the API Terms of
// Service for the official policy regarding backward incompatible
// changes and the API revision history for the exact date that the
// parameter was introduced.
func (c *ChannelBannersInsertCall) ChannelId(channelId string) *ChannelBannersInsertCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *ChannelBannersInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelBannersInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *ChannelBannersInsertCall) Media(r io.Reader, options ...googleapi.MediaOption) *ChannelBannersInsertCall {
c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *ChannelBannersInsertCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *ChannelBannersInsertCall {
c.ctx_ = ctx
c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *ChannelBannersInsertCall) ProgressUpdater(pu googleapi.ProgressUpdater) *ChannelBannersInsertCall {
c.mediaInfo_.SetProgressUpdater(pu)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelBannersInsertCall) Fields(s ...googleapi.Field) *ChannelBannersInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *ChannelBannersInsertCall) Context(ctx context.Context) *ChannelBannersInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelBannersInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelBannersInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channelbannerresource)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channelBanners/insert")
if c.mediaInfo_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)
defer cleanup()
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
gensupport.SetGetBody(req, getBody)
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channelBanners.insert" call.
// Exactly one of *ChannelBannerResource or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ChannelBannerResource.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ChannelBannersInsertCall) Do(opts ...googleapi.CallOption) (*ChannelBannerResource, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))
if rx != nil {
rx.Client = c.s.client
rx.UserAgent = c.s.userAgent()
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &ChannelBannerResource{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Uploads a channel banner image to YouTube. This method represents the first two steps in a three-step process to update the banner image for a channel:\n\n- Call the channelBanners.insert method to upload the binary image data to YouTube. The image must have a 16:9 aspect ratio and be at least 2120x1192 pixels.\n- Extract the url property's value from the response that the API returns for step 1.\n- Call the channels.update method to update the channel's branding settings. Set the brandingSettings.image.bannerExternalUrl property's value to the URL obtained in step 2.",
// "httpMethod": "POST",
// "id": "youtube.channelBanners.insert",
// "mediaUpload": {
// "accept": [
// "application/octet-stream",
// "image/jpeg",
// "image/png"
// ],
// "maxSize": "6MB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/youtube/v3/channelBanners/insert"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/youtube/v3/channelBanners/insert"
// }
// }
// },
// "parameters": {
// "channelId": {
// "description": "The channelId parameter identifies the YouTube channel to which the banner is uploaded. The channelId parameter was introduced as a required parameter in May 2017. As this was a backward-incompatible change, channelBanners.insert requests that do not specify this parameter will not return an error until six months have passed from the time that the parameter was introduced. Please see the API Terms of Service for the official policy regarding backward incompatible changes and the API revision history for the exact date that the parameter was introduced.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "channelBanners/insert",
// "request": {
// "$ref": "ChannelBannerResource"
// },
// "response": {
// "$ref": "ChannelBannerResource"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.upload"
// ],
// "supportsMediaUpload": true
// }
}
// method id "youtube.channelSections.delete":
type ChannelSectionsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a channelSection.
func (r *ChannelSectionsService) Delete(id string) *ChannelSectionsDeleteCall {
c := &ChannelSectionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *ChannelSectionsDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelSectionsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelSectionsDeleteCall) Fields(s ...googleapi.Field) *ChannelSectionsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelSectionsDeleteCall) Context(ctx context.Context) *ChannelSectionsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelSectionsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelSectionsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channelSections")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channelSections.delete" call.
func (c *ChannelSectionsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a channelSection.",
// "httpMethod": "DELETE",
// "id": "youtube.channelSections.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube channelSection ID for the resource that is being deleted. In a channelSection resource, the id property specifies the YouTube channelSection ID.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "channelSections",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.channelSections.insert":
type ChannelSectionsInsertCall struct {
s *Service
channelsection *ChannelSection
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Adds a channelSection for the authenticated user's channel.
func (r *ChannelSectionsService) Insert(part string, channelsection *ChannelSection) *ChannelSectionsInsertCall {
c := &ChannelSectionsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.channelsection = channelsection
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *ChannelSectionsInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelSectionsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *ChannelSectionsInsertCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *ChannelSectionsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelSectionsInsertCall) Fields(s ...googleapi.Field) *ChannelSectionsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelSectionsInsertCall) Context(ctx context.Context) *ChannelSectionsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelSectionsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelSectionsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channelsection)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channelSections")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channelSections.insert" call.
// Exactly one of *ChannelSection or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ChannelSection.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ChannelSectionsInsertCall) Do(opts ...googleapi.CallOption) (*ChannelSection, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ChannelSection{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a channelSection for the authenticated user's channel.",
// "httpMethod": "POST",
// "id": "youtube.channelSections.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe part names that you can include in the parameter value are snippet and contentDetails.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "channelSections",
// "request": {
// "$ref": "ChannelSection"
// },
// "response": {
// "$ref": "ChannelSection"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.channelSections.list":
type ChannelSectionsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns channelSection resources that match the API request
// criteria.
func (r *ChannelSectionsService) List(part string) *ChannelSectionsListCall {
c := &ChannelSectionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// ChannelId sets the optional parameter "channelId": The channelId
// parameter specifies a YouTube channel ID. The API will only return
// that channel's channelSections.
func (c *ChannelSectionsListCall) ChannelId(channelId string) *ChannelSectionsListCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// Hl sets the optional parameter "hl": The hl parameter indicates that
// the snippet.localized property values in the returned channelSection
// resources should be in the specified language if localized values for
// that language are available. For example, if the API request
// specifies hl=de, the snippet.localized properties in the API response
// will contain German titles if German titles are available. Channel
// owners can provide localized channel section titles using either the
// channelSections.insert or channelSections.update method.
func (c *ChannelSectionsListCall) Hl(hl string) *ChannelSectionsListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of the YouTube channelSection ID(s) for the
// resource(s) that are being retrieved. In a channelSection resource,
// the id property specifies the YouTube channelSection ID.
func (c *ChannelSectionsListCall) Id(id string) *ChannelSectionsListCall {
c.urlParams_.Set("id", id)
return c
}
// Mine sets the optional parameter "mine": Set this parameter's value
// to true to retrieve a feed of the authenticated user's
// channelSections.
func (c *ChannelSectionsListCall) Mine(mine bool) *ChannelSectionsListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *ChannelSectionsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelSectionsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelSectionsListCall) Fields(s ...googleapi.Field) *ChannelSectionsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ChannelSectionsListCall) IfNoneMatch(entityTag string) *ChannelSectionsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelSectionsListCall) Context(ctx context.Context) *ChannelSectionsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelSectionsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelSectionsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channelSections")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channelSections.list" call.
// Exactly one of *ChannelSectionListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *ChannelSectionListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ChannelSectionsListCall) Do(opts ...googleapi.CallOption) (*ChannelSectionListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ChannelSectionListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns channelSection resources that match the API request criteria.",
// "httpMethod": "GET",
// "id": "youtube.channelSections.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "channelId": {
// "description": "The channelId parameter specifies a YouTube channel ID. The API will only return that channel's channelSections.",
// "location": "query",
// "type": "string"
// },
// "hl": {
// "description": "The hl parameter indicates that the snippet.localized property values in the returned channelSection resources should be in the specified language if localized values for that language are available. For example, if the API request specifies hl=de, the snippet.localized properties in the API response will contain German titles if German titles are available. Channel owners can provide localized channel section titles using either the channelSections.insert or channelSections.update method.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube channelSection ID(s) for the resource(s) that are being retrieved. In a channelSection resource, the id property specifies the YouTube channelSection ID.",
// "location": "query",
// "type": "string"
// },
// "mine": {
// "description": "Set this parameter's value to true to retrieve a feed of the authenticated user's channelSections.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more channelSection resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, and contentDetails.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channelSection resource, the snippet property contains other properties, such as a display title for the channelSection. If you set part=snippet, the API response will also contain all of those nested properties.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "channelSections",
// "response": {
// "$ref": "ChannelSectionListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.channelSections.update":
type ChannelSectionsUpdateCall struct {
s *Service
channelsection *ChannelSection
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Update a channelSection.
func (r *ChannelSectionsService) Update(part string, channelsection *ChannelSection) *ChannelSectionsUpdateCall {
c := &ChannelSectionsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.channelsection = channelsection
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *ChannelSectionsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelSectionsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelSectionsUpdateCall) Fields(s ...googleapi.Field) *ChannelSectionsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelSectionsUpdateCall) Context(ctx context.Context) *ChannelSectionsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelSectionsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelSectionsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channelsection)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channelSections")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channelSections.update" call.
// Exactly one of *ChannelSection or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ChannelSection.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ChannelSectionsUpdateCall) Do(opts ...googleapi.CallOption) (*ChannelSection, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ChannelSection{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Update a channelSection.",
// "httpMethod": "PUT",
// "id": "youtube.channelSections.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe part names that you can include in the parameter value are snippet and contentDetails.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "channelSections",
// "request": {
// "$ref": "ChannelSection"
// },
// "response": {
// "$ref": "ChannelSection"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.channels.list":
type ChannelsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a collection of zero or more channel resources that
// match the request criteria.
func (r *ChannelsService) List(part string) *ChannelsListCall {
c := &ChannelsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// CategoryId sets the optional parameter "categoryId": The categoryId
// parameter specifies a YouTube guide category, thereby requesting
// YouTube channels associated with that category.
func (c *ChannelsListCall) CategoryId(categoryId string) *ChannelsListCall {
c.urlParams_.Set("categoryId", categoryId)
return c
}
// ForUsername sets the optional parameter "forUsername": The
// forUsername parameter specifies a YouTube username, thereby
// requesting the channel associated with that username.
func (c *ChannelsListCall) ForUsername(forUsername string) *ChannelsListCall {
c.urlParams_.Set("forUsername", forUsername)
return c
}
// Hl sets the optional parameter "hl": The hl parameter should be used
// for filter out the properties that are not in the given language.
// Used for the brandingSettings part.
func (c *ChannelsListCall) Hl(hl string) *ChannelsListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of the YouTube channel ID(s) for the resource(s)
// that are being retrieved. In a channel resource, the id property
// specifies the channel's YouTube channel ID.
func (c *ChannelsListCall) Id(id string) *ChannelsListCall {
c.urlParams_.Set("id", id)
return c
}
// ManagedByMe sets the optional parameter "managedByMe": Note: This
// parameter is intended exclusively for YouTube content partners.
//
// Set this parameter's value to true to instruct the API to only return
// channels managed by the content owner that the onBehalfOfContentOwner
// parameter specifies. The user must be authenticated as a CMS account
// linked to the specified content owner and onBehalfOfContentOwner must
// be provided.
func (c *ChannelsListCall) ManagedByMe(managedByMe bool) *ChannelsListCall {
c.urlParams_.Set("managedByMe", fmt.Sprint(managedByMe))
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *ChannelsListCall) MaxResults(maxResults int64) *ChannelsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// Mine sets the optional parameter "mine": Set this parameter's value
// to true to instruct the API to only return channels owned by the
// authenticated user.
func (c *ChannelsListCall) Mine(mine bool) *ChannelsListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// MySubscribers sets the optional parameter "mySubscribers": Use the
// subscriptions.list method and its mySubscribers parameter to retrieve
// a list of subscribers to the authenticated user's channel.
func (c *ChannelsListCall) MySubscribers(mySubscribers bool) *ChannelsListCall {
c.urlParams_.Set("mySubscribers", fmt.Sprint(mySubscribers))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *ChannelsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *ChannelsListCall) PageToken(pageToken string) *ChannelsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelsListCall) Fields(s ...googleapi.Field) *ChannelsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ChannelsListCall) IfNoneMatch(entityTag string) *ChannelsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelsListCall) Context(ctx context.Context) *ChannelsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channels")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channels.list" call.
// Exactly one of *ChannelListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ChannelListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ChannelsListCall) Do(opts ...googleapi.CallOption) (*ChannelListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ChannelListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a collection of zero or more channel resources that match the request criteria.",
// "httpMethod": "GET",
// "id": "youtube.channels.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "categoryId": {
// "description": "The categoryId parameter specifies a YouTube guide category, thereby requesting YouTube channels associated with that category.",
// "location": "query",
// "type": "string"
// },
// "forUsername": {
// "description": "The forUsername parameter specifies a YouTube username, thereby requesting the channel associated with that username.",
// "location": "query",
// "type": "string"
// },
// "hl": {
// "description": "The hl parameter should be used for filter out the properties that are not in the given language. Used for the brandingSettings part.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube channel ID(s) for the resource(s) that are being retrieved. In a channel resource, the id property specifies the channel's YouTube channel ID.",
// "location": "query",
// "type": "string"
// },
// "managedByMe": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nSet this parameter's value to true to instruct the API to only return channels managed by the content owner that the onBehalfOfContentOwner parameter specifies. The user must be authenticated as a CMS account linked to the specified content owner and onBehalfOfContentOwner must be provided.",
// "location": "query",
// "type": "boolean"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "mine": {
// "description": "Set this parameter's value to true to instruct the API to only return channels owned by the authenticated user.",
// "location": "query",
// "type": "boolean"
// },
// "mySubscribers": {
// "description": "Use the subscriptions.list method and its mySubscribers parameter to retrieve a list of subscribers to the authenticated user's channel.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more channel resource properties that the API response will include.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channel resource, the contentDetails property contains other properties, such as the uploads properties. As such, if you set part=contentDetails, the API response will also contain all of those nested properties.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "channels",
// "response": {
// "$ref": "ChannelListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner",
// "https://www.googleapis.com/auth/youtubepartner-channel-audit"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ChannelsListCall) Pages(ctx context.Context, f func(*ChannelListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.channels.update":
type ChannelsUpdateCall struct {
s *Service
channel *Channel
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a channel's metadata. Note that this method currently
// only supports updates to the channel resource's brandingSettings and
// invideoPromotion objects and their child properties.
func (r *ChannelsService) Update(part string, channel *Channel) *ChannelsUpdateCall {
c := &ChannelsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.channel = channel
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": The onBehalfOfContentOwner parameter
// indicates that the authenticated user is acting on behalf of the
// content owner specified in the parameter value. This parameter is
// intended for YouTube content partners that own and manage many
// different YouTube channels. It allows content owners to authenticate
// once and get access to all their video and channel data, without
// having to provide authentication credentials for each individual
// channel. The actual CMS account that the user authenticates with
// needs to be linked to the specified YouTube content owner.
func (c *ChannelsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ChannelsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelsUpdateCall) Fields(s ...googleapi.Field) *ChannelsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelsUpdateCall) Context(ctx context.Context) *ChannelsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "channels")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.channels.update" call.
// Exactly one of *Channel or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Channel.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ChannelsUpdateCall) Do(opts ...googleapi.CallOption) (*Channel, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Channel{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a channel's metadata. Note that this method currently only supports updates to the channel resource's brandingSettings and invideoPromotion objects and their child properties.",
// "httpMethod": "PUT",
// "id": "youtube.channels.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "The onBehalfOfContentOwner parameter indicates that the authenticated user is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with needs to be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe API currently only allows the parameter value to be set to either brandingSettings or invideoPromotion. (You cannot update both of those parts with a single request.)\n\nNote that this method overrides the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "channels",
// "request": {
// "$ref": "Channel"
// },
// "response": {
// "$ref": "Channel"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.commentThreads.insert":
type CommentThreadsInsertCall struct {
s *Service
commentthread *CommentThread
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new top-level comment. To add a reply to an
// existing comment, use the comments.insert method instead.
func (r *CommentThreadsService) Insert(part string, commentthread *CommentThread) *CommentThreadsInsertCall {
c := &CommentThreadsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.commentthread = commentthread
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentThreadsInsertCall) Fields(s ...googleapi.Field) *CommentThreadsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentThreadsInsertCall) Context(ctx context.Context) *CommentThreadsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentThreadsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentThreadsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.commentthread)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "commentThreads")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.commentThreads.insert" call.
// Exactly one of *CommentThread or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *CommentThread.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *CommentThreadsInsertCall) Do(opts ...googleapi.CallOption) (*CommentThread, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &CommentThread{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new top-level comment. To add a reply to an existing comment, use the comments.insert method instead.",
// "httpMethod": "POST",
// "id": "youtube.commentThreads.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter identifies the properties that the API response will include. Set the parameter value to snippet. The snippet part has a quota cost of 2 units.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "commentThreads",
// "request": {
// "$ref": "CommentThread"
// },
// "response": {
// "$ref": "CommentThread"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.commentThreads.list":
type CommentThreadsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of comment threads that match the API request
// parameters.
func (r *CommentThreadsService) List(part string) *CommentThreadsListCall {
c := &CommentThreadsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// AllThreadsRelatedToChannelId sets the optional parameter
// "allThreadsRelatedToChannelId": The allThreadsRelatedToChannelId
// parameter instructs the API to return all comment threads associated
// with the specified channel. The response can include comments about
// the channel or about the channel's videos.
func (c *CommentThreadsListCall) AllThreadsRelatedToChannelId(allThreadsRelatedToChannelId string) *CommentThreadsListCall {
c.urlParams_.Set("allThreadsRelatedToChannelId", allThreadsRelatedToChannelId)
return c
}
// ChannelId sets the optional parameter "channelId": The channelId
// parameter instructs the API to return comment threads containing
// comments about the specified channel. (The response will not include
// comments left on videos that the channel uploaded.)
func (c *CommentThreadsListCall) ChannelId(channelId string) *CommentThreadsListCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of comment thread IDs for the resources that
// should be retrieved.
func (c *CommentThreadsListCall) Id(id string) *CommentThreadsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
//
// Note: This parameter is not supported for use in conjunction with the
// id parameter.
func (c *CommentThreadsListCall) MaxResults(maxResults int64) *CommentThreadsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// ModerationStatus sets the optional parameter "moderationStatus": Set
// this parameter to limit the returned comment threads to a particular
// moderation state.
//
// Note: This parameter is not supported for use in conjunction with the
// id parameter.
//
// Possible values:
// "heldForReview" - Retrieve comment threads that are awaiting review
// by a moderator. A comment thread can be included in the response if
// the top-level comment or at least one of the replies to that comment
// are awaiting review.
// "likelySpam" - Retrieve comment threads classified as likely to be
// spam. A comment thread can be included in the response if the
// top-level comment or at least one of the replies to that comment is
// considered likely to be spam.
// "published" - Retrieve threads of published comments. This is the
// default value. A comment thread can be included in the response if
// its top-level comment has been published.
func (c *CommentThreadsListCall) ModerationStatus(moderationStatus string) *CommentThreadsListCall {
c.urlParams_.Set("moderationStatus", moderationStatus)
return c
}
// Order sets the optional parameter "order": The order parameter
// specifies the order in which the API response should list comment
// threads. Valid values are:
// - time - Comment threads are ordered by time. This is the default
// behavior.
// - relevance - Comment threads are ordered by relevance.Note: This
// parameter is not supported for use in conjunction with the id
// parameter.
//
// Possible values:
// "relevance" - Order by relevance.
// "time" - Order by time.
func (c *CommentThreadsListCall) Order(order string) *CommentThreadsListCall {
c.urlParams_.Set("order", order)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken property identifies
// the next page of the result that can be retrieved.
//
// Note: This parameter is not supported for use in conjunction with the
// id parameter.
func (c *CommentThreadsListCall) PageToken(pageToken string) *CommentThreadsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// SearchTerms sets the optional parameter "searchTerms": The
// searchTerms parameter instructs the API to limit the API response to
// only contain comments that contain the specified search terms.
//
// Note: This parameter is not supported for use in conjunction with the
// id parameter.
func (c *CommentThreadsListCall) SearchTerms(searchTerms string) *CommentThreadsListCall {
c.urlParams_.Set("searchTerms", searchTerms)
return c
}
// TextFormat sets the optional parameter "textFormat": Set this
// parameter's value to html or plainText to instruct the API to return
// the comments left by users in html formatted or in plain text.
//
// Possible values:
// "html" - Returns the comments in HTML format. This is the default
// value.
// "plainText" - Returns the comments in plain text format.
func (c *CommentThreadsListCall) TextFormat(textFormat string) *CommentThreadsListCall {
c.urlParams_.Set("textFormat", textFormat)
return c
}
// VideoId sets the optional parameter "videoId": The videoId parameter
// instructs the API to return comment threads associated with the
// specified video ID.
func (c *CommentThreadsListCall) VideoId(videoId string) *CommentThreadsListCall {
c.urlParams_.Set("videoId", videoId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentThreadsListCall) Fields(s ...googleapi.Field) *CommentThreadsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *CommentThreadsListCall) IfNoneMatch(entityTag string) *CommentThreadsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentThreadsListCall) Context(ctx context.Context) *CommentThreadsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentThreadsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentThreadsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "commentThreads")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.commentThreads.list" call.
// Exactly one of *CommentThreadListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *CommentThreadListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *CommentThreadsListCall) Do(opts ...googleapi.CallOption) (*CommentThreadListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &CommentThreadListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of comment threads that match the API request parameters.",
// "httpMethod": "GET",
// "id": "youtube.commentThreads.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "allThreadsRelatedToChannelId": {
// "description": "The allThreadsRelatedToChannelId parameter instructs the API to return all comment threads associated with the specified channel. The response can include comments about the channel or about the channel's videos.",
// "location": "query",
// "type": "string"
// },
// "channelId": {
// "description": "The channelId parameter instructs the API to return comment threads containing comments about the specified channel. (The response will not include comments left on videos that the channel uploaded.)",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of comment thread IDs for the resources that should be retrieved.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "20",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.\n\nNote: This parameter is not supported for use in conjunction with the id parameter.",
// "format": "uint32",
// "location": "query",
// "maximum": "100",
// "minimum": "1",
// "type": "integer"
// },
// "moderationStatus": {
// "default": "MODERATION_STATUS_PUBLISHED",
// "description": "Set this parameter to limit the returned comment threads to a particular moderation state.\n\nNote: This parameter is not supported for use in conjunction with the id parameter.",
// "enum": [
// "heldForReview",
// "likelySpam",
// "published"
// ],
// "enumDescriptions": [
// "Retrieve comment threads that are awaiting review by a moderator. A comment thread can be included in the response if the top-level comment or at least one of the replies to that comment are awaiting review.",
// "Retrieve comment threads classified as likely to be spam. A comment thread can be included in the response if the top-level comment or at least one of the replies to that comment is considered likely to be spam.",
// "Retrieve threads of published comments. This is the default value. A comment thread can be included in the response if its top-level comment has been published."
// ],
// "location": "query",
// "type": "string"
// },
// "order": {
// "default": "true",
// "description": "The order parameter specifies the order in which the API response should list comment threads. Valid values are: \n- time - Comment threads are ordered by time. This is the default behavior.\n- relevance - Comment threads are ordered by relevance.Note: This parameter is not supported for use in conjunction with the id parameter.",
// "enum": [
// "relevance",
// "time"
// ],
// "enumDescriptions": [
// "Order by relevance.",
// "Order by time."
// ],
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identifies the next page of the result that can be retrieved.\n\nNote: This parameter is not supported for use in conjunction with the id parameter.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more commentThread resource properties that the API response will include.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "searchTerms": {
// "description": "The searchTerms parameter instructs the API to limit the API response to only contain comments that contain the specified search terms.\n\nNote: This parameter is not supported for use in conjunction with the id parameter.",
// "location": "query",
// "type": "string"
// },
// "textFormat": {
// "default": "FORMAT_HTML",
// "description": "Set this parameter's value to html or plainText to instruct the API to return the comments left by users in html formatted or in plain text.",
// "enum": [
// "html",
// "plainText"
// ],
// "enumDescriptions": [
// "Returns the comments in HTML format. This is the default value.",
// "Returns the comments in plain text format."
// ],
// "location": "query",
// "type": "string"
// },
// "videoId": {
// "description": "The videoId parameter instructs the API to return comment threads associated with the specified video ID.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "commentThreads",
// "response": {
// "$ref": "CommentThreadListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *CommentThreadsListCall) Pages(ctx context.Context, f func(*CommentThreadListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.commentThreads.update":
type CommentThreadsUpdateCall struct {
s *Service
commentthread *CommentThread
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Modifies the top-level comment in a comment thread.
func (r *CommentThreadsService) Update(part string, commentthread *CommentThread) *CommentThreadsUpdateCall {
c := &CommentThreadsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.commentthread = commentthread
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentThreadsUpdateCall) Fields(s ...googleapi.Field) *CommentThreadsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentThreadsUpdateCall) Context(ctx context.Context) *CommentThreadsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentThreadsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentThreadsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.commentthread)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "commentThreads")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.commentThreads.update" call.
// Exactly one of *CommentThread or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *CommentThread.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *CommentThreadsUpdateCall) Do(opts ...googleapi.CallOption) (*CommentThread, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &CommentThread{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Modifies the top-level comment in a comment thread.",
// "httpMethod": "PUT",
// "id": "youtube.commentThreads.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter specifies a comma-separated list of commentThread resource properties that the API response will include. You must at least include the snippet part in the parameter value since that part contains all of the properties that the API request can update.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "commentThreads",
// "request": {
// "$ref": "CommentThread"
// },
// "response": {
// "$ref": "CommentThread"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.comments.delete":
type CommentsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a comment.
func (r *CommentsService) Delete(id string) *CommentsDeleteCall {
c := &CommentsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsDeleteCall) Fields(s ...googleapi.Field) *CommentsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentsDeleteCall) Context(ctx context.Context) *CommentsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "comments")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.comments.delete" call.
func (c *CommentsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a comment.",
// "httpMethod": "DELETE",
// "id": "youtube.comments.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the comment ID for the resource that is being deleted.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "comments",
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.comments.insert":
type CommentsInsertCall struct {
s *Service
comment *Comment
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a reply to an existing comment. Note: To create a
// top-level comment, use the commentThreads.insert method.
func (r *CommentsService) Insert(part string, comment *Comment) *CommentsInsertCall {
c := &CommentsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.comment = comment
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsInsertCall) Fields(s ...googleapi.Field) *CommentsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentsInsertCall) Context(ctx context.Context) *CommentsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.comment)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "comments")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.comments.insert" call.
// Exactly one of *Comment or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Comment.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *CommentsInsertCall) Do(opts ...googleapi.CallOption) (*Comment, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Comment{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a reply to an existing comment. Note: To create a top-level comment, use the commentThreads.insert method.",
// "httpMethod": "POST",
// "id": "youtube.comments.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter identifies the properties that the API response will include. Set the parameter value to snippet. The snippet part has a quota cost of 2 units.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "comments",
// "request": {
// "$ref": "Comment"
// },
// "response": {
// "$ref": "Comment"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.comments.list":
type CommentsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of comments that match the API request
// parameters.
func (r *CommentsService) List(part string) *CommentsListCall {
c := &CommentsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of comment IDs for the resources that are being
// retrieved. In a comment resource, the id property specifies the
// comment's ID.
func (c *CommentsListCall) Id(id string) *CommentsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
//
// Note: This parameter is not supported for use in conjunction with the
// id parameter.
func (c *CommentsListCall) MaxResults(maxResults int64) *CommentsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken property identifies
// the next page of the result that can be retrieved.
//
// Note: This parameter is not supported for use in conjunction with the
// id parameter.
func (c *CommentsListCall) PageToken(pageToken string) *CommentsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// ParentId sets the optional parameter "parentId": The parentId
// parameter specifies the ID of the comment for which replies should be
// retrieved.
//
// Note: YouTube currently supports replies only for top-level comments.
// However, replies to replies may be supported in the future.
func (c *CommentsListCall) ParentId(parentId string) *CommentsListCall {
c.urlParams_.Set("parentId", parentId)
return c
}
// TextFormat sets the optional parameter "textFormat": This parameter
// indicates whether the API should return comments formatted as HTML or
// as plain text.
//
// Possible values:
// "html" - Returns the comments in HTML format. This is the default
// value.
// "plainText" - Returns the comments in plain text format.
func (c *CommentsListCall) TextFormat(textFormat string) *CommentsListCall {
c.urlParams_.Set("textFormat", textFormat)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsListCall) Fields(s ...googleapi.Field) *CommentsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *CommentsListCall) IfNoneMatch(entityTag string) *CommentsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentsListCall) Context(ctx context.Context) *CommentsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "comments")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.comments.list" call.
// Exactly one of *CommentListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *CommentListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *CommentsListCall) Do(opts ...googleapi.CallOption) (*CommentListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &CommentListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of comments that match the API request parameters.",
// "httpMethod": "GET",
// "id": "youtube.comments.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies a comma-separated list of comment IDs for the resources that are being retrieved. In a comment resource, the id property specifies the comment's ID.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "20",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.\n\nNote: This parameter is not supported for use in conjunction with the id parameter.",
// "format": "uint32",
// "location": "query",
// "maximum": "100",
// "minimum": "1",
// "type": "integer"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identifies the next page of the result that can be retrieved.\n\nNote: This parameter is not supported for use in conjunction with the id parameter.",
// "location": "query",
// "type": "string"
// },
// "parentId": {
// "description": "The parentId parameter specifies the ID of the comment for which replies should be retrieved.\n\nNote: YouTube currently supports replies only for top-level comments. However, replies to replies may be supported in the future.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more comment resource properties that the API response will include.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "textFormat": {
// "default": "FORMAT_HTML",
// "description": "This parameter indicates whether the API should return comments formatted as HTML or as plain text.",
// "enum": [
// "html",
// "plainText"
// ],
// "enumDescriptions": [
// "Returns the comments in HTML format. This is the default value.",
// "Returns the comments in plain text format."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "comments",
// "response": {
// "$ref": "CommentListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *CommentsListCall) Pages(ctx context.Context, f func(*CommentListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.comments.markAsSpam":
type CommentsMarkAsSpamCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// MarkAsSpam: Expresses the caller's opinion that one or more comments
// should be flagged as spam.
func (r *CommentsService) MarkAsSpam(id string) *CommentsMarkAsSpamCall {
c := &CommentsMarkAsSpamCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsMarkAsSpamCall) Fields(s ...googleapi.Field) *CommentsMarkAsSpamCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentsMarkAsSpamCall) Context(ctx context.Context) *CommentsMarkAsSpamCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentsMarkAsSpamCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentsMarkAsSpamCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "comments/markAsSpam")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.comments.markAsSpam" call.
func (c *CommentsMarkAsSpamCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Expresses the caller's opinion that one or more comments should be flagged as spam.",
// "httpMethod": "POST",
// "id": "youtube.comments.markAsSpam",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies a comma-separated list of IDs of comments that the caller believes should be classified as spam.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "comments/markAsSpam",
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.comments.setModerationStatus":
type CommentsSetModerationStatusCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetModerationStatus: Sets the moderation status of one or more
// comments. The API request must be authorized by the owner of the
// channel or video associated with the comments.
func (r *CommentsService) SetModerationStatus(id string, moderationStatus string) *CommentsSetModerationStatusCall {
c := &CommentsSetModerationStatusCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
c.urlParams_.Set("moderationStatus", moderationStatus)
return c
}
// BanAuthor sets the optional parameter "banAuthor": The banAuthor
// parameter lets you indicate that you want to automatically reject any
// additional comments written by the comment's author. Set the
// parameter value to true to ban the author.
//
// Note: This parameter is only valid if the moderationStatus parameter
// is also set to rejected.
func (c *CommentsSetModerationStatusCall) BanAuthor(banAuthor bool) *CommentsSetModerationStatusCall {
c.urlParams_.Set("banAuthor", fmt.Sprint(banAuthor))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsSetModerationStatusCall) Fields(s ...googleapi.Field) *CommentsSetModerationStatusCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentsSetModerationStatusCall) Context(ctx context.Context) *CommentsSetModerationStatusCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentsSetModerationStatusCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentsSetModerationStatusCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "comments/setModerationStatus")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.comments.setModerationStatus" call.
func (c *CommentsSetModerationStatusCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Sets the moderation status of one or more comments. The API request must be authorized by the owner of the channel or video associated with the comments.",
// "httpMethod": "POST",
// "id": "youtube.comments.setModerationStatus",
// "parameterOrder": [
// "id",
// "moderationStatus"
// ],
// "parameters": {
// "banAuthor": {
// "default": "false",
// "description": "The banAuthor parameter lets you indicate that you want to automatically reject any additional comments written by the comment's author. Set the parameter value to true to ban the author.\n\nNote: This parameter is only valid if the moderationStatus parameter is also set to rejected.",
// "location": "query",
// "type": "boolean"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of IDs that identify the comments for which you are updating the moderation status.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "moderationStatus": {
// "description": "Identifies the new moderation status of the specified comments.",
// "enum": [
// "heldForReview",
// "published",
// "rejected"
// ],
// "enumDescriptions": [
// "Marks a comment as awaiting review by a moderator.",
// "Clears a comment for public display.",
// "Rejects a comment as being unfit for display. This action also effectively hides all replies to the rejected comment.\n\nNote: The API does not currently provide a way to list or otherwise discover rejected comments. However, you can change the moderation status of a rejected comment if you still know its ID. If you were to change the moderation status of a rejected comment, the comment replies would subsequently be discoverable again as well."
// ],
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "comments/setModerationStatus",
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.comments.update":
type CommentsUpdateCall struct {
s *Service
comment *Comment
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Modifies a comment.
func (r *CommentsService) Update(part string, comment *Comment) *CommentsUpdateCall {
c := &CommentsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.comment = comment
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CommentsUpdateCall) Fields(s ...googleapi.Field) *CommentsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CommentsUpdateCall) Context(ctx context.Context) *CommentsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CommentsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CommentsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.comment)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "comments")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.comments.update" call.
// Exactly one of *Comment or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Comment.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *CommentsUpdateCall) Do(opts ...googleapi.CallOption) (*Comment, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Comment{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Modifies a comment.",
// "httpMethod": "PUT",
// "id": "youtube.comments.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter identifies the properties that the API response will include. You must at least include the snippet part in the parameter value since that part contains all of the properties that the API request can update.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "comments",
// "request": {
// "$ref": "Comment"
// },
// "response": {
// "$ref": "Comment"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.guideCategories.list":
type GuideCategoriesListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of categories that can be associated with
// YouTube channels.
func (r *GuideCategoriesService) List(part string) *GuideCategoriesListCall {
c := &GuideCategoriesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter specifies the
// language that will be used for text values in the API response.
func (c *GuideCategoriesListCall) Hl(hl string) *GuideCategoriesListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of the YouTube channel category ID(s) for the
// resource(s) that are being retrieved. In a guideCategory resource,
// the id property specifies the YouTube channel category ID.
func (c *GuideCategoriesListCall) Id(id string) *GuideCategoriesListCall {
c.urlParams_.Set("id", id)
return c
}
// RegionCode sets the optional parameter "regionCode": The regionCode
// parameter instructs the API to return the list of guide categories
// available in the specified country. The parameter value is an ISO
// 3166-1 alpha-2 country code.
func (c *GuideCategoriesListCall) RegionCode(regionCode string) *GuideCategoriesListCall {
c.urlParams_.Set("regionCode", regionCode)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GuideCategoriesListCall) Fields(s ...googleapi.Field) *GuideCategoriesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *GuideCategoriesListCall) IfNoneMatch(entityTag string) *GuideCategoriesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GuideCategoriesListCall) Context(ctx context.Context) *GuideCategoriesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *GuideCategoriesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *GuideCategoriesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "guideCategories")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.guideCategories.list" call.
// Exactly one of *GuideCategoryListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *GuideCategoryListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *GuideCategoriesListCall) Do(opts ...googleapi.CallOption) (*GuideCategoryListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GuideCategoryListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of categories that can be associated with YouTube channels.",
// "httpMethod": "GET",
// "id": "youtube.guideCategories.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "hl": {
// "default": "en-US",
// "description": "The hl parameter specifies the language that will be used for text values in the API response.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube channel category ID(s) for the resource(s) that are being retrieved. In a guideCategory resource, the id property specifies the YouTube channel category ID.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the guideCategory resource properties that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "regionCode": {
// "description": "The regionCode parameter instructs the API to return the list of guide categories available in the specified country. The parameter value is an ISO 3166-1 alpha-2 country code.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "guideCategories",
// "response": {
// "$ref": "GuideCategoryListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.i18nLanguages.list":
type I18nLanguagesListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of application languages that the YouTube
// website supports.
func (r *I18nLanguagesService) List(part string) *I18nLanguagesListCall {
c := &I18nLanguagesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter specifies the
// language that should be used for text values in the API response.
func (c *I18nLanguagesListCall) Hl(hl string) *I18nLanguagesListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *I18nLanguagesListCall) Fields(s ...googleapi.Field) *I18nLanguagesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *I18nLanguagesListCall) IfNoneMatch(entityTag string) *I18nLanguagesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *I18nLanguagesListCall) Context(ctx context.Context) *I18nLanguagesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *I18nLanguagesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *I18nLanguagesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "i18nLanguages")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.i18nLanguages.list" call.
// Exactly one of *I18nLanguageListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *I18nLanguageListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *I18nLanguagesListCall) Do(opts ...googleapi.CallOption) (*I18nLanguageListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &I18nLanguageListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of application languages that the YouTube website supports.",
// "httpMethod": "GET",
// "id": "youtube.i18nLanguages.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "hl": {
// "default": "en_US",
// "description": "The hl parameter specifies the language that should be used for text values in the API response.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the i18nLanguage resource properties that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "i18nLanguages",
// "response": {
// "$ref": "I18nLanguageListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.i18nRegions.list":
type I18nRegionsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of content regions that the YouTube website
// supports.
func (r *I18nRegionsService) List(part string) *I18nRegionsListCall {
c := &I18nRegionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter specifies the
// language that should be used for text values in the API response.
func (c *I18nRegionsListCall) Hl(hl string) *I18nRegionsListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *I18nRegionsListCall) Fields(s ...googleapi.Field) *I18nRegionsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *I18nRegionsListCall) IfNoneMatch(entityTag string) *I18nRegionsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *I18nRegionsListCall) Context(ctx context.Context) *I18nRegionsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *I18nRegionsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *I18nRegionsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "i18nRegions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.i18nRegions.list" call.
// Exactly one of *I18nRegionListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *I18nRegionListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *I18nRegionsListCall) Do(opts ...googleapi.CallOption) (*I18nRegionListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &I18nRegionListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of content regions that the YouTube website supports.",
// "httpMethod": "GET",
// "id": "youtube.i18nRegions.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "hl": {
// "default": "en_US",
// "description": "The hl parameter specifies the language that should be used for text values in the API response.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the i18nRegion resource properties that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "i18nRegions",
// "response": {
// "$ref": "I18nRegionListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.liveBroadcasts.bind":
type LiveBroadcastsBindCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Bind: Binds a YouTube broadcast to a stream or removes an existing
// binding between a broadcast and a stream. A broadcast can only be
// bound to one video stream, though a video stream may be bound to more
// than one broadcast.
func (r *LiveBroadcastsService) Bind(id string, part string) *LiveBroadcastsBindCall {
c := &LiveBroadcastsBindCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
c.urlParams_.Set("part", part)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsBindCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsBindCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsBindCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsBindCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// StreamId sets the optional parameter "streamId": The streamId
// parameter specifies the unique ID of the video stream that is being
// bound to a broadcast. If this parameter is omitted, the API will
// remove any existing binding between the broadcast and a video stream.
func (c *LiveBroadcastsBindCall) StreamId(streamId string) *LiveBroadcastsBindCall {
c.urlParams_.Set("streamId", streamId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsBindCall) Fields(s ...googleapi.Field) *LiveBroadcastsBindCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsBindCall) Context(ctx context.Context) *LiveBroadcastsBindCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsBindCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsBindCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts/bind")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.bind" call.
// Exactly one of *LiveBroadcast or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveBroadcast.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveBroadcastsBindCall) Do(opts ...googleapi.CallOption) (*LiveBroadcast, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveBroadcast{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Binds a YouTube broadcast to a stream or removes an existing binding between a broadcast and a stream. A broadcast can only be bound to one video stream, though a video stream may be bound to more than one broadcast.",
// "httpMethod": "POST",
// "id": "youtube.liveBroadcasts.bind",
// "parameterOrder": [
// "id",
// "part"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the unique ID of the broadcast that is being bound to a video stream.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "streamId": {
// "description": "The streamId parameter specifies the unique ID of the video stream that is being bound to a broadcast. If this parameter is omitted, the API will remove any existing binding between the broadcast and a video stream.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "liveBroadcasts/bind",
// "response": {
// "$ref": "LiveBroadcast"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveBroadcasts.control":
type LiveBroadcastsControlCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Control: Controls the settings for a slate that can be displayed in
// the broadcast stream.
func (r *LiveBroadcastsService) Control(id string, part string) *LiveBroadcastsControlCall {
c := &LiveBroadcastsControlCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
c.urlParams_.Set("part", part)
return c
}
// DisplaySlate sets the optional parameter "displaySlate": The
// displaySlate parameter specifies whether the slate is being enabled
// or disabled.
func (c *LiveBroadcastsControlCall) DisplaySlate(displaySlate bool) *LiveBroadcastsControlCall {
c.urlParams_.Set("displaySlate", fmt.Sprint(displaySlate))
return c
}
// OffsetTimeMs sets the optional parameter "offsetTimeMs": The
// offsetTimeMs parameter specifies a positive time offset when the
// specified slate change will occur. The value is measured in
// milliseconds from the beginning of the broadcast's monitor stream,
// which is the time that the testing phase for the broadcast began.
// Even though it is specified in milliseconds, the value is actually an
// approximation, and YouTube completes the requested action as closely
// as possible to that time.
//
// If you do not specify a value for this parameter, then YouTube
// performs the action as soon as possible. See the Getting started
// guide for more details.
//
// Important: You should only specify a value for this parameter if your
// broadcast stream is delayed.
func (c *LiveBroadcastsControlCall) OffsetTimeMs(offsetTimeMs uint64) *LiveBroadcastsControlCall {
c.urlParams_.Set("offsetTimeMs", fmt.Sprint(offsetTimeMs))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsControlCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsControlCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsControlCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsControlCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Walltime sets the optional parameter "walltime": The walltime
// parameter specifies the wall clock time at which the specified slate
// change will occur. The value is specified in ISO 8601
// (YYYY-MM-DDThh:mm:ss.sssZ) format.
func (c *LiveBroadcastsControlCall) Walltime(walltime string) *LiveBroadcastsControlCall {
c.urlParams_.Set("walltime", walltime)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsControlCall) Fields(s ...googleapi.Field) *LiveBroadcastsControlCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsControlCall) Context(ctx context.Context) *LiveBroadcastsControlCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsControlCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsControlCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts/control")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.control" call.
// Exactly one of *LiveBroadcast or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveBroadcast.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveBroadcastsControlCall) Do(opts ...googleapi.CallOption) (*LiveBroadcast, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveBroadcast{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Controls the settings for a slate that can be displayed in the broadcast stream.",
// "httpMethod": "POST",
// "id": "youtube.liveBroadcasts.control",
// "parameterOrder": [
// "id",
// "part"
// ],
// "parameters": {
// "displaySlate": {
// "description": "The displaySlate parameter specifies whether the slate is being enabled or disabled.",
// "location": "query",
// "type": "boolean"
// },
// "id": {
// "description": "The id parameter specifies the YouTube live broadcast ID that uniquely identifies the broadcast in which the slate is being updated.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "offsetTimeMs": {
// "description": "The offsetTimeMs parameter specifies a positive time offset when the specified slate change will occur. The value is measured in milliseconds from the beginning of the broadcast's monitor stream, which is the time that the testing phase for the broadcast began. Even though it is specified in milliseconds, the value is actually an approximation, and YouTube completes the requested action as closely as possible to that time.\n\nIf you do not specify a value for this parameter, then YouTube performs the action as soon as possible. See the Getting started guide for more details.\n\nImportant: You should only specify a value for this parameter if your broadcast stream is delayed.",
// "format": "uint64",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "walltime": {
// "description": "The walltime parameter specifies the wall clock time at which the specified slate change will occur. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sssZ) format.",
// "format": "date-time",
// "location": "query",
// "type": "string"
// }
// },
// "path": "liveBroadcasts/control",
// "response": {
// "$ref": "LiveBroadcast"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveBroadcasts.delete":
type LiveBroadcastsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a broadcast.
func (r *LiveBroadcastsService) Delete(id string) *LiveBroadcastsDeleteCall {
c := &LiveBroadcastsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsDeleteCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsDeleteCall) Fields(s ...googleapi.Field) *LiveBroadcastsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsDeleteCall) Context(ctx context.Context) *LiveBroadcastsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.delete" call.
func (c *LiveBroadcastsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a broadcast.",
// "httpMethod": "DELETE",
// "id": "youtube.liveBroadcasts.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube live broadcast ID for the resource that is being deleted.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "liveBroadcasts",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveBroadcasts.insert":
type LiveBroadcastsInsertCall struct {
s *Service
livebroadcast *LiveBroadcast
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a broadcast.
func (r *LiveBroadcastsService) Insert(part string, livebroadcast *LiveBroadcast) *LiveBroadcastsInsertCall {
c := &LiveBroadcastsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livebroadcast = livebroadcast
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsInsertCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsInsertCall) Fields(s ...googleapi.Field) *LiveBroadcastsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsInsertCall) Context(ctx context.Context) *LiveBroadcastsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livebroadcast)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.insert" call.
// Exactly one of *LiveBroadcast or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveBroadcast.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveBroadcastsInsertCall) Do(opts ...googleapi.CallOption) (*LiveBroadcast, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveBroadcast{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a broadcast.",
// "httpMethod": "POST",
// "id": "youtube.liveBroadcasts.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe part properties that you can include in the parameter value are id, snippet, contentDetails, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveBroadcasts",
// "request": {
// "$ref": "LiveBroadcast"
// },
// "response": {
// "$ref": "LiveBroadcast"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveBroadcasts.list":
type LiveBroadcastsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of YouTube broadcasts that match the API request
// parameters.
func (r *LiveBroadcastsService) List(part string) *LiveBroadcastsListCall {
c := &LiveBroadcastsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// BroadcastStatus sets the optional parameter "broadcastStatus": The
// broadcastStatus parameter filters the API response to only include
// broadcasts with the specified status.
//
// Possible values:
// "active" - Return current live broadcasts.
// "all" - Return all broadcasts.
// "completed" - Return broadcasts that have already ended.
// "upcoming" - Return broadcasts that have not yet started.
func (c *LiveBroadcastsListCall) BroadcastStatus(broadcastStatus string) *LiveBroadcastsListCall {
c.urlParams_.Set("broadcastStatus", broadcastStatus)
return c
}
// BroadcastType sets the optional parameter "broadcastType": The
// broadcastType parameter filters the API response to only include
// broadcasts with the specified type. This is only compatible with the
// mine filter for now.
//
// Possible values:
// "all" - Return all broadcasts.
// "event" - Return only scheduled event broadcasts.
// "persistent" - Return only persistent broadcasts.
func (c *LiveBroadcastsListCall) BroadcastType(broadcastType string) *LiveBroadcastsListCall {
c.urlParams_.Set("broadcastType", broadcastType)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of YouTube broadcast IDs that identify the
// broadcasts being retrieved. In a liveBroadcast resource, the id
// property specifies the broadcast's ID.
func (c *LiveBroadcastsListCall) Id(id string) *LiveBroadcastsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *LiveBroadcastsListCall) MaxResults(maxResults int64) *LiveBroadcastsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// Mine sets the optional parameter "mine": The mine parameter can be
// used to instruct the API to only return broadcasts owned by the
// authenticated user. Set the parameter value to true to only retrieve
// your own broadcasts.
func (c *LiveBroadcastsListCall) Mine(mine bool) *LiveBroadcastsListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsListCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsListCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *LiveBroadcastsListCall) PageToken(pageToken string) *LiveBroadcastsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsListCall) Fields(s ...googleapi.Field) *LiveBroadcastsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *LiveBroadcastsListCall) IfNoneMatch(entityTag string) *LiveBroadcastsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsListCall) Context(ctx context.Context) *LiveBroadcastsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.list" call.
// Exactly one of *LiveBroadcastListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *LiveBroadcastListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveBroadcastsListCall) Do(opts ...googleapi.CallOption) (*LiveBroadcastListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveBroadcastListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of YouTube broadcasts that match the API request parameters.",
// "httpMethod": "GET",
// "id": "youtube.liveBroadcasts.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "broadcastStatus": {
// "description": "The broadcastStatus parameter filters the API response to only include broadcasts with the specified status.",
// "enum": [
// "active",
// "all",
// "completed",
// "upcoming"
// ],
// "enumDescriptions": [
// "Return current live broadcasts.",
// "Return all broadcasts.",
// "Return broadcasts that have already ended.",
// "Return broadcasts that have not yet started."
// ],
// "location": "query",
// "type": "string"
// },
// "broadcastType": {
// "default": "BROADCAST_TYPE_FILTER_EVENT",
// "description": "The broadcastType parameter filters the API response to only include broadcasts with the specified type. This is only compatible with the mine filter for now.",
// "enum": [
// "all",
// "event",
// "persistent"
// ],
// "enumDescriptions": [
// "Return all broadcasts.",
// "Return only scheduled event broadcasts.",
// "Return only persistent broadcasts."
// ],
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of YouTube broadcast IDs that identify the broadcasts being retrieved. In a liveBroadcast resource, the id property specifies the broadcast's ID.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "mine": {
// "description": "The mine parameter can be used to instruct the API to only return broadcasts owned by the authenticated user. Set the parameter value to true to only retrieve your own broadcasts.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveBroadcasts",
// "response": {
// "$ref": "LiveBroadcastListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *LiveBroadcastsListCall) Pages(ctx context.Context, f func(*LiveBroadcastListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.liveBroadcasts.transition":
type LiveBroadcastsTransitionCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Transition: Changes the status of a YouTube live broadcast and
// initiates any processes associated with the new status. For example,
// when you transition a broadcast's status to testing, YouTube starts
// to transmit video to that broadcast's monitor stream. Before calling
// this method, you should confirm that the value of the
// status.streamStatus property for the stream bound to your broadcast
// is active.
func (r *LiveBroadcastsService) Transition(broadcastStatus string, id string, part string) *LiveBroadcastsTransitionCall {
c := &LiveBroadcastsTransitionCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("broadcastStatus", broadcastStatus)
c.urlParams_.Set("id", id)
c.urlParams_.Set("part", part)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsTransitionCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsTransitionCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsTransitionCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsTransitionCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsTransitionCall) Fields(s ...googleapi.Field) *LiveBroadcastsTransitionCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsTransitionCall) Context(ctx context.Context) *LiveBroadcastsTransitionCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsTransitionCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsTransitionCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts/transition")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.transition" call.
// Exactly one of *LiveBroadcast or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveBroadcast.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveBroadcastsTransitionCall) Do(opts ...googleapi.CallOption) (*LiveBroadcast, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveBroadcast{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Changes the status of a YouTube live broadcast and initiates any processes associated with the new status. For example, when you transition a broadcast's status to testing, YouTube starts to transmit video to that broadcast's monitor stream. Before calling this method, you should confirm that the value of the status.streamStatus property for the stream bound to your broadcast is active.",
// "httpMethod": "POST",
// "id": "youtube.liveBroadcasts.transition",
// "parameterOrder": [
// "broadcastStatus",
// "id",
// "part"
// ],
// "parameters": {
// "broadcastStatus": {
// "description": "The broadcastStatus parameter identifies the state to which the broadcast is changing. Note that to transition a broadcast to either the testing or live state, the status.streamStatus must be active for the stream that the broadcast is bound to.",
// "enum": [
// "complete",
// "live",
// "testing"
// ],
// "enumDescriptions": [
// "The broadcast is over. YouTube stops transmitting video.",
// "The broadcast is visible to its audience. YouTube transmits video to the broadcast's monitor stream and its broadcast stream.",
// "Start testing the broadcast. YouTube transmits video to the broadcast's monitor stream. Note that you can only transition a broadcast to the testing state if its contentDetails.monitorStream.enableMonitorStream property is set to true."
// ],
// "location": "query",
// "required": true,
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies the unique ID of the broadcast that is transitioning to another status.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more liveBroadcast resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, contentDetails, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveBroadcasts/transition",
// "response": {
// "$ref": "LiveBroadcast"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveBroadcasts.update":
type LiveBroadcastsUpdateCall struct {
s *Service
livebroadcast *LiveBroadcast
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a broadcast. For example, you could modify the
// broadcast settings defined in the liveBroadcast resource's
// contentDetails object.
func (r *LiveBroadcastsService) Update(part string, livebroadcast *LiveBroadcast) *LiveBroadcastsUpdateCall {
c := &LiveBroadcastsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livebroadcast = livebroadcast
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveBroadcastsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveBroadcastsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveBroadcastsUpdateCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveBroadcastsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveBroadcastsUpdateCall) Fields(s ...googleapi.Field) *LiveBroadcastsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveBroadcastsUpdateCall) Context(ctx context.Context) *LiveBroadcastsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveBroadcastsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveBroadcastsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livebroadcast)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveBroadcasts")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveBroadcasts.update" call.
// Exactly one of *LiveBroadcast or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveBroadcast.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveBroadcastsUpdateCall) Do(opts ...googleapi.CallOption) (*LiveBroadcast, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveBroadcast{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a broadcast. For example, you could modify the broadcast settings defined in the liveBroadcast resource's contentDetails object.",
// "httpMethod": "PUT",
// "id": "youtube.liveBroadcasts.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe part properties that you can include in the parameter value are id, snippet, contentDetails, and status.\n\nNote that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a broadcast's privacy status is defined in the status part. As such, if your request is updating a private or unlisted broadcast, and the request's part parameter value includes the status part, the broadcast's privacy setting will be updated to whatever value the request body specifies. If the request body does not specify a value, the existing privacy setting will be removed and the broadcast will revert to the default privacy setting.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveBroadcasts",
// "request": {
// "$ref": "LiveBroadcast"
// },
// "response": {
// "$ref": "LiveBroadcast"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatBans.delete":
type LiveChatBansDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Removes a chat ban.
func (r *LiveChatBansService) Delete(id string) *LiveChatBansDeleteCall {
c := &LiveChatBansDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatBansDeleteCall) Fields(s ...googleapi.Field) *LiveChatBansDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatBansDeleteCall) Context(ctx context.Context) *LiveChatBansDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatBansDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatBansDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/bans")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatBans.delete" call.
func (c *LiveChatBansDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Removes a chat ban.",
// "httpMethod": "DELETE",
// "id": "youtube.liveChatBans.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter identifies the chat ban to remove. The value uniquely identifies both the ban and the chat.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/bans",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatBans.insert":
type LiveChatBansInsertCall struct {
s *Service
livechatban *LiveChatBan
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Adds a new ban to the chat.
func (r *LiveChatBansService) Insert(part string, livechatban *LiveChatBan) *LiveChatBansInsertCall {
c := &LiveChatBansInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livechatban = livechatban
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatBansInsertCall) Fields(s ...googleapi.Field) *LiveChatBansInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatBansInsertCall) Context(ctx context.Context) *LiveChatBansInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatBansInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatBansInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livechatban)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/bans")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatBans.insert" call.
// Exactly one of *LiveChatBan or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveChatBan.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *LiveChatBansInsertCall) Do(opts ...googleapi.CallOption) (*LiveChatBan, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveChatBan{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a new ban to the chat.",
// "httpMethod": "POST",
// "id": "youtube.liveChatBans.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response returns. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/bans",
// "request": {
// "$ref": "LiveChatBan"
// },
// "response": {
// "$ref": "LiveChatBan"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatMessages.delete":
type LiveChatMessagesDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a chat message.
func (r *LiveChatMessagesService) Delete(id string) *LiveChatMessagesDeleteCall {
c := &LiveChatMessagesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatMessagesDeleteCall) Fields(s ...googleapi.Field) *LiveChatMessagesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatMessagesDeleteCall) Context(ctx context.Context) *LiveChatMessagesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatMessagesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatMessagesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/messages")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatMessages.delete" call.
func (c *LiveChatMessagesDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a chat message.",
// "httpMethod": "DELETE",
// "id": "youtube.liveChatMessages.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube chat message ID of the resource that is being deleted.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/messages",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatMessages.insert":
type LiveChatMessagesInsertCall struct {
s *Service
livechatmessage *LiveChatMessage
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Adds a message to a live chat.
func (r *LiveChatMessagesService) Insert(part string, livechatmessage *LiveChatMessage) *LiveChatMessagesInsertCall {
c := &LiveChatMessagesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livechatmessage = livechatmessage
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatMessagesInsertCall) Fields(s ...googleapi.Field) *LiveChatMessagesInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatMessagesInsertCall) Context(ctx context.Context) *LiveChatMessagesInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatMessagesInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatMessagesInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livechatmessage)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/messages")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatMessages.insert" call.
// Exactly one of *LiveChatMessage or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveChatMessage.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveChatMessagesInsertCall) Do(opts ...googleapi.CallOption) (*LiveChatMessage, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveChatMessage{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a message to a live chat.",
// "httpMethod": "POST",
// "id": "youtube.liveChatMessages.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter serves two purposes. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/messages",
// "request": {
// "$ref": "LiveChatMessage"
// },
// "response": {
// "$ref": "LiveChatMessage"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatMessages.list":
type LiveChatMessagesListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists live chat messages for a specific chat.
func (r *LiveChatMessagesService) List(liveChatId string, part string) *LiveChatMessagesListCall {
c := &LiveChatMessagesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("liveChatId", liveChatId)
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter instructs the
// API to retrieve localized resource metadata for a specific
// application language that the YouTube website supports. The parameter
// value must be a language code included in the list returned by the
// i18nLanguages.list method.
//
// If localized resource details are available in that language, the
// resource's snippet.localized object will contain the localized
// values. However, if localized details are not available, the
// snippet.localized object will contain resource details in the
// resource's default language.
func (c *LiveChatMessagesListCall) Hl(hl string) *LiveChatMessagesListCall {
c.urlParams_.Set("hl", hl)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of messages that should be
// returned in the result set.
func (c *LiveChatMessagesListCall) MaxResults(maxResults int64) *LiveChatMessagesListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken property identify
// other pages that could be retrieved.
func (c *LiveChatMessagesListCall) PageToken(pageToken string) *LiveChatMessagesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// ProfileImageSize sets the optional parameter "profileImageSize": The
// profileImageSize parameter specifies the size of the user profile
// pictures that should be returned in the result set. Default: 88.
func (c *LiveChatMessagesListCall) ProfileImageSize(profileImageSize int64) *LiveChatMessagesListCall {
c.urlParams_.Set("profileImageSize", fmt.Sprint(profileImageSize))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatMessagesListCall) Fields(s ...googleapi.Field) *LiveChatMessagesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *LiveChatMessagesListCall) IfNoneMatch(entityTag string) *LiveChatMessagesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatMessagesListCall) Context(ctx context.Context) *LiveChatMessagesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatMessagesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatMessagesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/messages")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatMessages.list" call.
// Exactly one of *LiveChatMessageListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *LiveChatMessageListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveChatMessagesListCall) Do(opts ...googleapi.CallOption) (*LiveChatMessageListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveChatMessageListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists live chat messages for a specific chat.",
// "httpMethod": "GET",
// "id": "youtube.liveChatMessages.list",
// "parameterOrder": [
// "liveChatId",
// "part"
// ],
// "parameters": {
// "hl": {
// "description": "The hl parameter instructs the API to retrieve localized resource metadata for a specific application language that the YouTube website supports. The parameter value must be a language code included in the list returned by the i18nLanguages.list method.\n\nIf localized resource details are available in that language, the resource's snippet.localized object will contain the localized values. However, if localized details are not available, the snippet.localized object will contain resource details in the resource's default language.",
// "location": "query",
// "type": "string"
// },
// "liveChatId": {
// "description": "The liveChatId parameter specifies the ID of the chat whose messages will be returned.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "maxResults": {
// "default": "500",
// "description": "The maxResults parameter specifies the maximum number of messages that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "2000",
// "minimum": "200",
// "type": "integer"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the liveChatComment resource parts that the API response will include. Supported values are id and snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "profileImageSize": {
// "description": "The profileImageSize parameter specifies the size of the user profile pictures that should be returned in the result set. Default: 88.",
// "format": "uint32",
// "location": "query",
// "maximum": "720",
// "minimum": "16",
// "type": "integer"
// }
// },
// "path": "liveChat/messages",
// "response": {
// "$ref": "LiveChatMessageListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *LiveChatMessagesListCall) Pages(ctx context.Context, f func(*LiveChatMessageListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.liveChatModerators.delete":
type LiveChatModeratorsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Removes a chat moderator.
func (r *LiveChatModeratorsService) Delete(id string) *LiveChatModeratorsDeleteCall {
c := &LiveChatModeratorsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatModeratorsDeleteCall) Fields(s ...googleapi.Field) *LiveChatModeratorsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatModeratorsDeleteCall) Context(ctx context.Context) *LiveChatModeratorsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatModeratorsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatModeratorsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/moderators")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatModerators.delete" call.
func (c *LiveChatModeratorsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Removes a chat moderator.",
// "httpMethod": "DELETE",
// "id": "youtube.liveChatModerators.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter identifies the chat moderator to remove. The value uniquely identifies both the moderator and the chat.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/moderators",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatModerators.insert":
type LiveChatModeratorsInsertCall struct {
s *Service
livechatmoderator *LiveChatModerator
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Adds a new moderator for the chat.
func (r *LiveChatModeratorsService) Insert(part string, livechatmoderator *LiveChatModerator) *LiveChatModeratorsInsertCall {
c := &LiveChatModeratorsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livechatmoderator = livechatmoderator
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatModeratorsInsertCall) Fields(s ...googleapi.Field) *LiveChatModeratorsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatModeratorsInsertCall) Context(ctx context.Context) *LiveChatModeratorsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatModeratorsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatModeratorsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livechatmoderator)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/moderators")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatModerators.insert" call.
// Exactly one of *LiveChatModerator or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *LiveChatModerator.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveChatModeratorsInsertCall) Do(opts ...googleapi.CallOption) (*LiveChatModerator, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveChatModerator{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a new moderator for the chat.",
// "httpMethod": "POST",
// "id": "youtube.liveChatModerators.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response returns. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/moderators",
// "request": {
// "$ref": "LiveChatModerator"
// },
// "response": {
// "$ref": "LiveChatModerator"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveChatModerators.list":
type LiveChatModeratorsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists moderators for a live chat.
func (r *LiveChatModeratorsService) List(liveChatId string, part string) *LiveChatModeratorsListCall {
c := &LiveChatModeratorsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("liveChatId", liveChatId)
c.urlParams_.Set("part", part)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *LiveChatModeratorsListCall) MaxResults(maxResults int64) *LiveChatModeratorsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *LiveChatModeratorsListCall) PageToken(pageToken string) *LiveChatModeratorsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveChatModeratorsListCall) Fields(s ...googleapi.Field) *LiveChatModeratorsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *LiveChatModeratorsListCall) IfNoneMatch(entityTag string) *LiveChatModeratorsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveChatModeratorsListCall) Context(ctx context.Context) *LiveChatModeratorsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveChatModeratorsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveChatModeratorsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveChat/moderators")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveChatModerators.list" call.
// Exactly one of *LiveChatModeratorListResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *LiveChatModeratorListResponse.ServerResponse.Header or (if a
// response was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveChatModeratorsListCall) Do(opts ...googleapi.CallOption) (*LiveChatModeratorListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveChatModeratorListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists moderators for a live chat.",
// "httpMethod": "GET",
// "id": "youtube.liveChatModerators.list",
// "parameterOrder": [
// "liveChatId",
// "part"
// ],
// "parameters": {
// "liveChatId": {
// "description": "The liveChatId parameter specifies the YouTube live chat for which the API should return moderators.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the liveChatModerator resource parts that the API response will include. Supported values are id and snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveChat/moderators",
// "response": {
// "$ref": "LiveChatModeratorListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *LiveChatModeratorsListCall) Pages(ctx context.Context, f func(*LiveChatModeratorListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.liveStreams.delete":
type LiveStreamsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a video stream.
func (r *LiveStreamsService) Delete(id string) *LiveStreamsDeleteCall {
c := &LiveStreamsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveStreamsDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveStreamsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveStreamsDeleteCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveStreamsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveStreamsDeleteCall) Fields(s ...googleapi.Field) *LiveStreamsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveStreamsDeleteCall) Context(ctx context.Context) *LiveStreamsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveStreamsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveStreamsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveStreams")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveStreams.delete" call.
func (c *LiveStreamsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a video stream.",
// "httpMethod": "DELETE",
// "id": "youtube.liveStreams.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube live stream ID for the resource that is being deleted.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "liveStreams",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveStreams.insert":
type LiveStreamsInsertCall struct {
s *Service
livestream *LiveStream
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a video stream. The stream enables you to send your
// video to YouTube, which can then broadcast the video to your
// audience.
func (r *LiveStreamsService) Insert(part string, livestream *LiveStream) *LiveStreamsInsertCall {
c := &LiveStreamsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livestream = livestream
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveStreamsInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveStreamsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveStreamsInsertCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveStreamsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveStreamsInsertCall) Fields(s ...googleapi.Field) *LiveStreamsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveStreamsInsertCall) Context(ctx context.Context) *LiveStreamsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveStreamsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveStreamsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livestream)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveStreams")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveStreams.insert" call.
// Exactly one of *LiveStream or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveStream.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *LiveStreamsInsertCall) Do(opts ...googleapi.CallOption) (*LiveStream, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveStream{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a video stream. The stream enables you to send your video to YouTube, which can then broadcast the video to your audience.",
// "httpMethod": "POST",
// "id": "youtube.liveStreams.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe part properties that you can include in the parameter value are id, snippet, cdn, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveStreams",
// "request": {
// "$ref": "LiveStream"
// },
// "response": {
// "$ref": "LiveStream"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.liveStreams.list":
type LiveStreamsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of video streams that match the API request
// parameters.
func (r *LiveStreamsService) List(part string) *LiveStreamsListCall {
c := &LiveStreamsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of YouTube stream IDs that identify the streams
// being retrieved. In a liveStream resource, the id property specifies
// the stream's ID.
func (c *LiveStreamsListCall) Id(id string) *LiveStreamsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *LiveStreamsListCall) MaxResults(maxResults int64) *LiveStreamsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// Mine sets the optional parameter "mine": The mine parameter can be
// used to instruct the API to only return streams owned by the
// authenticated user. Set the parameter value to true to only retrieve
// your own streams.
func (c *LiveStreamsListCall) Mine(mine bool) *LiveStreamsListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveStreamsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveStreamsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveStreamsListCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveStreamsListCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *LiveStreamsListCall) PageToken(pageToken string) *LiveStreamsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveStreamsListCall) Fields(s ...googleapi.Field) *LiveStreamsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *LiveStreamsListCall) IfNoneMatch(entityTag string) *LiveStreamsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveStreamsListCall) Context(ctx context.Context) *LiveStreamsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveStreamsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveStreamsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveStreams")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveStreams.list" call.
// Exactly one of *LiveStreamListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *LiveStreamListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *LiveStreamsListCall) Do(opts ...googleapi.CallOption) (*LiveStreamListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveStreamListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of video streams that match the API request parameters.",
// "httpMethod": "GET",
// "id": "youtube.liveStreams.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies a comma-separated list of YouTube stream IDs that identify the streams being retrieved. In a liveStream resource, the id property specifies the stream's ID.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "mine": {
// "description": "The mine parameter can be used to instruct the API to only return streams owned by the authenticated user. Set the parameter value to true to only retrieve your own streams.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more liveStream resource properties that the API response will include. The part names that you can include in the parameter value are id, snippet, cdn, and status.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveStreams",
// "response": {
// "$ref": "LiveStreamListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *LiveStreamsListCall) Pages(ctx context.Context, f func(*LiveStreamListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.liveStreams.update":
type LiveStreamsUpdateCall struct {
s *Service
livestream *LiveStream
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a video stream. If the properties that you want to
// change cannot be updated, then you need to create a new stream with
// the proper settings.
func (r *LiveStreamsService) Update(part string, livestream *LiveStream) *LiveStreamsUpdateCall {
c := &LiveStreamsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.livestream = livestream
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *LiveStreamsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *LiveStreamsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *LiveStreamsUpdateCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *LiveStreamsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LiveStreamsUpdateCall) Fields(s ...googleapi.Field) *LiveStreamsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LiveStreamsUpdateCall) Context(ctx context.Context) *LiveStreamsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LiveStreamsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LiveStreamsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.livestream)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "liveStreams")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.liveStreams.update" call.
// Exactly one of *LiveStream or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *LiveStream.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *LiveStreamsUpdateCall) Do(opts ...googleapi.CallOption) (*LiveStream, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LiveStream{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a video stream. If the properties that you want to change cannot be updated, then you need to create a new stream with the proper settings.",
// "httpMethod": "PUT",
// "id": "youtube.liveStreams.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nThe part properties that you can include in the parameter value are id, snippet, cdn, and status.\n\nNote that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. If the request body does not specify a value for a mutable property, the existing value for that property will be removed.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "liveStreams",
// "request": {
// "$ref": "LiveStream"
// },
// "response": {
// "$ref": "LiveStream"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl"
// ]
// }
}
// method id "youtube.playlistItems.delete":
type PlaylistItemsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a playlist item.
func (r *PlaylistItemsService) Delete(id string) *PlaylistItemsDeleteCall {
c := &PlaylistItemsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistItemsDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistItemsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistItemsDeleteCall) Fields(s ...googleapi.Field) *PlaylistItemsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistItemsDeleteCall) Context(ctx context.Context) *PlaylistItemsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistItemsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistItemsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlistItems")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlistItems.delete" call.
func (c *PlaylistItemsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a playlist item.",
// "httpMethod": "DELETE",
// "id": "youtube.playlistItems.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube playlist item ID for the playlist item that is being deleted. In a playlistItem resource, the id property specifies the playlist item's ID.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "playlistItems",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.playlistItems.insert":
type PlaylistItemsInsertCall struct {
s *Service
playlistitem *PlaylistItem
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Adds a resource to a playlist.
func (r *PlaylistItemsService) Insert(part string, playlistitem *PlaylistItem) *PlaylistItemsInsertCall {
c := &PlaylistItemsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.playlistitem = playlistitem
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistItemsInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistItemsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistItemsInsertCall) Fields(s ...googleapi.Field) *PlaylistItemsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistItemsInsertCall) Context(ctx context.Context) *PlaylistItemsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistItemsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistItemsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.playlistitem)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlistItems")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlistItems.insert" call.
// Exactly one of *PlaylistItem or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *PlaylistItem.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *PlaylistItemsInsertCall) Do(opts ...googleapi.CallOption) (*PlaylistItem, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &PlaylistItem{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a resource to a playlist.",
// "httpMethod": "POST",
// "id": "youtube.playlistItems.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "playlistItems",
// "request": {
// "$ref": "PlaylistItem"
// },
// "response": {
// "$ref": "PlaylistItem"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.playlistItems.list":
type PlaylistItemsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a collection of playlist items that match the API
// request parameters. You can retrieve all of the playlist items in a
// specified playlist or retrieve one or more playlist items by their
// unique IDs.
func (r *PlaylistItemsService) List(part string) *PlaylistItemsListCall {
c := &PlaylistItemsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of one or more unique playlist item IDs.
func (c *PlaylistItemsListCall) Id(id string) *PlaylistItemsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *PlaylistItemsListCall) MaxResults(maxResults int64) *PlaylistItemsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistItemsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistItemsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *PlaylistItemsListCall) PageToken(pageToken string) *PlaylistItemsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// PlaylistId sets the optional parameter "playlistId": The playlistId
// parameter specifies the unique ID of the playlist for which you want
// to retrieve playlist items. Note that even though this is an optional
// parameter, every request to retrieve playlist items must specify a
// value for either the id parameter or the playlistId parameter.
func (c *PlaylistItemsListCall) PlaylistId(playlistId string) *PlaylistItemsListCall {
c.urlParams_.Set("playlistId", playlistId)
return c
}
// VideoId sets the optional parameter "videoId": The videoId parameter
// specifies that the request should return only the playlist items that
// contain the specified video.
func (c *PlaylistItemsListCall) VideoId(videoId string) *PlaylistItemsListCall {
c.urlParams_.Set("videoId", videoId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistItemsListCall) Fields(s ...googleapi.Field) *PlaylistItemsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *PlaylistItemsListCall) IfNoneMatch(entityTag string) *PlaylistItemsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistItemsListCall) Context(ctx context.Context) *PlaylistItemsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistItemsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistItemsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlistItems")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlistItems.list" call.
// Exactly one of *PlaylistItemListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *PlaylistItemListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *PlaylistItemsListCall) Do(opts ...googleapi.CallOption) (*PlaylistItemListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &PlaylistItemListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a collection of playlist items that match the API request parameters. You can retrieve all of the playlist items in a specified playlist or retrieve one or more playlist items by their unique IDs.",
// "httpMethod": "GET",
// "id": "youtube.playlistItems.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies a comma-separated list of one or more unique playlist item IDs.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more playlistItem resource properties that the API response will include.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a playlistItem resource, the snippet property contains numerous fields, including the title, description, position, and resourceId properties. As such, if you set part=snippet, the API response will contain all of those properties.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "playlistId": {
// "description": "The playlistId parameter specifies the unique ID of the playlist for which you want to retrieve playlist items. Note that even though this is an optional parameter, every request to retrieve playlist items must specify a value for either the id parameter or the playlistId parameter.",
// "location": "query",
// "type": "string"
// },
// "videoId": {
// "description": "The videoId parameter specifies that the request should return only the playlist items that contain the specified video.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "playlistItems",
// "response": {
// "$ref": "PlaylistItemListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsSubscription": true
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *PlaylistItemsListCall) Pages(ctx context.Context, f func(*PlaylistItemListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.playlistItems.update":
type PlaylistItemsUpdateCall struct {
s *Service
playlistitem *PlaylistItem
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Modifies a playlist item. For example, you could update the
// item's position in the playlist.
func (r *PlaylistItemsService) Update(part string, playlistitem *PlaylistItem) *PlaylistItemsUpdateCall {
c := &PlaylistItemsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.playlistitem = playlistitem
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistItemsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistItemsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistItemsUpdateCall) Fields(s ...googleapi.Field) *PlaylistItemsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistItemsUpdateCall) Context(ctx context.Context) *PlaylistItemsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistItemsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistItemsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.playlistitem)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlistItems")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlistItems.update" call.
// Exactly one of *PlaylistItem or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *PlaylistItem.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *PlaylistItemsUpdateCall) Do(opts ...googleapi.CallOption) (*PlaylistItem, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &PlaylistItem{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Modifies a playlist item. For example, you could update the item's position in the playlist.",
// "httpMethod": "PUT",
// "id": "youtube.playlistItems.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nNote that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a playlist item can specify a start time and end time, which identify the times portion of the video that should play when users watch the video in the playlist. If your request is updating a playlist item that sets these values, and the request's part parameter value includes the contentDetails part, the playlist item's start and end times will be updated to whatever value the request body specifies. If the request body does not specify values, the existing start and end times will be removed and replaced with the default settings.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "playlistItems",
// "request": {
// "$ref": "PlaylistItem"
// },
// "response": {
// "$ref": "PlaylistItem"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.playlists.delete":
type PlaylistsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a playlist.
func (r *PlaylistsService) Delete(id string) *PlaylistsDeleteCall {
c := &PlaylistsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistsDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistsDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistsDeleteCall) Fields(s ...googleapi.Field) *PlaylistsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistsDeleteCall) Context(ctx context.Context) *PlaylistsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlists")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlists.delete" call.
func (c *PlaylistsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a playlist.",
// "httpMethod": "DELETE",
// "id": "youtube.playlists.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube playlist ID for the playlist that is being deleted. In a playlist resource, the id property specifies the playlist's ID.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "playlists",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.playlists.insert":
type PlaylistsInsertCall struct {
s *Service
playlist *Playlist
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a playlist.
func (r *PlaylistsService) Insert(part string, playlist *Playlist) *PlaylistsInsertCall {
c := &PlaylistsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.playlist = playlist
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistsInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *PlaylistsInsertCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *PlaylistsInsertCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistsInsertCall) Fields(s ...googleapi.Field) *PlaylistsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistsInsertCall) Context(ctx context.Context) *PlaylistsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.playlist)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlists")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlists.insert" call.
// Exactly one of *Playlist or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Playlist.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *PlaylistsInsertCall) Do(opts ...googleapi.CallOption) (*Playlist, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Playlist{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a playlist.",
// "httpMethod": "POST",
// "id": "youtube.playlists.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "playlists",
// "request": {
// "$ref": "Playlist"
// },
// "response": {
// "$ref": "Playlist"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.playlists.list":
type PlaylistsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a collection of playlists that match the API request
// parameters. For example, you can retrieve all playlists that the
// authenticated user owns, or you can retrieve one or more playlists by
// their unique IDs.
func (r *PlaylistsService) List(part string) *PlaylistsListCall {
c := &PlaylistsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// ChannelId sets the optional parameter "channelId": This value
// indicates that the API should only return the specified channel's
// playlists.
func (c *PlaylistsListCall) ChannelId(channelId string) *PlaylistsListCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// Hl sets the optional parameter "hl": The hl parameter should be used
// for filter out the properties that are not in the given language.
// Used for the snippet part.
func (c *PlaylistsListCall) Hl(hl string) *PlaylistsListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of the YouTube playlist ID(s) for the
// resource(s) that are being retrieved. In a playlist resource, the id
// property specifies the playlist's YouTube playlist ID.
func (c *PlaylistsListCall) Id(id string) *PlaylistsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *PlaylistsListCall) MaxResults(maxResults int64) *PlaylistsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// Mine sets the optional parameter "mine": Set this parameter's value
// to true to instruct the API to only return playlists owned by the
// authenticated user.
func (c *PlaylistsListCall) Mine(mine bool) *PlaylistsListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *PlaylistsListCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *PlaylistsListCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *PlaylistsListCall) PageToken(pageToken string) *PlaylistsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistsListCall) Fields(s ...googleapi.Field) *PlaylistsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *PlaylistsListCall) IfNoneMatch(entityTag string) *PlaylistsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistsListCall) Context(ctx context.Context) *PlaylistsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlists")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlists.list" call.
// Exactly one of *PlaylistListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *PlaylistListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *PlaylistsListCall) Do(opts ...googleapi.CallOption) (*PlaylistListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &PlaylistListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a collection of playlists that match the API request parameters. For example, you can retrieve all playlists that the authenticated user owns, or you can retrieve one or more playlists by their unique IDs.",
// "httpMethod": "GET",
// "id": "youtube.playlists.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "channelId": {
// "description": "This value indicates that the API should only return the specified channel's playlists.",
// "location": "query",
// "type": "string"
// },
// "hl": {
// "description": "The hl parameter should be used for filter out the properties that are not in the given language. Used for the snippet part.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube playlist ID(s) for the resource(s) that are being retrieved. In a playlist resource, the id property specifies the playlist's YouTube playlist ID.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "mine": {
// "description": "Set this parameter's value to true to instruct the API to only return playlists owned by the authenticated user.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more playlist resource properties that the API response will include.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a playlist resource, the snippet property contains properties like author, title, description, tags, and timeCreated. As such, if you set part=snippet, the API response will contain all of those properties.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "playlists",
// "response": {
// "$ref": "PlaylistListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *PlaylistsListCall) Pages(ctx context.Context, f func(*PlaylistListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.playlists.update":
type PlaylistsUpdateCall struct {
s *Service
playlist *Playlist
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Modifies a playlist. For example, you could change a
// playlist's title, description, or privacy status.
func (r *PlaylistsService) Update(part string, playlist *Playlist) *PlaylistsUpdateCall {
c := &PlaylistsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.playlist = playlist
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *PlaylistsUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *PlaylistsUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *PlaylistsUpdateCall) Fields(s ...googleapi.Field) *PlaylistsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *PlaylistsUpdateCall) Context(ctx context.Context) *PlaylistsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *PlaylistsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *PlaylistsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.playlist)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "playlists")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.playlists.update" call.
// Exactly one of *Playlist or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Playlist.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *PlaylistsUpdateCall) Do(opts ...googleapi.CallOption) (*Playlist, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Playlist{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Modifies a playlist. For example, you could change a playlist's title, description, or privacy status.",
// "httpMethod": "PUT",
// "id": "youtube.playlists.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nNote that this method will override the existing values for mutable properties that are contained in any parts that the request body specifies. For example, a playlist's description is contained in the snippet part, which must be included in the request body. If the request does not specify a value for the snippet.description property, the playlist's existing description will be deleted.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "playlists",
// "request": {
// "$ref": "Playlist"
// },
// "response": {
// "$ref": "Playlist"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.search.list":
type SearchListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a collection of search results that match the query
// parameters specified in the API request. By default, a search result
// set identifies matching video, channel, and playlist resources, but
// you can also configure queries to only retrieve a specific type of
// resource.
func (r *SearchService) List(part string) *SearchListCall {
c := &SearchListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// ChannelId sets the optional parameter "channelId": The channelId
// parameter indicates that the API response should only contain
// resources created by the channel
func (c *SearchListCall) ChannelId(channelId string) *SearchListCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// ChannelType sets the optional parameter "channelType": The
// channelType parameter lets you restrict a search to a particular type
// of channel.
//
// Possible values:
// "any" - Return all channels.
// "show" - Only retrieve shows.
func (c *SearchListCall) ChannelType(channelType string) *SearchListCall {
c.urlParams_.Set("channelType", channelType)
return c
}
// EventType sets the optional parameter "eventType": The eventType
// parameter restricts a search to broadcast events. If you specify a
// value for this parameter, you must also set the type parameter's
// value to video.
//
// Possible values:
// "completed" - Only include completed broadcasts.
// "live" - Only include active broadcasts.
// "upcoming" - Only include upcoming broadcasts.
func (c *SearchListCall) EventType(eventType string) *SearchListCall {
c.urlParams_.Set("eventType", eventType)
return c
}
// ForContentOwner sets the optional parameter "forContentOwner": Note:
// This parameter is intended exclusively for YouTube content
// partners.
//
// The forContentOwner parameter restricts the search to only retrieve
// resources owned by the content owner specified by the
// onBehalfOfContentOwner parameter. The user must be authenticated
// using a CMS account linked to the specified content owner and
// onBehalfOfContentOwner must be provided.
func (c *SearchListCall) ForContentOwner(forContentOwner bool) *SearchListCall {
c.urlParams_.Set("forContentOwner", fmt.Sprint(forContentOwner))
return c
}
// ForDeveloper sets the optional parameter "forDeveloper": The
// forDeveloper parameter restricts the search to only retrieve videos
// uploaded via the developer's application or website. The API server
// uses the request's authorization credentials to identify the
// developer. Therefore, a developer can restrict results to videos
// uploaded through the developer's own app or website but not to videos
// uploaded through other apps or sites.
func (c *SearchListCall) ForDeveloper(forDeveloper bool) *SearchListCall {
c.urlParams_.Set("forDeveloper", fmt.Sprint(forDeveloper))
return c
}
// ForMine sets the optional parameter "forMine": The forMine parameter
// restricts the search to only retrieve videos owned by the
// authenticated user. If you set this parameter to true, then the type
// parameter's value must also be set to video.
func (c *SearchListCall) ForMine(forMine bool) *SearchListCall {
c.urlParams_.Set("forMine", fmt.Sprint(forMine))
return c
}
// Location sets the optional parameter "location": The location
// parameter, in conjunction with the locationRadius parameter, defines
// a circular geographic area and also restricts a search to videos that
// specify, in their metadata, a geographic location that falls within
// that area. The parameter value is a string that specifies
// latitude/longitude coordinates e.g. (37.42307,-122.08427).
//
//
// - The location parameter value identifies the point at the center of
// the area.
// - The locationRadius parameter specifies the maximum distance that
// the location associated with a video can be from that point for the
// video to still be included in the search results.The API returns an
// error if your request specifies a value for the location parameter
// but does not also specify a value for the locationRadius parameter.
func (c *SearchListCall) Location(location string) *SearchListCall {
c.urlParams_.Set("location", location)
return c
}
// LocationRadius sets the optional parameter "locationRadius": The
// locationRadius parameter, in conjunction with the location parameter,
// defines a circular geographic area.
//
// The parameter value must be a floating point number followed by a
// measurement unit. Valid measurement units are m, km, ft, and mi. For
// example, valid parameter values include 1500m, 5km, 10000ft, and
// 0.75mi. The API does not support locationRadius parameter values
// larger than 1000 kilometers.
//
// Note: See the definition of the location parameter for more
// information.
func (c *SearchListCall) LocationRadius(locationRadius string) *SearchListCall {
c.urlParams_.Set("locationRadius", locationRadius)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *SearchListCall) MaxResults(maxResults int64) *SearchListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *SearchListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *SearchListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Order sets the optional parameter "order": The order parameter
// specifies the method that will be used to order resources in the API
// response.
//
// Possible values:
// "date" - Resources are sorted in reverse chronological order based
// on the date they were created.
// "rating" - Resources are sorted from highest to lowest rating.
// "relevance" - Resources are sorted based on their relevance to the
// search query. This is the default value for this parameter.
// "title" - Resources are sorted alphabetically by title.
// "videoCount" - Channels are sorted in descending order of their
// number of uploaded videos.
// "viewCount" - Resources are sorted from highest to lowest number of
// views.
func (c *SearchListCall) Order(order string) *SearchListCall {
c.urlParams_.Set("order", order)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *SearchListCall) PageToken(pageToken string) *SearchListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// PublishedAfter sets the optional parameter "publishedAfter": The
// publishedAfter parameter indicates that the API response should only
// contain resources created after the specified time. The value is an
// RFC 3339 formatted date-time value (1970-01-01T00:00:00Z).
func (c *SearchListCall) PublishedAfter(publishedAfter string) *SearchListCall {
c.urlParams_.Set("publishedAfter", publishedAfter)
return c
}
// PublishedBefore sets the optional parameter "publishedBefore": The
// publishedBefore parameter indicates that the API response should only
// contain resources created before the specified time. The value is an
// RFC 3339 formatted date-time value (1970-01-01T00:00:00Z).
func (c *SearchListCall) PublishedBefore(publishedBefore string) *SearchListCall {
c.urlParams_.Set("publishedBefore", publishedBefore)
return c
}
// Q sets the optional parameter "q": The q parameter specifies the
// query term to search for.
//
// Your request can also use the Boolean NOT (-) and OR (|) operators to
// exclude videos or to find videos that are associated with one of
// several search terms. For example, to search for videos matching
// either "boating" or "sailing", set the q parameter value to
// boating|sailing. Similarly, to search for videos matching either
// "boating" or "sailing" but not "fishing", set the q parameter value
// to boating|sailing -fishing. Note that the pipe character must be
// URL-escaped when it is sent in your API request. The URL-escaped
// value for the pipe character is %7C.
func (c *SearchListCall) Q(q string) *SearchListCall {
c.urlParams_.Set("q", q)
return c
}
// RegionCode sets the optional parameter "regionCode": The regionCode
// parameter instructs the API to return search results for the
// specified country. The parameter value is an ISO 3166-1 alpha-2
// country code.
func (c *SearchListCall) RegionCode(regionCode string) *SearchListCall {
c.urlParams_.Set("regionCode", regionCode)
return c
}
// RelatedToVideoId sets the optional parameter "relatedToVideoId": The
// relatedToVideoId parameter retrieves a list of videos that are
// related to the video that the parameter value identifies. The
// parameter value must be set to a YouTube video ID and, if you are
// using this parameter, the type parameter must be set to video.
func (c *SearchListCall) RelatedToVideoId(relatedToVideoId string) *SearchListCall {
c.urlParams_.Set("relatedToVideoId", relatedToVideoId)
return c
}
// RelevanceLanguage sets the optional parameter "relevanceLanguage":
// The relevanceLanguage parameter instructs the API to return search
// results that are most relevant to the specified language. The
// parameter value is typically an ISO 639-1 two-letter language code.
// However, you should use the values zh-Hans for simplified Chinese and
// zh-Hant for traditional Chinese. Please note that results in other
// languages will still be returned if they are highly relevant to the
// search query term.
func (c *SearchListCall) RelevanceLanguage(relevanceLanguage string) *SearchListCall {
c.urlParams_.Set("relevanceLanguage", relevanceLanguage)
return c
}
// SafeSearch sets the optional parameter "safeSearch": The safeSearch
// parameter indicates whether the search results should include
// restricted content as well as standard content.
//
// Possible values:
// "moderate" - YouTube will filter some content from search results
// and, at the least, will filter content that is restricted in your
// locale. Based on their content, search results could be removed from
// search results or demoted in search results. This is the default
// parameter value.
// "none" - YouTube will not filter the search result set.
// "strict" - YouTube will try to exclude all restricted content from
// the search result set. Based on their content, search results could
// be removed from search results or demoted in search results.
func (c *SearchListCall) SafeSearch(safeSearch string) *SearchListCall {
c.urlParams_.Set("safeSearch", safeSearch)
return c
}
// TopicId sets the optional parameter "topicId": The topicId parameter
// indicates that the API response should only contain resources
// associated with the specified topic. The value identifies a Freebase
// topic ID.
func (c *SearchListCall) TopicId(topicId string) *SearchListCall {
c.urlParams_.Set("topicId", topicId)
return c
}
// Type sets the optional parameter "type": The type parameter restricts
// a search query to only retrieve a particular type of resource. The
// value is a comma-separated list of resource types.
func (c *SearchListCall) Type(type_ string) *SearchListCall {
c.urlParams_.Set("type", type_)
return c
}
// VideoCaption sets the optional parameter "videoCaption": The
// videoCaption parameter indicates whether the API should filter video
// search results based on whether they have captions. If you specify a
// value for this parameter, you must also set the type parameter's
// value to video.
//
// Possible values:
// "any" - Do not filter results based on caption availability.
// "closedCaption" - Only include videos that have captions.
// "none" - Only include videos that do not have captions.
func (c *SearchListCall) VideoCaption(videoCaption string) *SearchListCall {
c.urlParams_.Set("videoCaption", videoCaption)
return c
}
// VideoCategoryId sets the optional parameter "videoCategoryId": The
// videoCategoryId parameter filters video search results based on their
// category. If you specify a value for this parameter, you must also
// set the type parameter's value to video.
func (c *SearchListCall) VideoCategoryId(videoCategoryId string) *SearchListCall {
c.urlParams_.Set("videoCategoryId", videoCategoryId)
return c
}
// VideoDefinition sets the optional parameter "videoDefinition": The
// videoDefinition parameter lets you restrict a search to only include
// either high definition (HD) or standard definition (SD) videos. HD
// videos are available for playback in at least 720p, though higher
// resolutions, like 1080p, might also be available. If you specify a
// value for this parameter, you must also set the type parameter's
// value to video.
//
// Possible values:
// "any" - Return all videos, regardless of their resolution.
// "high" - Only retrieve HD videos.
// "standard" - Only retrieve videos in standard definition.
func (c *SearchListCall) VideoDefinition(videoDefinition string) *SearchListCall {
c.urlParams_.Set("videoDefinition", videoDefinition)
return c
}
// VideoDimension sets the optional parameter "videoDimension": The
// videoDimension parameter lets you restrict a search to only retrieve
// 2D or 3D videos. If you specify a value for this parameter, you must
// also set the type parameter's value to video.
//
// Possible values:
// "2d" - Restrict search results to exclude 3D videos.
// "3d" - Restrict search results to only include 3D videos.
// "any" - Include both 3D and non-3D videos in returned results. This
// is the default value.
func (c *SearchListCall) VideoDimension(videoDimension string) *SearchListCall {
c.urlParams_.Set("videoDimension", videoDimension)
return c
}
// VideoDuration sets the optional parameter "videoDuration": The
// videoDuration parameter filters video search results based on their
// duration. If you specify a value for this parameter, you must also
// set the type parameter's value to video.
//
// Possible values:
// "any" - Do not filter video search results based on their duration.
// This is the default value.
// "long" - Only include videos longer than 20 minutes.
// "medium" - Only include videos that are between four and 20 minutes
// long (inclusive).
// "short" - Only include videos that are less than four minutes long.
func (c *SearchListCall) VideoDuration(videoDuration string) *SearchListCall {
c.urlParams_.Set("videoDuration", videoDuration)
return c
}
// VideoEmbeddable sets the optional parameter "videoEmbeddable": The
// videoEmbeddable parameter lets you to restrict a search to only
// videos that can be embedded into a webpage. If you specify a value
// for this parameter, you must also set the type parameter's value to
// video.
//
// Possible values:
// "any" - Return all videos, embeddable or not.
// "true" - Only retrieve embeddable videos.
func (c *SearchListCall) VideoEmbeddable(videoEmbeddable string) *SearchListCall {
c.urlParams_.Set("videoEmbeddable", videoEmbeddable)
return c
}
// VideoLicense sets the optional parameter "videoLicense": The
// videoLicense parameter filters search results to only include videos
// with a particular license. YouTube lets video uploaders choose to
// attach either the Creative Commons license or the standard YouTube
// license to each of their videos. If you specify a value for this
// parameter, you must also set the type parameter's value to video.
//
// Possible values:
// "any" - Return all videos, regardless of which license they have,
// that match the query parameters.
// "creativeCommon" - Only return videos that have a Creative Commons
// license. Users can reuse videos with this license in other videos
// that they create. Learn more.
// "youtube" - Only return videos that have the standard YouTube
// license.
func (c *SearchListCall) VideoLicense(videoLicense string) *SearchListCall {
c.urlParams_.Set("videoLicense", videoLicense)
return c
}
// VideoSyndicated sets the optional parameter "videoSyndicated": The
// videoSyndicated parameter lets you to restrict a search to only
// videos that can be played outside youtube.com. If you specify a value
// for this parameter, you must also set the type parameter's value to
// video.
//
// Possible values:
// "any" - Return all videos, syndicated or not.
// "true" - Only retrieve syndicated videos.
func (c *SearchListCall) VideoSyndicated(videoSyndicated string) *SearchListCall {
c.urlParams_.Set("videoSyndicated", videoSyndicated)
return c
}
// VideoType sets the optional parameter "videoType": The videoType
// parameter lets you restrict a search to a particular type of videos.
// If you specify a value for this parameter, you must also set the type
// parameter's value to video.
//
// Possible values:
// "any" - Return all videos.
// "episode" - Only retrieve episodes of shows.
// "movie" - Only retrieve movies.
func (c *SearchListCall) VideoType(videoType string) *SearchListCall {
c.urlParams_.Set("videoType", videoType)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *SearchListCall) Fields(s ...googleapi.Field) *SearchListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *SearchListCall) IfNoneMatch(entityTag string) *SearchListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *SearchListCall) Context(ctx context.Context) *SearchListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *SearchListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *SearchListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "search")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.search.list" call.
// Exactly one of *SearchListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *SearchListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *SearchListCall) Do(opts ...googleapi.CallOption) (*SearchListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &SearchListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a collection of search results that match the query parameters specified in the API request. By default, a search result set identifies matching video, channel, and playlist resources, but you can also configure queries to only retrieve a specific type of resource.",
// "httpMethod": "GET",
// "id": "youtube.search.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "channelId": {
// "description": "The channelId parameter indicates that the API response should only contain resources created by the channel",
// "location": "query",
// "type": "string"
// },
// "channelType": {
// "description": "The channelType parameter lets you restrict a search to a particular type of channel.",
// "enum": [
// "any",
// "show"
// ],
// "enumDescriptions": [
// "Return all channels.",
// "Only retrieve shows."
// ],
// "location": "query",
// "type": "string"
// },
// "eventType": {
// "description": "The eventType parameter restricts a search to broadcast events. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "completed",
// "live",
// "upcoming"
// ],
// "enumDescriptions": [
// "Only include completed broadcasts.",
// "Only include active broadcasts.",
// "Only include upcoming broadcasts."
// ],
// "location": "query",
// "type": "string"
// },
// "forContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe forContentOwner parameter restricts the search to only retrieve resources owned by the content owner specified by the onBehalfOfContentOwner parameter. The user must be authenticated using a CMS account linked to the specified content owner and onBehalfOfContentOwner must be provided.",
// "location": "query",
// "type": "boolean"
// },
// "forDeveloper": {
// "description": "The forDeveloper parameter restricts the search to only retrieve videos uploaded via the developer's application or website. The API server uses the request's authorization credentials to identify the developer. Therefore, a developer can restrict results to videos uploaded through the developer's own app or website but not to videos uploaded through other apps or sites.",
// "location": "query",
// "type": "boolean"
// },
// "forMine": {
// "description": "The forMine parameter restricts the search to only retrieve videos owned by the authenticated user. If you set this parameter to true, then the type parameter's value must also be set to video.",
// "location": "query",
// "type": "boolean"
// },
// "location": {
// "description": "The location parameter, in conjunction with the locationRadius parameter, defines a circular geographic area and also restricts a search to videos that specify, in their metadata, a geographic location that falls within that area. The parameter value is a string that specifies latitude/longitude coordinates e.g. (37.42307,-122.08427).\n\n\n- The location parameter value identifies the point at the center of the area.\n- The locationRadius parameter specifies the maximum distance that the location associated with a video can be from that point for the video to still be included in the search results.The API returns an error if your request specifies a value for the location parameter but does not also specify a value for the locationRadius parameter.",
// "location": "query",
// "type": "string"
// },
// "locationRadius": {
// "description": "The locationRadius parameter, in conjunction with the location parameter, defines a circular geographic area.\n\nThe parameter value must be a floating point number followed by a measurement unit. Valid measurement units are m, km, ft, and mi. For example, valid parameter values include 1500m, 5km, 10000ft, and 0.75mi. The API does not support locationRadius parameter values larger than 1000 kilometers.\n\nNote: See the definition of the location parameter for more information.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "order": {
// "default": "SEARCH_SORT_RELEVANCE",
// "description": "The order parameter specifies the method that will be used to order resources in the API response.",
// "enum": [
// "date",
// "rating",
// "relevance",
// "title",
// "videoCount",
// "viewCount"
// ],
// "enumDescriptions": [
// "Resources are sorted in reverse chronological order based on the date they were created.",
// "Resources are sorted from highest to lowest rating.",
// "Resources are sorted based on their relevance to the search query. This is the default value for this parameter.",
// "Resources are sorted alphabetically by title.",
// "Channels are sorted in descending order of their number of uploaded videos.",
// "Resources are sorted from highest to lowest number of views."
// ],
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more search resource properties that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "publishedAfter": {
// "description": "The publishedAfter parameter indicates that the API response should only contain resources created after the specified time. The value is an RFC 3339 formatted date-time value (1970-01-01T00:00:00Z).",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "publishedBefore": {
// "description": "The publishedBefore parameter indicates that the API response should only contain resources created before the specified time. The value is an RFC 3339 formatted date-time value (1970-01-01T00:00:00Z).",
// "format": "date-time",
// "location": "query",
// "type": "string"
// },
// "q": {
// "description": "The q parameter specifies the query term to search for.\n\nYour request can also use the Boolean NOT (-) and OR (|) operators to exclude videos or to find videos that are associated with one of several search terms. For example, to search for videos matching either \"boating\" or \"sailing\", set the q parameter value to boating|sailing. Similarly, to search for videos matching either \"boating\" or \"sailing\" but not \"fishing\", set the q parameter value to boating|sailing -fishing. Note that the pipe character must be URL-escaped when it is sent in your API request. The URL-escaped value for the pipe character is %7C.",
// "location": "query",
// "type": "string"
// },
// "regionCode": {
// "description": "The regionCode parameter instructs the API to return search results for the specified country. The parameter value is an ISO 3166-1 alpha-2 country code.",
// "location": "query",
// "type": "string"
// },
// "relatedToVideoId": {
// "description": "The relatedToVideoId parameter retrieves a list of videos that are related to the video that the parameter value identifies. The parameter value must be set to a YouTube video ID and, if you are using this parameter, the type parameter must be set to video.",
// "location": "query",
// "type": "string"
// },
// "relevanceLanguage": {
// "description": "The relevanceLanguage parameter instructs the API to return search results that are most relevant to the specified language. The parameter value is typically an ISO 639-1 two-letter language code. However, you should use the values zh-Hans for simplified Chinese and zh-Hant for traditional Chinese. Please note that results in other languages will still be returned if they are highly relevant to the search query term.",
// "location": "query",
// "type": "string"
// },
// "safeSearch": {
// "description": "The safeSearch parameter indicates whether the search results should include restricted content as well as standard content.",
// "enum": [
// "moderate",
// "none",
// "strict"
// ],
// "enumDescriptions": [
// "YouTube will filter some content from search results and, at the least, will filter content that is restricted in your locale. Based on their content, search results could be removed from search results or demoted in search results. This is the default parameter value.",
// "YouTube will not filter the search result set.",
// "YouTube will try to exclude all restricted content from the search result set. Based on their content, search results could be removed from search results or demoted in search results."
// ],
// "location": "query",
// "type": "string"
// },
// "topicId": {
// "description": "The topicId parameter indicates that the API response should only contain resources associated with the specified topic. The value identifies a Freebase topic ID.",
// "location": "query",
// "type": "string"
// },
// "type": {
// "default": "video,channel,playlist",
// "description": "The type parameter restricts a search query to only retrieve a particular type of resource. The value is a comma-separated list of resource types.",
// "location": "query",
// "type": "string"
// },
// "videoCaption": {
// "description": "The videoCaption parameter indicates whether the API should filter video search results based on whether they have captions. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "closedCaption",
// "none"
// ],
// "enumDescriptions": [
// "Do not filter results based on caption availability.",
// "Only include videos that have captions.",
// "Only include videos that do not have captions."
// ],
// "location": "query",
// "type": "string"
// },
// "videoCategoryId": {
// "description": "The videoCategoryId parameter filters video search results based on their category. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "location": "query",
// "type": "string"
// },
// "videoDefinition": {
// "description": "The videoDefinition parameter lets you restrict a search to only include either high definition (HD) or standard definition (SD) videos. HD videos are available for playback in at least 720p, though higher resolutions, like 1080p, might also be available. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "high",
// "standard"
// ],
// "enumDescriptions": [
// "Return all videos, regardless of their resolution.",
// "Only retrieve HD videos.",
// "Only retrieve videos in standard definition."
// ],
// "location": "query",
// "type": "string"
// },
// "videoDimension": {
// "description": "The videoDimension parameter lets you restrict a search to only retrieve 2D or 3D videos. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "2d",
// "3d",
// "any"
// ],
// "enumDescriptions": [
// "Restrict search results to exclude 3D videos.",
// "Restrict search results to only include 3D videos.",
// "Include both 3D and non-3D videos in returned results. This is the default value."
// ],
// "location": "query",
// "type": "string"
// },
// "videoDuration": {
// "description": "The videoDuration parameter filters video search results based on their duration. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "long",
// "medium",
// "short"
// ],
// "enumDescriptions": [
// "Do not filter video search results based on their duration. This is the default value.",
// "Only include videos longer than 20 minutes.",
// "Only include videos that are between four and 20 minutes long (inclusive).",
// "Only include videos that are less than four minutes long."
// ],
// "location": "query",
// "type": "string"
// },
// "videoEmbeddable": {
// "description": "The videoEmbeddable parameter lets you to restrict a search to only videos that can be embedded into a webpage. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "true"
// ],
// "enumDescriptions": [
// "Return all videos, embeddable or not.",
// "Only retrieve embeddable videos."
// ],
// "location": "query",
// "type": "string"
// },
// "videoLicense": {
// "description": "The videoLicense parameter filters search results to only include videos with a particular license. YouTube lets video uploaders choose to attach either the Creative Commons license or the standard YouTube license to each of their videos. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "creativeCommon",
// "youtube"
// ],
// "enumDescriptions": [
// "Return all videos, regardless of which license they have, that match the query parameters.",
// "Only return videos that have a Creative Commons license. Users can reuse videos with this license in other videos that they create. Learn more.",
// "Only return videos that have the standard YouTube license."
// ],
// "location": "query",
// "type": "string"
// },
// "videoSyndicated": {
// "description": "The videoSyndicated parameter lets you to restrict a search to only videos that can be played outside youtube.com. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "true"
// ],
// "enumDescriptions": [
// "Return all videos, syndicated or not.",
// "Only retrieve syndicated videos."
// ],
// "location": "query",
// "type": "string"
// },
// "videoType": {
// "description": "The videoType parameter lets you restrict a search to a particular type of videos. If you specify a value for this parameter, you must also set the type parameter's value to video.",
// "enum": [
// "any",
// "episode",
// "movie"
// ],
// "enumDescriptions": [
// "Return all videos.",
// "Only retrieve episodes of shows.",
// "Only retrieve movies."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "search",
// "response": {
// "$ref": "SearchListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *SearchListCall) Pages(ctx context.Context, f func(*SearchListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.sponsors.list":
type SponsorsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists sponsors for a channel.
func (r *SponsorsService) List(part string) *SponsorsListCall {
c := &SponsorsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Filter sets the optional parameter "filter": The filter parameter
// specifies which channel sponsors to return.
//
// Possible values:
// "all" - Return all sponsors, from newest to oldest.
// "newest" - Return the most recent sponsors, from newest to oldest.
func (c *SponsorsListCall) Filter(filter string) *SponsorsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *SponsorsListCall) MaxResults(maxResults int64) *SponsorsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *SponsorsListCall) PageToken(pageToken string) *SponsorsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *SponsorsListCall) Fields(s ...googleapi.Field) *SponsorsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *SponsorsListCall) IfNoneMatch(entityTag string) *SponsorsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *SponsorsListCall) Context(ctx context.Context) *SponsorsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *SponsorsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *SponsorsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "sponsors")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.sponsors.list" call.
// Exactly one of *SponsorListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *SponsorListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *SponsorsListCall) Do(opts ...googleapi.CallOption) (*SponsorListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &SponsorListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists sponsors for a channel.",
// "httpMethod": "GET",
// "id": "youtube.sponsors.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "filter": {
// "default": "POLL_NEWEST",
// "description": "The filter parameter specifies which channel sponsors to return.",
// "enum": [
// "all",
// "newest"
// ],
// "enumDescriptions": [
// "Return all sponsors, from newest to oldest.",
// "Return the most recent sponsors, from newest to oldest."
// ],
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the sponsor resource parts that the API response will include. Supported values are id and snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "sponsors",
// "response": {
// "$ref": "SponsorListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *SponsorsListCall) Pages(ctx context.Context, f func(*SponsorListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.subscriptions.delete":
type SubscriptionsDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a subscription.
func (r *SubscriptionsService) Delete(id string) *SubscriptionsDeleteCall {
c := &SubscriptionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *SubscriptionsDeleteCall) Fields(s ...googleapi.Field) *SubscriptionsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *SubscriptionsDeleteCall) Context(ctx context.Context) *SubscriptionsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *SubscriptionsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *SubscriptionsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "subscriptions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.subscriptions.delete" call.
func (c *SubscriptionsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a subscription.",
// "httpMethod": "DELETE",
// "id": "youtube.subscriptions.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube subscription ID for the resource that is being deleted. In a subscription resource, the id property specifies the YouTube subscription ID.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "subscriptions",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.subscriptions.insert":
type SubscriptionsInsertCall struct {
s *Service
subscription *Subscription
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Adds a subscription for the authenticated user's channel.
func (r *SubscriptionsService) Insert(part string, subscription *Subscription) *SubscriptionsInsertCall {
c := &SubscriptionsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.subscription = subscription
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *SubscriptionsInsertCall) Fields(s ...googleapi.Field) *SubscriptionsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *SubscriptionsInsertCall) Context(ctx context.Context) *SubscriptionsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *SubscriptionsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *SubscriptionsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.subscription)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "subscriptions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.subscriptions.insert" call.
// Exactly one of *Subscription or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Subscription.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *SubscriptionsInsertCall) Do(opts ...googleapi.CallOption) (*Subscription, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Subscription{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a subscription for the authenticated user's channel.",
// "httpMethod": "POST",
// "id": "youtube.subscriptions.insert",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "subscriptions",
// "request": {
// "$ref": "Subscription"
// },
// "response": {
// "$ref": "Subscription"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.subscriptions.list":
type SubscriptionsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns subscription resources that match the API request
// criteria.
func (r *SubscriptionsService) List(part string) *SubscriptionsListCall {
c := &SubscriptionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// ChannelId sets the optional parameter "channelId": The channelId
// parameter specifies a YouTube channel ID. The API will only return
// that channel's subscriptions.
func (c *SubscriptionsListCall) ChannelId(channelId string) *SubscriptionsListCall {
c.urlParams_.Set("channelId", channelId)
return c
}
// ForChannelId sets the optional parameter "forChannelId": The
// forChannelId parameter specifies a comma-separated list of channel
// IDs. The API response will then only contain subscriptions matching
// those channels.
func (c *SubscriptionsListCall) ForChannelId(forChannelId string) *SubscriptionsListCall {
c.urlParams_.Set("forChannelId", forChannelId)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of the YouTube subscription ID(s) for the
// resource(s) that are being retrieved. In a subscription resource, the
// id property specifies the YouTube subscription ID.
func (c *SubscriptionsListCall) Id(id string) *SubscriptionsListCall {
c.urlParams_.Set("id", id)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *SubscriptionsListCall) MaxResults(maxResults int64) *SubscriptionsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// Mine sets the optional parameter "mine": Set this parameter's value
// to true to retrieve a feed of the authenticated user's subscriptions.
func (c *SubscriptionsListCall) Mine(mine bool) *SubscriptionsListCall {
c.urlParams_.Set("mine", fmt.Sprint(mine))
return c
}
// MyRecentSubscribers sets the optional parameter
// "myRecentSubscribers": Set this parameter's value to true to retrieve
// a feed of the subscribers of the authenticated user in reverse
// chronological order (newest first).
func (c *SubscriptionsListCall) MyRecentSubscribers(myRecentSubscribers bool) *SubscriptionsListCall {
c.urlParams_.Set("myRecentSubscribers", fmt.Sprint(myRecentSubscribers))
return c
}
// MySubscribers sets the optional parameter "mySubscribers": Set this
// parameter's value to true to retrieve a feed of the subscribers of
// the authenticated user in no particular order.
func (c *SubscriptionsListCall) MySubscribers(mySubscribers bool) *SubscriptionsListCall {
c.urlParams_.Set("mySubscribers", fmt.Sprint(mySubscribers))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *SubscriptionsListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *SubscriptionsListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *SubscriptionsListCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *SubscriptionsListCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Order sets the optional parameter "order": The order parameter
// specifies the method that will be used to sort resources in the API
// response.
//
// Possible values:
// "alphabetical" - Sort alphabetically.
// "relevance" - Sort by relevance.
// "unread" - Sort by order of activity.
func (c *SubscriptionsListCall) Order(order string) *SubscriptionsListCall {
c.urlParams_.Set("order", order)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *SubscriptionsListCall) PageToken(pageToken string) *SubscriptionsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *SubscriptionsListCall) Fields(s ...googleapi.Field) *SubscriptionsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *SubscriptionsListCall) IfNoneMatch(entityTag string) *SubscriptionsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *SubscriptionsListCall) Context(ctx context.Context) *SubscriptionsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *SubscriptionsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *SubscriptionsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "subscriptions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.subscriptions.list" call.
// Exactly one of *SubscriptionListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *SubscriptionListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *SubscriptionsListCall) Do(opts ...googleapi.CallOption) (*SubscriptionListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &SubscriptionListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns subscription resources that match the API request criteria.",
// "httpMethod": "GET",
// "id": "youtube.subscriptions.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "channelId": {
// "description": "The channelId parameter specifies a YouTube channel ID. The API will only return that channel's subscriptions.",
// "location": "query",
// "type": "string"
// },
// "forChannelId": {
// "description": "The forChannelId parameter specifies a comma-separated list of channel IDs. The API response will then only contain subscriptions matching those channels.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube subscription ID(s) for the resource(s) that are being retrieved. In a subscription resource, the id property specifies the YouTube subscription ID.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "0",
// "type": "integer"
// },
// "mine": {
// "description": "Set this parameter's value to true to retrieve a feed of the authenticated user's subscriptions.",
// "location": "query",
// "type": "boolean"
// },
// "myRecentSubscribers": {
// "description": "Set this parameter's value to true to retrieve a feed of the subscribers of the authenticated user in reverse chronological order (newest first).",
// "location": "query",
// "type": "boolean"
// },
// "mySubscribers": {
// "description": "Set this parameter's value to true to retrieve a feed of the subscribers of the authenticated user in no particular order.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "order": {
// "default": "SUBSCRIPTION_ORDER_RELEVANCE",
// "description": "The order parameter specifies the method that will be used to sort resources in the API response.",
// "enum": [
// "alphabetical",
// "relevance",
// "unread"
// ],
// "enumDescriptions": [
// "Sort alphabetically.",
// "Sort by relevance.",
// "Sort by order of activity."
// ],
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more subscription resource properties that the API response will include.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a subscription resource, the snippet property contains other properties, such as a display title for the subscription. If you set part=snippet, the API response will also contain all of those nested properties.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "subscriptions",
// "response": {
// "$ref": "SubscriptionListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *SubscriptionsListCall) Pages(ctx context.Context, f func(*SubscriptionListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.superChatEvents.list":
type SuperChatEventsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists Super Chat events for a channel.
func (r *SuperChatEventsService) List(part string) *SuperChatEventsListCall {
c := &SuperChatEventsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter instructs the
// API to retrieve localized resource metadata for a specific
// application language that the YouTube website supports. The parameter
// value must be a language code included in the list returned by the
// i18nLanguages.list method.
//
// If localized resource details are available in that language, the
// resource's snippet.localized object will contain the localized
// values. However, if localized details are not available, the
// snippet.localized object will contain resource details in the
// resource's default language.
func (c *SuperChatEventsListCall) Hl(hl string) *SuperChatEventsListCall {
c.urlParams_.Set("hl", hl)
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
func (c *SuperChatEventsListCall) MaxResults(maxResults int64) *SuperChatEventsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
func (c *SuperChatEventsListCall) PageToken(pageToken string) *SuperChatEventsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *SuperChatEventsListCall) Fields(s ...googleapi.Field) *SuperChatEventsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *SuperChatEventsListCall) IfNoneMatch(entityTag string) *SuperChatEventsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *SuperChatEventsListCall) Context(ctx context.Context) *SuperChatEventsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *SuperChatEventsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *SuperChatEventsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "superChatEvents")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.superChatEvents.list" call.
// Exactly one of *SuperChatEventListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *SuperChatEventListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *SuperChatEventsListCall) Do(opts ...googleapi.CallOption) (*SuperChatEventListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &SuperChatEventListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists Super Chat events for a channel.",
// "httpMethod": "GET",
// "id": "youtube.superChatEvents.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "hl": {
// "description": "The hl parameter instructs the API to retrieve localized resource metadata for a specific application language that the YouTube website supports. The parameter value must be a language code included in the list returned by the i18nLanguages.list method.\n\nIf localized resource details are available in that language, the resource's snippet.localized object will contain the localized values. However, if localized details are not available, the snippet.localized object will contain resource details in the resource's default language.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "1",
// "type": "integer"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the superChatEvent resource parts that the API response will include. Supported values are id and snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "superChatEvents",
// "response": {
// "$ref": "SuperChatEventListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *SuperChatEventsListCall) Pages(ctx context.Context, f func(*SuperChatEventListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.thumbnails.set":
type ThumbnailsSetCall struct {
s *Service
urlParams_ gensupport.URLParams
mediaInfo_ *gensupport.MediaInfo
ctx_ context.Context
header_ http.Header
}
// Set: Uploads a custom video thumbnail to YouTube and sets it for a
// video.
func (r *ThumbnailsService) Set(videoId string) *ThumbnailsSetCall {
c := &ThumbnailsSetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("videoId", videoId)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *ThumbnailsSetCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *ThumbnailsSetCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *ThumbnailsSetCall) Media(r io.Reader, options ...googleapi.MediaOption) *ThumbnailsSetCall {
c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *ThumbnailsSetCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *ThumbnailsSetCall {
c.ctx_ = ctx
c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *ThumbnailsSetCall) ProgressUpdater(pu googleapi.ProgressUpdater) *ThumbnailsSetCall {
c.mediaInfo_.SetProgressUpdater(pu)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ThumbnailsSetCall) Fields(s ...googleapi.Field) *ThumbnailsSetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *ThumbnailsSetCall) Context(ctx context.Context) *ThumbnailsSetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ThumbnailsSetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ThumbnailsSetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "thumbnails/set")
if c.mediaInfo_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)
defer cleanup()
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
gensupport.SetGetBody(req, getBody)
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.thumbnails.set" call.
// Exactly one of *ThumbnailSetResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ThumbnailSetResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ThumbnailsSetCall) Do(opts ...googleapi.CallOption) (*ThumbnailSetResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))
if rx != nil {
rx.Client = c.s.client
rx.UserAgent = c.s.userAgent()
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &ThumbnailSetResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Uploads a custom video thumbnail to YouTube and sets it for a video.",
// "httpMethod": "POST",
// "id": "youtube.thumbnails.set",
// "mediaUpload": {
// "accept": [
// "application/octet-stream",
// "image/jpeg",
// "image/png"
// ],
// "maxSize": "2MB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/youtube/v3/thumbnails/set"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/youtube/v3/thumbnails/set"
// }
// }
// },
// "parameterOrder": [
// "videoId"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "videoId": {
// "description": "The videoId parameter specifies a YouTube video ID for which the custom video thumbnail is being provided.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "thumbnails/set",
// "response": {
// "$ref": "ThumbnailSetResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.upload",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsMediaUpload": true
// }
}
// method id "youtube.videoAbuseReportReasons.list":
type VideoAbuseReportReasonsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of abuse reasons that can be used for reporting
// abusive videos.
func (r *VideoAbuseReportReasonsService) List(part string) *VideoAbuseReportReasonsListCall {
c := &VideoAbuseReportReasonsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter specifies the
// language that should be used for text values in the API response.
func (c *VideoAbuseReportReasonsListCall) Hl(hl string) *VideoAbuseReportReasonsListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideoAbuseReportReasonsListCall) Fields(s ...googleapi.Field) *VideoAbuseReportReasonsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *VideoAbuseReportReasonsListCall) IfNoneMatch(entityTag string) *VideoAbuseReportReasonsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideoAbuseReportReasonsListCall) Context(ctx context.Context) *VideoAbuseReportReasonsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideoAbuseReportReasonsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideoAbuseReportReasonsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videoAbuseReportReasons")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videoAbuseReportReasons.list" call.
// Exactly one of *VideoAbuseReportReasonListResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *VideoAbuseReportReasonListResponse.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *VideoAbuseReportReasonsListCall) Do(opts ...googleapi.CallOption) (*VideoAbuseReportReasonListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &VideoAbuseReportReasonListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of abuse reasons that can be used for reporting abusive videos.",
// "httpMethod": "GET",
// "id": "youtube.videoAbuseReportReasons.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "hl": {
// "default": "en_US",
// "description": "The hl parameter specifies the language that should be used for text values in the API response.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the videoCategory resource parts that the API response will include. Supported values are id and snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "videoAbuseReportReasons",
// "response": {
// "$ref": "VideoAbuseReportReasonListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly"
// ]
// }
}
// method id "youtube.videoCategories.list":
type VideoCategoriesListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of categories that can be associated with
// YouTube videos.
func (r *VideoCategoriesService) List(part string) *VideoCategoriesListCall {
c := &VideoCategoriesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Hl sets the optional parameter "hl": The hl parameter specifies the
// language that should be used for text values in the API response.
func (c *VideoCategoriesListCall) Hl(hl string) *VideoCategoriesListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of video category IDs for the resources that you
// are retrieving.
func (c *VideoCategoriesListCall) Id(id string) *VideoCategoriesListCall {
c.urlParams_.Set("id", id)
return c
}
// RegionCode sets the optional parameter "regionCode": The regionCode
// parameter instructs the API to return the list of video categories
// available in the specified country. The parameter value is an ISO
// 3166-1 alpha-2 country code.
func (c *VideoCategoriesListCall) RegionCode(regionCode string) *VideoCategoriesListCall {
c.urlParams_.Set("regionCode", regionCode)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideoCategoriesListCall) Fields(s ...googleapi.Field) *VideoCategoriesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *VideoCategoriesListCall) IfNoneMatch(entityTag string) *VideoCategoriesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideoCategoriesListCall) Context(ctx context.Context) *VideoCategoriesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideoCategoriesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideoCategoriesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videoCategories")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videoCategories.list" call.
// Exactly one of *VideoCategoryListResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *VideoCategoryListResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *VideoCategoriesListCall) Do(opts ...googleapi.CallOption) (*VideoCategoryListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &VideoCategoryListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of categories that can be associated with YouTube videos.",
// "httpMethod": "GET",
// "id": "youtube.videoCategories.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "hl": {
// "default": "en_US",
// "description": "The hl parameter specifies the language that should be used for text values in the API response.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of video category IDs for the resources that you are retrieving.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies the videoCategory resource properties that the API response will include. Set the parameter value to snippet.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "regionCode": {
// "description": "The regionCode parameter instructs the API to return the list of video categories available in the specified country. The parameter value is an ISO 3166-1 alpha-2 country code.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "videoCategories",
// "response": {
// "$ref": "VideoCategoryListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.videos.delete":
type VideosDeleteCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a YouTube video.
func (r *VideosService) Delete(id string) *VideosDeleteCall {
c := &VideosDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *VideosDeleteCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *VideosDeleteCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosDeleteCall) Fields(s ...googleapi.Field) *VideosDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideosDeleteCall) Context(ctx context.Context) *VideosDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.delete" call.
func (c *VideosDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a YouTube video.",
// "httpMethod": "DELETE",
// "id": "youtube.videos.delete",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube video ID for the resource that is being deleted. In a video resource, the id property specifies the video's ID.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "videos",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.videos.getRating":
type VideosGetRatingCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// GetRating: Retrieves the ratings that the authorized user gave to a
// list of specified videos.
func (r *VideosService) GetRating(id string) *VideosGetRatingCall {
c := &VideosGetRatingCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *VideosGetRatingCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *VideosGetRatingCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosGetRatingCall) Fields(s ...googleapi.Field) *VideosGetRatingCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *VideosGetRatingCall) IfNoneMatch(entityTag string) *VideosGetRatingCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideosGetRatingCall) Context(ctx context.Context) *VideosGetRatingCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosGetRatingCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosGetRatingCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos/getRating")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.getRating" call.
// Exactly one of *VideoGetRatingResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *VideoGetRatingResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *VideosGetRatingCall) Do(opts ...googleapi.CallOption) (*VideoGetRatingResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &VideoGetRatingResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the ratings that the authorized user gave to a list of specified videos.",
// "httpMethod": "GET",
// "id": "youtube.videos.getRating",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube video ID(s) for the resource(s) for which you are retrieving rating data. In a video resource, the id property specifies the video's ID.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "videos/getRating",
// "response": {
// "$ref": "VideoGetRatingResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.videos.insert":
type VideosInsertCall struct {
s *Service
video *Video
urlParams_ gensupport.URLParams
mediaInfo_ *gensupport.MediaInfo
ctx_ context.Context
header_ http.Header
}
// Insert: Uploads a video to YouTube and optionally sets the video's
// metadata.
func (r *VideosService) Insert(part string, video *Video) *VideosInsertCall {
c := &VideosInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.video = video
return c
}
// AutoLevels sets the optional parameter "autoLevels": The autoLevels
// parameter indicates whether YouTube should automatically enhance the
// video's lighting and color.
func (c *VideosInsertCall) AutoLevels(autoLevels bool) *VideosInsertCall {
c.urlParams_.Set("autoLevels", fmt.Sprint(autoLevels))
return c
}
// NotifySubscribers sets the optional parameter "notifySubscribers":
// The notifySubscribers parameter indicates whether YouTube should send
// a notification about the new video to users who subscribe to the
// video's channel. A parameter value of True indicates that subscribers
// will be notified of newly uploaded videos. However, a channel owner
// who is uploading many videos might prefer to set the value to False
// to avoid sending a notification about each new video to the channel's
// subscribers.
func (c *VideosInsertCall) NotifySubscribers(notifySubscribers bool) *VideosInsertCall {
c.urlParams_.Set("notifySubscribers", fmt.Sprint(notifySubscribers))
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *VideosInsertCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *VideosInsertCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// OnBehalfOfContentOwnerChannel sets the optional parameter
// "onBehalfOfContentOwnerChannel": This parameter can only be used in a
// properly authorized request. Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwnerChannel parameter specifies the YouTube
// channel ID of the channel to which a video is being added. This
// parameter is required when a request specifies a value for the
// onBehalfOfContentOwner parameter, and it can only be used in
// conjunction with that parameter. In addition, the request must be
// authorized using a CMS account that is linked to the content owner
// that the onBehalfOfContentOwner parameter specifies. Finally, the
// channel that the onBehalfOfContentOwnerChannel parameter value
// specifies must be linked to the content owner that the
// onBehalfOfContentOwner parameter specifies.
//
// This parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and perform actions on behalf of the channel
// specified in the parameter value, without having to provide
// authentication credentials for each separate channel.
func (c *VideosInsertCall) OnBehalfOfContentOwnerChannel(onBehalfOfContentOwnerChannel string) *VideosInsertCall {
c.urlParams_.Set("onBehalfOfContentOwnerChannel", onBehalfOfContentOwnerChannel)
return c
}
// Stabilize sets the optional parameter "stabilize": The stabilize
// parameter indicates whether YouTube should adjust the video to remove
// shaky camera motions.
func (c *VideosInsertCall) Stabilize(stabilize bool) *VideosInsertCall {
c.urlParams_.Set("stabilize", fmt.Sprint(stabilize))
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *VideosInsertCall) Media(r io.Reader, options ...googleapi.MediaOption) *VideosInsertCall {
c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *VideosInsertCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *VideosInsertCall {
c.ctx_ = ctx
c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *VideosInsertCall) ProgressUpdater(pu googleapi.ProgressUpdater) *VideosInsertCall {
c.mediaInfo_.SetProgressUpdater(pu)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosInsertCall) Fields(s ...googleapi.Field) *VideosInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *VideosInsertCall) Context(ctx context.Context) *VideosInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.video)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos")
if c.mediaInfo_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)
defer cleanup()
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
gensupport.SetGetBody(req, getBody)
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.insert" call.
// Exactly one of *Video or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Video.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *VideosInsertCall) Do(opts ...googleapi.CallOption) (*Video, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))
if rx != nil {
rx.Client = c.s.client
rx.UserAgent = c.s.userAgent()
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &Video{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Uploads a video to YouTube and optionally sets the video's metadata.",
// "httpMethod": "POST",
// "id": "youtube.videos.insert",
// "mediaUpload": {
// "accept": [
// "application/octet-stream",
// "video/*"
// ],
// "maxSize": "64GB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/youtube/v3/videos"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/youtube/v3/videos"
// }
// }
// },
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "autoLevels": {
// "description": "The autoLevels parameter indicates whether YouTube should automatically enhance the video's lighting and color.",
// "location": "query",
// "type": "boolean"
// },
// "notifySubscribers": {
// "default": "true",
// "description": "The notifySubscribers parameter indicates whether YouTube should send a notification about the new video to users who subscribe to the video's channel. A parameter value of True indicates that subscribers will be notified of newly uploaded videos. However, a channel owner who is uploading many videos might prefer to set the value to False to avoid sending a notification about each new video to the channel's subscribers.",
// "location": "query",
// "type": "boolean"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwnerChannel": {
// "description": "This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.\n\nThis parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nNote that not all parts contain properties that can be set when inserting or updating a video. For example, the statistics object encapsulates statistics that YouTube calculates for a video and does not contain values that you can set or modify. If the parameter value specifies a part that does not contain mutable values, that part will still be included in the API response.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "stabilize": {
// "description": "The stabilize parameter indicates whether YouTube should adjust the video to remove shaky camera motions.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "videos",
// "request": {
// "$ref": "Video"
// },
// "response": {
// "$ref": "Video"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.upload",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsMediaUpload": true
// }
}
// method id "youtube.videos.list":
type VideosListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Returns a list of videos that match the API request parameters.
func (r *VideosService) List(part string) *VideosListCall {
c := &VideosListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
return c
}
// Chart sets the optional parameter "chart": The chart parameter
// identifies the chart that you want to retrieve.
//
// Possible values:
// "mostPopular" - Return the most popular videos for the specified
// content region and video category.
func (c *VideosListCall) Chart(chart string) *VideosListCall {
c.urlParams_.Set("chart", chart)
return c
}
// Hl sets the optional parameter "hl": The hl parameter instructs the
// API to retrieve localized resource metadata for a specific
// application language that the YouTube website supports. The parameter
// value must be a language code included in the list returned by the
// i18nLanguages.list method.
//
// If localized resource details are available in that language, the
// resource's snippet.localized object will contain the localized
// values. However, if localized details are not available, the
// snippet.localized object will contain resource details in the
// resource's default language.
func (c *VideosListCall) Hl(hl string) *VideosListCall {
c.urlParams_.Set("hl", hl)
return c
}
// Id sets the optional parameter "id": The id parameter specifies a
// comma-separated list of the YouTube video ID(s) for the resource(s)
// that are being retrieved. In a video resource, the id property
// specifies the video's ID.
func (c *VideosListCall) Id(id string) *VideosListCall {
c.urlParams_.Set("id", id)
return c
}
// Locale sets the optional parameter "locale": DEPRECATED
func (c *VideosListCall) Locale(locale string) *VideosListCall {
c.urlParams_.Set("locale", locale)
return c
}
// MaxHeight sets the optional parameter "maxHeight": The maxHeight
// parameter specifies a maximum height of the embedded player. If
// maxWidth is provided, maxHeight may not be reached in order to not
// violate the width request.
func (c *VideosListCall) MaxHeight(maxHeight int64) *VideosListCall {
c.urlParams_.Set("maxHeight", fmt.Sprint(maxHeight))
return c
}
// MaxResults sets the optional parameter "maxResults": The maxResults
// parameter specifies the maximum number of items that should be
// returned in the result set.
//
// Note: This parameter is supported for use in conjunction with the
// myRating and chart parameters, but it is not supported for use in
// conjunction with the id parameter.
func (c *VideosListCall) MaxResults(maxResults int64) *VideosListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// MaxWidth sets the optional parameter "maxWidth": The maxWidth
// parameter specifies a maximum width of the embedded player. If
// maxHeight is provided, maxWidth may not be reached in order to not
// violate the height request.
func (c *VideosListCall) MaxWidth(maxWidth int64) *VideosListCall {
c.urlParams_.Set("maxWidth", fmt.Sprint(maxWidth))
return c
}
// MyRating sets the optional parameter "myRating": Set this parameter's
// value to like or dislike to instruct the API to only return videos
// liked or disliked by the authenticated user.
//
// Possible values:
// "dislike" - Returns only videos disliked by the authenticated user.
// "like" - Returns only video liked by the authenticated user.
func (c *VideosListCall) MyRating(myRating string) *VideosListCall {
c.urlParams_.Set("myRating", myRating)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *VideosListCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *VideosListCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// PageToken sets the optional parameter "pageToken": The pageToken
// parameter identifies a specific page in the result set that should be
// returned. In an API response, the nextPageToken and prevPageToken
// properties identify other pages that could be retrieved.
//
// Note: This parameter is supported for use in conjunction with the
// myRating and chart parameters, but it is not supported for use in
// conjunction with the id parameter.
func (c *VideosListCall) PageToken(pageToken string) *VideosListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// RegionCode sets the optional parameter "regionCode": The regionCode
// parameter instructs the API to select a video chart available in the
// specified region. This parameter can only be used in conjunction with
// the chart parameter. The parameter value is an ISO 3166-1 alpha-2
// country code.
func (c *VideosListCall) RegionCode(regionCode string) *VideosListCall {
c.urlParams_.Set("regionCode", regionCode)
return c
}
// VideoCategoryId sets the optional parameter "videoCategoryId": The
// videoCategoryId parameter identifies the video category for which the
// chart should be retrieved. This parameter can only be used in
// conjunction with the chart parameter. By default, charts are not
// restricted to a particular category.
func (c *VideosListCall) VideoCategoryId(videoCategoryId string) *VideosListCall {
c.urlParams_.Set("videoCategoryId", videoCategoryId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosListCall) Fields(s ...googleapi.Field) *VideosListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *VideosListCall) IfNoneMatch(entityTag string) *VideosListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideosListCall) Context(ctx context.Context) *VideosListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.list" call.
// Exactly one of *VideoListResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *VideoListResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *VideosListCall) Do(opts ...googleapi.CallOption) (*VideoListResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &VideoListResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of videos that match the API request parameters.",
// "httpMethod": "GET",
// "id": "youtube.videos.list",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "chart": {
// "description": "The chart parameter identifies the chart that you want to retrieve.",
// "enum": [
// "mostPopular"
// ],
// "enumDescriptions": [
// "Return the most popular videos for the specified content region and video category."
// ],
// "location": "query",
// "type": "string"
// },
// "hl": {
// "description": "The hl parameter instructs the API to retrieve localized resource metadata for a specific application language that the YouTube website supports. The parameter value must be a language code included in the list returned by the i18nLanguages.list method.\n\nIf localized resource details are available in that language, the resource's snippet.localized object will contain the localized values. However, if localized details are not available, the snippet.localized object will contain resource details in the resource's default language.",
// "location": "query",
// "type": "string"
// },
// "id": {
// "description": "The id parameter specifies a comma-separated list of the YouTube video ID(s) for the resource(s) that are being retrieved. In a video resource, the id property specifies the video's ID.",
// "location": "query",
// "type": "string"
// },
// "locale": {
// "description": "DEPRECATED",
// "location": "query",
// "type": "string"
// },
// "maxHeight": {
// "description": "The maxHeight parameter specifies a maximum height of the embedded player. If maxWidth is provided, maxHeight may not be reached in order to not violate the width request.",
// "format": "uint32",
// "location": "query",
// "maximum": "8192",
// "minimum": "72",
// "type": "integer"
// },
// "maxResults": {
// "default": "5",
// "description": "The maxResults parameter specifies the maximum number of items that should be returned in the result set.\n\nNote: This parameter is supported for use in conjunction with the myRating and chart parameters, but it is not supported for use in conjunction with the id parameter.",
// "format": "uint32",
// "location": "query",
// "maximum": "50",
// "minimum": "1",
// "type": "integer"
// },
// "maxWidth": {
// "description": "The maxWidth parameter specifies a maximum width of the embedded player. If maxHeight is provided, maxWidth may not be reached in order to not violate the height request.",
// "format": "uint32",
// "location": "query",
// "maximum": "8192",
// "minimum": "72",
// "type": "integer"
// },
// "myRating": {
// "description": "Set this parameter's value to like or dislike to instruct the API to only return videos liked or disliked by the authenticated user.",
// "enum": [
// "dislike",
// "like"
// ],
// "enumDescriptions": [
// "Returns only videos disliked by the authenticated user.",
// "Returns only video liked by the authenticated user."
// ],
// "location": "query",
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.\n\nNote: This parameter is supported for use in conjunction with the myRating and chart parameters, but it is not supported for use in conjunction with the id parameter.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter specifies a comma-separated list of one or more video resource properties that the API response will include.\n\nIf the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a video resource, the snippet property contains the channelId, title, description, tags, and categoryId properties. As such, if you set part=snippet, the API response will contain all of those properties.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "regionCode": {
// "description": "The regionCode parameter instructs the API to select a video chart available in the specified region. This parameter can only be used in conjunction with the chart parameter. The parameter value is an ISO 3166-1 alpha-2 country code.",
// "location": "query",
// "type": "string"
// },
// "videoCategoryId": {
// "default": "0",
// "description": "The videoCategoryId parameter identifies the video category for which the chart should be retrieved. This parameter can only be used in conjunction with the chart parameter. By default, charts are not restricted to a particular category.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "videos",
// "response": {
// "$ref": "VideoListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *VideosListCall) Pages(ctx context.Context, f func(*VideoListResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "youtube.videos.rate":
type VideosRateCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Rate: Add a like or dislike rating to a video or remove a rating from
// a video.
func (r *VideosService) Rate(id string, rating string) *VideosRateCall {
c := &VideosRateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("id", id)
c.urlParams_.Set("rating", rating)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosRateCall) Fields(s ...googleapi.Field) *VideosRateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideosRateCall) Context(ctx context.Context) *VideosRateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosRateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosRateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos/rate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.rate" call.
func (c *VideosRateCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Add a like or dislike rating to a video or remove a rating from a video.",
// "httpMethod": "POST",
// "id": "youtube.videos.rate",
// "parameterOrder": [
// "id",
// "rating"
// ],
// "parameters": {
// "id": {
// "description": "The id parameter specifies the YouTube video ID of the video that is being rated or having its rating removed.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "rating": {
// "description": "Specifies the rating to record.",
// "enum": [
// "dislike",
// "like",
// "none"
// ],
// "enumDescriptions": [
// "Records that the authenticated user disliked the video.",
// "Records that the authenticated user liked the video.",
// "Removes any rating that the authenticated user had previously set for the video."
// ],
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "videos/rate",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.videos.reportAbuse":
type VideosReportAbuseCall struct {
s *Service
videoabusereport *VideoAbuseReport
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// ReportAbuse: Report abuse for a video.
func (r *VideosService) ReportAbuse(videoabusereport *VideoAbuseReport) *VideosReportAbuseCall {
c := &VideosReportAbuseCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.videoabusereport = videoabusereport
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *VideosReportAbuseCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *VideosReportAbuseCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosReportAbuseCall) Fields(s ...googleapi.Field) *VideosReportAbuseCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideosReportAbuseCall) Context(ctx context.Context) *VideosReportAbuseCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosReportAbuseCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosReportAbuseCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.videoabusereport)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos/reportAbuse")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.reportAbuse" call.
func (c *VideosReportAbuseCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Report abuse for a video.",
// "httpMethod": "POST",
// "id": "youtube.videos.reportAbuse",
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "videos/reportAbuse",
// "request": {
// "$ref": "VideoAbuseReport"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.videos.update":
type VideosUpdateCall struct {
s *Service
video *Video
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a video's metadata.
func (r *VideosService) Update(part string, video *Video) *VideosUpdateCall {
c := &VideosUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("part", part)
c.video = video
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The actual CMS account that the user
// authenticates with must be linked to the specified YouTube content
// owner.
func (c *VideosUpdateCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *VideosUpdateCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *VideosUpdateCall) Fields(s ...googleapi.Field) *VideosUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *VideosUpdateCall) Context(ctx context.Context) *VideosUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *VideosUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *VideosUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.video)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "videos")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PUT", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.videos.update" call.
// Exactly one of *Video or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Video.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *VideosUpdateCall) Do(opts ...googleapi.CallOption) (*Video, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Video{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a video's metadata.",
// "httpMethod": "PUT",
// "id": "youtube.videos.update",
// "parameterOrder": [
// "part"
// ],
// "parameters": {
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The actual CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// },
// "part": {
// "description": "The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.\n\nNote that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a video's privacy setting is contained in the status part. As such, if your request is updating a private video, and the request's part parameter value includes the status part, the video's privacy setting will be updated to whatever value the request body specifies. If the request body does not specify a value, the existing privacy setting will be removed and the video will revert to the default privacy setting.\n\nIn addition, not all parts contain properties that can be set when inserting or updating a video. For example, the statistics object encapsulates statistics that YouTube calculates for a video and does not contain values that you can set or modify. If the parameter value specifies a part that does not contain mutable values, that part will still be included in the API response.",
// "location": "query",
// "required": true,
// "type": "string"
// }
// },
// "path": "videos",
// "request": {
// "$ref": "Video"
// },
// "response": {
// "$ref": "Video"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
// method id "youtube.watermarks.set":
type WatermarksSetCall struct {
s *Service
invideobranding *InvideoBranding
urlParams_ gensupport.URLParams
mediaInfo_ *gensupport.MediaInfo
ctx_ context.Context
header_ http.Header
}
// Set: Uploads a watermark image to YouTube and sets it for a channel.
func (r *WatermarksService) Set(channelId string, invideobranding *InvideoBranding) *WatermarksSetCall {
c := &WatermarksSetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("channelId", channelId)
c.invideobranding = invideobranding
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *WatermarksSetCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *WatermarksSetCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *WatermarksSetCall) Media(r io.Reader, options ...googleapi.MediaOption) *WatermarksSetCall {
c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *WatermarksSetCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *WatermarksSetCall {
c.ctx_ = ctx
c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType)
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *WatermarksSetCall) ProgressUpdater(pu googleapi.ProgressUpdater) *WatermarksSetCall {
c.mediaInfo_.SetProgressUpdater(pu)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *WatermarksSetCall) Fields(s ...googleapi.Field) *WatermarksSetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *WatermarksSetCall) Context(ctx context.Context) *WatermarksSetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *WatermarksSetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *WatermarksSetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.invideobranding)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "watermarks/set")
if c.mediaInfo_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType())
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body)
defer cleanup()
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
gensupport.SetGetBody(req, getBody)
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.watermarks.set" call.
func (c *WatermarksSetCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location"))
if rx != nil {
rx.Client = c.s.client
rx.UserAgent = c.s.userAgent()
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return err
}
}
return nil
// {
// "description": "Uploads a watermark image to YouTube and sets it for a channel.",
// "httpMethod": "POST",
// "id": "youtube.watermarks.set",
// "mediaUpload": {
// "accept": [
// "application/octet-stream",
// "image/jpeg",
// "image/png"
// ],
// "maxSize": "10MB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/youtube/v3/watermarks/set"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/youtube/v3/watermarks/set"
// }
// }
// },
// "parameterOrder": [
// "channelId"
// ],
// "parameters": {
// "channelId": {
// "description": "The channelId parameter specifies the YouTube channel ID for which the watermark is being provided.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "watermarks/set",
// "request": {
// "$ref": "InvideoBranding"
// },
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtube.upload",
// "https://www.googleapis.com/auth/youtubepartner"
// ],
// "supportsMediaUpload": true
// }
}
// method id "youtube.watermarks.unset":
type WatermarksUnsetCall struct {
s *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Unset: Deletes a channel's watermark image.
func (r *WatermarksService) Unset(channelId string) *WatermarksUnsetCall {
c := &WatermarksUnsetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("channelId", channelId)
return c
}
// OnBehalfOfContentOwner sets the optional parameter
// "onBehalfOfContentOwner": Note: This parameter is intended
// exclusively for YouTube content partners.
//
// The onBehalfOfContentOwner parameter indicates that the request's
// authorization credentials identify a YouTube CMS user who is acting
// on behalf of the content owner specified in the parameter value. This
// parameter is intended for YouTube content partners that own and
// manage many different YouTube channels. It allows content owners to
// authenticate once and get access to all their video and channel data,
// without having to provide authentication credentials for each
// individual channel. The CMS account that the user authenticates with
// must be linked to the specified YouTube content owner.
func (c *WatermarksUnsetCall) OnBehalfOfContentOwner(onBehalfOfContentOwner string) *WatermarksUnsetCall {
c.urlParams_.Set("onBehalfOfContentOwner", onBehalfOfContentOwner)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *WatermarksUnsetCall) Fields(s ...googleapi.Field) *WatermarksUnsetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *WatermarksUnsetCall) Context(ctx context.Context) *WatermarksUnsetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *WatermarksUnsetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *WatermarksUnsetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "watermarks/unset")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "youtube.watermarks.unset" call.
func (c *WatermarksUnsetCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a channel's watermark image.",
// "httpMethod": "POST",
// "id": "youtube.watermarks.unset",
// "parameterOrder": [
// "channelId"
// ],
// "parameters": {
// "channelId": {
// "description": "The channelId parameter specifies the YouTube channel ID for which the watermark is being unset.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "onBehalfOfContentOwner": {
// "description": "Note: This parameter is intended exclusively for YouTube content partners.\n\nThe onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "watermarks/unset",
// "scopes": [
// "https://www.googleapis.com/auth/youtube",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "https://www.googleapis.com/auth/youtubepartner"
// ]
// }
}
| {
rs := &LiveStreamsService{s: s}
return rs
} |
error-codes.h.go | // THIS FILE WAS AUTO-GENERATED BY https://github.com/kjk/w/cmd/gengo
package w
const (
ERROR_SUCCESS = 0
ERROR_INVALID_FUNCTION = 1
ERROR_FILE_NOT_FOUND = 2
ERROR_PATH_NOT_FOUND = 3
ERROR_TOO_MANY_OPEN_FILES = 4
ERROR_ACCESS_DENIED = 5
ERROR_INVALID_HANDLE = 6
ERROR_ARENA_TRASHED = 7
ERROR_NOT_ENOUGH_MEMORY = 8
ERROR_INVALID_BLOCK = 9
ERROR_BAD_ENVIRONMENT = 10
ERROR_BAD_FORMAT = 11
ERROR_INVALID_ACCESS = 12
ERROR_INVALID_DATA = 13
ERROR_OUTOFMEMORY = 14
ERROR_INVALID_DRIVE = 15
ERROR_CURRENT_DIRECTORY = 16
ERROR_NOT_SAME_DEVICE = 17
ERROR_NO_MORE_FILES = 18
ERROR_WRITE_PROTECT = 19
ERROR_BAD_UNIT = 20
ERROR_NOT_READY = 21
ERROR_BAD_COMMAND = 22
ERROR_CRC = 23
ERROR_BAD_LENGTH = 24
ERROR_SEEK = 25
ERROR_NOT_DOS_DISK = 26
ERROR_SECTOR_NOT_FOUND = 27
ERROR_OUT_OF_PAPER = 28
ERROR_WRITE_FAULT = 29
ERROR_READ_FAULT = 30
ERROR_GEN_FAILURE = 31
ERROR_SHARING_VIOLATION = 32
ERROR_LOCK_VIOLATION = 33
ERROR_WRONG_DISK = 34
ERROR_SHARING_BUFFER_EXCEEDED = 36
ERROR_HANDLE_EOF = 38
ERROR_HANDLE_DISK_FULL = 39
SNMP_MGMTAPI_TIMEOUT = 40
SNMP_MGMTAPI_SELECT_FDERRORS = 41
SNMP_MGMTAPI_TRAP_ERRORS = 42
SNMP_MGMTAPI_TRAP_DUPINIT = 43
SNMP_MGMTAPI_NOTRAPS = 44
SNMP_MGMTAPI_AGAIN = 45
SNMP_MGMTAPI_INVALID_CTL = 46
SNMP_MGMTAPI_INVALID_SESSION = 47
SNMP_MGMTAPI_INVALID_BUFFER = 48
ERROR_NOT_SUPPORTED = 50
ERROR_REM_NOT_LIST = 51
ERROR_DUP_NAME = 52
ERROR_BAD_NETPATH = 53
ERROR_NETWORK_BUSY = 54
ERROR_DEV_NOT_EXIST = 55
ERROR_TOO_MANY_CMDS = 56
ERROR_ADAP_HDW_ERR = 57
ERROR_BAD_NET_RESP = 58
ERROR_UNEXP_NET_ERR = 59
ERROR_BAD_REM_ADAP = 60
ERROR_PRINTQ_FULL = 61
ERROR_NO_SPOOL_SPACE = 62
ERROR_PRINT_CANCELLED = 63
ERROR_NETNAME_DELETED = 64
ERROR_NETWORK_ACCESS_DENIED = 65
ERROR_BAD_DEV_TYPE = 66
ERROR_BAD_NET_NAME = 67
ERROR_TOO_MANY_NAMES = 68
ERROR_TOO_MANY_SESS = 69
ERROR_SHARING_PAUSED = 70
ERROR_REQ_NOT_ACCEP = 71
ERROR_REDIR_PAUSED = 72
ERROR_FILE_EXISTS = 80
ERROR_CANNOT_MAKE = 82
ERROR_FAIL_I24 = 83
ERROR_OUT_OF_STRUCTURES = 84
ERROR_ALREADY_ASSIGNED = 85
ERROR_INVALID_PASSWORD = 86
ERROR_INVALID_PARAMETER = 87
ERROR_NET_WRITE_FAULT = 88
ERROR_NO_PROC_SLOTS = 89
ERROR_TOO_MANY_SEMAPHORES = 100
ERROR_EXCL_SEM_ALREADY_OWNED = 101
ERROR_SEM_IS_SET = 102
ERROR_TOO_MANY_SEM_REQUESTS = 103
ERROR_INVALID_AT_INTERRUPT_TIME = 104
ERROR_SEM_OWNER_DIED = 105
ERROR_SEM_USER_LIMIT = 106
ERROR_DISK_CHANGE = 107
ERROR_DRIVE_LOCKED = 108
ERROR_BROKEN_PIPE = 109
ERROR_OPEN_FAILED = 110
ERROR_BUFFER_OVERFLOW = 111
ERROR_DISK_FULL = 112
ERROR_NO_MORE_SEARCH_HANDLES = 113
ERROR_INVALID_TARGET_HANDLE = 114
ERROR_INVALID_CATEGORY = 117
ERROR_INVALID_VERIFY_SWITCH = 118
ERROR_BAD_DRIVER_LEVEL = 119
ERROR_CALL_NOT_IMPLEMENTED = 120
ERROR_SEM_TIMEOUT = 121
ERROR_INSUFFICIENT_BUFFER = 122
ERROR_INVALID_NAME = 123
ERROR_INVALID_LEVEL = 124
ERROR_NO_VOLUME_LABEL = 125
ERROR_MOD_NOT_FOUND = 126
ERROR_PROC_NOT_FOUND = 127
ERROR_WAIT_NO_CHILDREN = 128
ERROR_CHILD_NOT_COMPLETE = 129
ERROR_DIRECT_ACCESS_HANDLE = 130
ERROR_NEGATIVE_SEEK = 131
ERROR_SEEK_ON_DEVICE = 132
ERROR_IS_JOIN_TARGET = 133
ERROR_IS_JOINED = 134
ERROR_IS_SUBSTED = 135
ERROR_NOT_JOINED = 136
ERROR_NOT_SUBSTED = 137
ERROR_JOIN_TO_JOIN = 138
ERROR_SUBST_TO_SUBST = 139
ERROR_JOIN_TO_SUBST = 140
ERROR_SUBST_TO_JOIN = 141
ERROR_BUSY_DRIVE = 142
ERROR_SAME_DRIVE = 143
ERROR_DIR_NOT_ROOT = 144
ERROR_DIR_NOT_EMPTY = 145
ERROR_IS_SUBST_PATH = 146
ERROR_IS_JOIN_PATH = 147
ERROR_PATH_BUSY = 148
ERROR_IS_SUBST_TARGET = 149
ERROR_SYSTEM_TRACE = 150
ERROR_INVALID_EVENT_COUNT = 151
ERROR_TOO_MANY_MUXWAITERS = 152
ERROR_INVALID_LIST_FORMAT = 153
ERROR_LABEL_TOO_LONG = 154
ERROR_TOO_MANY_TCBS = 155
ERROR_SIGNAL_REFUSED = 156
ERROR_DISCARDED = 157
ERROR_NOT_LOCKED = 158
ERROR_BAD_THREADID_ADDR = 159
ERROR_BAD_ARGUMENTS = 160
ERROR_BAD_PATHNAME = 161
ERROR_SIGNAL_PENDING = 162
ERROR_MAX_THRDS_REACHED = 164
ERROR_LOCK_FAILED = 167
ERROR_BUSY = 170
ERROR_CANCEL_VIOLATION = 173
ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174
ERROR_INVALID_SEGMENT_NUMBER = 180
ERROR_INVALID_ORDINAL = 182
ERROR_ALREADY_EXISTS = 183
ERROR_INVALID_FLAG_NUMBER = 186
ERROR_SEM_NOT_FOUND = 187
ERROR_INVALID_STARTING_CODESEG = 188
ERROR_INVALID_STACKSEG = 189
ERROR_INVALID_MODULETYPE = 190
ERROR_INVALID_EXE_SIGNATURE = 191
ERROR_EXE_MARKED_INVALID = 192
ERROR_BAD_EXE_FORMAT = 193
ERROR_ITERATED_DATA_EXCEEDS_64k = 194
ERROR_INVALID_MINALLOCSIZE = 195
ERROR_DYNLINK_FROM_INVALID_RING = 196
ERROR_IOPL_NOT_ENABLED = 197
ERROR_INVALID_SEGDPL = 198
ERROR_AUTODATASEG_EXCEEDS_64k = 199
ERROR_RING2SEG_MUST_BE_MOVABLE = 200
ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201
ERROR_INFLOOP_IN_RELOC_CHAIN = 202
ERROR_ENVVAR_NOT_FOUND = 203
ERROR_NO_SIGNAL_SENT = 205
ERROR_FILENAME_EXCED_RANGE = 206
ERROR_RING2_STACK_IN_USE = 207
ERROR_META_EXPANSION_TOO_LONG = 208
ERROR_INVALID_SIGNAL_NUMBER = 209
ERROR_THREAD_1_INACTIVE = 210
ERROR_LOCKED = 212
ERROR_TOO_MANY_MODULES = 214
ERROR_NESTING_NOT_ALLOWED = 215
ERROR_EXE_MACHINE_TYPE_MISMATCH = 216
ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY = 217
ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218
ERROR_FILE_CHECKED_OUT = 220
ERROR_CHECKOUT_REQUIRED = 221
ERROR_BAD_FILE_TYPE = 222
ERROR_FILE_TOO_LARGE = 223
ERROR_FORMS_AUTH_REQUIRED = 224
ERROR_VIRUS_INFECTED = 225
ERROR_VIRUS_DELETED = 226
ERROR_PIPE_LOCAL = 229
ERROR_BAD_PIPE = 230
ERROR_PIPE_BUSY = 231
ERROR_NO_DATA = 232
ERROR_PIPE_NOT_CONNECTED = 233
ERROR_MORE_DATA = 234
ERROR_VC_DISCONNECTED = 240
ERROR_INVALID_EA_NAME = 254
ERROR_EA_LIST_INCONSISTENT = 255
WAIT_TIMEOUT = 258
ERROR_NO_MORE_ITEMS = 259
ERROR_CANNOT_COPY = 266
ERROR_DIRECTORY = 267
ERROR_EAS_DIDNT_FIT = 275
ERROR_EA_FILE_CORRUPT = 276
ERROR_EA_TABLE_FULL = 277
ERROR_INVALID_EA_HANDLE = 278
ERROR_EAS_NOT_SUPPORTED = 282
ERROR_NOT_OWNER = 288
ERROR_TOO_MANY_POSTS = 298
ERROR_PARTIAL_COPY = 299
ERROR_OPLOCK_NOT_GRANTED = 300
ERROR_INVALID_OPLOCK_PROTOCOL = 301
ERROR_DISK_TOO_FRAGMENTED = 302
ERROR_DELETE_PENDING = 303
ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304
ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305
ERROR_SECURITY_STREAM_IS_INCONSISTENT = 306
ERROR_INVALID_LOCK_RANGE = 307
ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT = 308
ERROR_NOTIFICATION_GUID_ALREADY_DEFINED = 309
ERROR_MR_MID_NOT_FOUND = 317
ERROR_SCOPE_NOT_FOUND = 318
ERROR_FAIL_NOACTION_REBOOT = 350
ERROR_FAIL_SHUTDOWN = 351
ERROR_FAIL_RESTART = 352
ERROR_MAX_SESSIONS_REACHED = 353
ERROR_THREAD_MODE_ALREADY_BACKGROUND = 400
ERROR_THREAD_MODE_NOT_BACKGROUND = 401
ERROR_PROCESS_MODE_ALREADY_BACKGROUND = 402
ERROR_PROCESS_MODE_NOT_BACKGROUND = 403
ERROR_INVALID_ADDRESS = 487
ERROR_USER_PROFILE_LOAD = 500
ERROR_ARITHMETIC_OVERFLOW = 534
ERROR_PIPE_CONNECTED = 535
ERROR_PIPE_LISTENING = 536
ERROR_VERIFIER_STOP = 537
ERROR_ABIOS_ERROR = 538
ERROR_WX86_WARNING = 539
ERROR_WX86_ERROR = 540
ERROR_TIMER_NOT_CANCELED = 541
ERROR_UNWIND = 542
ERROR_BAD_STACK = 543
ERROR_INVALID_UNWIND_TARGET = 544
ERROR_INVALID_PORT_ATTRIBUTES = 545
ERROR_PORT_MESSAGE_TOO_LONG = 546
ERROR_INVALID_QUOTA_LOWER = 547
ERROR_DEVICE_ALREADY_ATTACHED = 548
ERROR_INSTRUCTION_MISALIGNMENT = 549
ERROR_PROFILING_NOT_STARTED = 550
ERROR_PROFILING_NOT_STOPPED = 551
ERROR_COULD_NOT_INTERPRET = 552
ERROR_PROFILING_AT_LIMIT = 553
ERROR_CANT_WAIT = 554
ERROR_CANT_TERMINATE_SELF = 555
ERROR_UNEXPECTED_MM_CREATE_ERR = 556
ERROR_UNEXPECTED_MM_MAP_ERROR = 557
ERROR_UNEXPECTED_MM_EXTEND_ERR = 558
ERROR_BAD_FUNCTION_TABLE = 559
ERROR_NO_GUID_TRANSLATION = 560
ERROR_INVALID_LDT_SIZE = 561
ERROR_INVALID_LDT_OFFSET = 563
ERROR_INVALID_LDT_DESCRIPTOR = 564
ERROR_TOO_MANY_THREADS = 565
ERROR_THREAD_NOT_IN_PROCESS = 566
ERROR_PAGEFILE_QUOTA_EXCEEDED = 567
ERROR_LOGON_SERVER_CONFLICT = 568
ERROR_SYNCHRONIZATION_REQUIRED = 569
ERROR_NET_OPEN_FAILED = 570
ERROR_IO_PRIVILEGE_FAILED = 571
ERROR_CONTROL_C_EXIT = 572
ERROR_MISSING_SYSTEMFILE = 573
ERROR_UNHANDLED_EXCEPTION = 574
ERROR_APP_INIT_FAILURE = 575
ERROR_PAGEFILE_CREATE_FAILED = 576
ERROR_INVALID_IMAGE_HASH = 577
ERROR_NO_PAGEFILE = 578
ERROR_ILLEGAL_FLOAT_CONTEXT = 579
ERROR_NO_EVENT_PAIR = 580
ERROR_DOMAIN_CTRLR_CONFIG_ERROR = 581
ERROR_ILLEGAL_CHARACTER = 582
ERROR_UNDEFINED_CHARACTER = 583
ERROR_FLOPPY_VOLUME = 584
ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT = 585
ERROR_BACKUP_CONTROLLER = 586
ERROR_MUTANT_LIMIT_EXCEEDED = 587
ERROR_FS_DRIVER_REQUIRED = 588
ERROR_CANNOT_LOAD_REGISTRY_FILE = 589
ERROR_DEBUG_ATTACH_FAILED = 590
ERROR_SYSTEM_PROCESS_TERMINATED = 591
ERROR_DATA_NOT_ACCEPTED = 592
ERROR_VDM_HARD_ERROR = 593
ERROR_DRIVER_CANCEL_TIMEOUT = 594
ERROR_REPLY_MESSAGE_MISMATCH = 595
ERROR_LOST_WRITEBEHIND_DATA = 596
ERROR_CLIENT_SERVER_PARAMETERS_INVALID = 597
ERROR_NOT_TINY_STREAM = 598
ERROR_STACK_OVERFLOW_READ = 599
ERROR_CONVERT_TO_LARGE = 600
ERROR_FOUND_OUT_OF_SCOPE = 601
ERROR_ALLOCATE_BUCKET = 602
ERROR_MARSHALL_OVERFLOW = 603
ERROR_INVALID_VARIANT = 604
ERROR_BAD_COMPRESSION_BUFFER = 605
ERROR_AUDIT_FAILED = 606
ERROR_TIMER_RESOLUTION_NOT_SET = 607
ERROR_INSUFFICIENT_LOGON_INFO = 608
ERROR_BAD_DLL_ENTRYPOINT = 609
ERROR_BAD_SERVICE_ENTRYPOINT = 610
ERROR_IP_ADDRESS_CONFLICT1 = 611
ERROR_IP_ADDRESS_CONFLICT2 = 612
ERROR_REGISTRY_QUOTA_LIMIT = 613
ERROR_NO_CALLBACK_ACTIVE = 614
ERROR_PWD_TOO_SHORT = 615
ERROR_PWD_TOO_RECENT = 616
ERROR_PWD_HISTORY_CONFLICT = 617
ERROR_UNSUPPORTED_COMPRESSION = 618
ERROR_INVALID_HW_PROFILE = 619
ERROR_INVALID_PLUGPLAY_DEVICE_PATH = 620
ERROR_QUOTA_LIST_INCONSISTENT = 621
ERROR_EVALUATION_EXPIRATION = 622
ERROR_ILLEGAL_DLL_RELOCATION = 623
ERROR_DLL_INIT_FAILED_LOGOFF = 624
ERROR_VALIDATE_CONTINUE = 625
ERROR_NO_MORE_MATCHES = 626
ERROR_RANGE_LIST_CONFLICT = 627
ERROR_SERVER_SID_MISMATCH = 628
ERROR_CANT_ENABLE_DENY_ONLY = 629
ERROR_FLOAT_MULTIPLE_FAULTS = 630
ERROR_FLOAT_MULTIPLE_TRAPS = 631
ERROR_NOINTERFACE = 632
ERROR_DRIVER_FAILED_SLEEP = 633
ERROR_CORRUPT_SYSTEM_FILE = 634
ERROR_COMMITMENT_MINIMUM = 635
ERROR_PNP_RESTART_ENUMERATION = 636
ERROR_SYSTEM_IMAGE_BAD_SIGNATURE = 637
ERROR_PNP_REBOOT_REQUIRED = 638
ERROR_INSUFFICIENT_POWER = 639
ERROR_MULTIPLE_FAULT_VIOLATION = 640
ERROR_SYSTEM_SHUTDOWN = 641
ERROR_PORT_NOT_SET = 642
ERROR_DS_VERSION_CHECK_FAILURE = 643
ERROR_RANGE_NOT_FOUND = 644
ERROR_NOT_SAFE_MODE_DRIVER = 646
ERROR_FAILED_DRIVER_ENTRY = 647
ERROR_DEVICE_ENUMERATION_ERROR = 648
ERROR_MOUNT_POINT_NOT_RESOLVED = 649
ERROR_INVALID_DEVICE_OBJECT_PARAMETER = 650
ERROR_MCA_OCCURED = 651
ERROR_DRIVER_DATABASE_ERROR = 652
ERROR_SYSTEM_HIVE_TOO_LARGE = 653
ERROR_DRIVER_FAILED_PRIOR_UNLOAD = 654
ERROR_VOLSNAP_PREPARE_HIBERNATE = 655
ERROR_HIBERNATION_FAILURE = 656
ERROR_FILE_SYSTEM_LIMITATION = 665
ERROR_ASSERTION_FAILURE = 668
ERROR_ACPI_ERROR = 669
ERROR_WOW_ASSERTION = 670
ERROR_PNP_BAD_MPS_TABLE = 671
ERROR_PNP_TRANSLATION_FAILED = 672
ERROR_PNP_IRQ_TRANSLATION_FAILED = 673
ERROR_PNP_INVALID_ID = 674
ERROR_WAKE_SYSTEM_DEBUGGER = 675
ERROR_HANDLES_CLOSED = 676
ERROR_EXTRANEOUS_INFORMATION = 677
ERROR_RXACT_COMMIT_NECESSARY = 678
ERROR_MEDIA_CHECK = 679
ERROR_GUID_SUBSTITUTION_MADE = 680
ERROR_STOPPED_ON_SYMLINK = 681
ERROR_LONGJUMP = 682
ERROR_PLUGPLAY_QUERY_VETOED = 683
ERROR_UNWIND_CONSOLIDATE = 684
ERROR_REGISTRY_HIVE_RECOVERED = 685
ERROR_DLL_MIGHT_BE_INSECURE = 686
ERROR_DLL_MIGHT_BE_INCOMPATIBLE = 687
ERROR_DBG_EXCEPTION_NOT_HANDLED = 688
ERROR_DBG_REPLY_LATER = 689
ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE = 690
ERROR_DBG_TERMINATE_THREAD = 691
ERROR_DBG_TERMINATE_PROCESS = 692
ERROR_DBG_CONTROL_C = 693
ERROR_DBG_PRINTEXCEPTION_C = 694
ERROR_DBG_RIPEXCEPTION = 695
ERROR_DBG_CONTROL_BREAK = 696
ERROR_DBG_COMMAND_EXCEPTION = 697
ERROR_OBJECT_NAME_EXISTS = 698
ERROR_THREAD_WAS_SUSPENDED = 699
ERROR_IMAGE_NOT_AT_BASE = 700
ERROR_RXACT_STATE_CREATED = 701
ERROR_SEGMENT_NOTIFICATION = 702
ERROR_BAD_CURRENT_DIRECTORY = 703
ERROR_FT_READ_RECOVERY_FROM_BACKUP = 704
ERROR_FT_WRITE_RECOVERY = 705
ERROR_IMAGE_MACHINE_TYPE_MISMATCH = 706
ERROR_RECEIVE_PARTIAL = 707
ERROR_RECEIVE_EXPEDITED = 708
ERROR_RECEIVE_PARTIAL_EXPEDITED = 709
ERROR_EVENT_DONE = 710
ERROR_EVENT_PENDING = 711
ERROR_CHECKING_FILE_SYSTEM = 712
ERROR_FATAL_APP_EXIT = 713
ERROR_PREDEFINED_HANDLE = 714
ERROR_WAS_UNLOCKED = 715
ERROR_SERVICE_NOTIFICATION = 716
ERROR_WAS_LOCKED = 717
ERROR_LOG_HARD_ERROR = 718
ERROR_ALREADY_WIN32 = 719
ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720
ERROR_NO_YIELD_PERFORMED = 721
ERROR_TIMER_RESUME_IGNORED = 722
ERROR_ARBITRATION_UNHANDLED = 723
ERROR_CARDBUS_NOT_SUPPORTED = 724
ERROR_MP_PROCESSOR_MISMATCH = 725
ERROR_HIBERNATED = 726
ERROR_RESUME_HIBERNATION = 727
ERROR_FIRMWARE_UPDATED = 728
ERROR_DRIVERS_LEAKING_LOCKED_PAGES = 729
ERROR_WAKE_SYSTEM = 730
ERROR_WAIT_1 = 731
ERROR_WAIT_2 = 732
ERROR_WAIT_3 = 733
ERROR_WAIT_63 = 734
ERROR_ABANDONED_WAIT_0 = 735
ERROR_ABANDONED_WAIT_63 = 736
ERROR_USER_APC = 737
ERROR_KERNEL_APC = 738
ERROR_ALERTED = 739
ERROR_ELEVATION_REQUIRED = 740
ERROR_REPARSE = 741
ERROR_OPLOCK_BREAK_IN_PROGRESS = 742
ERROR_VOLUME_MOUNTED = 743
ERROR_RXACT_COMMITTED = 744
ERROR_NOTIFY_CLEANUP = 745
ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED = 746
ERROR_PAGE_FAULT_TRANSITION = 747
ERROR_PAGE_FAULT_DEMAND_ZERO = 748
ERROR_PAGE_FAULT_COPY_ON_WRITE = 749
ERROR_PAGE_FAULT_GUARD_PAGE = 750
ERROR_PAGE_FAULT_PAGING_FILE = 751
ERROR_CACHE_PAGE_LOCKED = 752
ERROR_CRASH_DUMP = 753
ERROR_BUFFER_ALL_ZEROS = 754
ERROR_REPARSE_OBJECT = 755
ERROR_RESOURCE_REQUIREMENTS_CHANGED = 756
ERROR_TRANSLATION_COMPLETE = 757
ERROR_NOTHING_TO_TERMINATE = 758
ERROR_PROCESS_NOT_IN_JOB = 759
ERROR_PROCESS_IN_JOB = 760
ERROR_VOLSNAP_HIBERNATE_READY = 761
ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762
ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED = 763
ERROR_INTERRUPT_STILL_CONNECTED = 764
ERROR_WAIT_FOR_OPLOCK = 765
ERROR_DBG_EXCEPTION_HANDLED = 766
ERROR_DBG_CONTINUE = 767
ERROR_CALLBACK_POP_STACK = 768
ERROR_COMPRESSION_DISABLED = 769
ERROR_CANTFETCHBACKWARDS = 770
ERROR_CANTSCROLLBACKWARDS = 771
ERROR_ROWSNOTRELEASED = 772
ERROR_BAD_ACCESSOR_FLAGS = 773
ERROR_ERRORS_ENCOUNTERED = 774
ERROR_NOT_CAPABLE = 775
ERROR_REQUEST_OUT_OF_SEQUENCE = 776
ERROR_VERSION_PARSE_ERROR = 777
ERROR_BADSTARTPOSITION = 778
ERROR_MEMORY_HARDWARE = 779
ERROR_DISK_REPAIR_DISABLED = 780
ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781
ERROR_SYSTEM_POWERSTATE_TRANSITION = 782
ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783
ERROR_MCA_EXCEPTION = 784
ERROR_ACCESS_AUDIT_BY_POLICY = 785
ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786
ERROR_ABANDON_HIBERFILE = 787
ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788
ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789
ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790
ERROR_BAD_MCFG_TABLE = 791
ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE = 800
ERROR_CANNOT_GRANT_REQUESTED_OPLOCK = 801
ERROR_CANNOT_BREAK_OPLOCK = 802
ERROR_OPLOCK_HANDLE_CLOSED = 803
ERROR_NO_ACE_CONDITION = 804
ERROR_INVALID_ACE_CONDITION = 805
ERROR_EA_ACCESS_DENIED = 994
ERROR_OPERATION_ABORTED = 995
ERROR_IO_INCOMPLETE = 996
ERROR_IO_PENDING = 997
ERROR_NOACCESS = 998
ERROR_SWAPERROR = 999
ERROR_STACK_OVERFLOW = 1001
ERROR_INVALID_MESSAGE = 1002
ERROR_CAN_NOT_COMPLETE = 1003
ERROR_INVALID_FLAGS = 1004
ERROR_UNRECOGNIZED_VOLUME = 1005
ERROR_FILE_INVALID = 1006
ERROR_FULLSCREEN_MODE = 1007
ERROR_NO_TOKEN = 1008
ERROR_BADDB = 1009
ERROR_BADKEY = 1010
ERROR_CANTOPEN = 1011
ERROR_CANTREAD = 1012
ERROR_CANTWRITE = 1013
ERROR_REGISTRY_RECOVERED = 1014
ERROR_REGISTRY_CORRUPT = 1015
ERROR_REGISTRY_IO_FAILED = 1016
ERROR_NOT_REGISTRY_FILE = 1017
ERROR_KEY_DELETED = 1018
ERROR_NO_LOG_SPACE = 1019
ERROR_KEY_HAS_CHILDREN = 1020
ERROR_CHILD_MUST_BE_VOLATILE = 1021
ERROR_NOTIFY_ENUM_DIR = 1022
ERROR_DEPENDENT_SERVICES_RUNNING = 1051
ERROR_INVALID_SERVICE_CONTROL = 1052
ERROR_SERVICE_REQUEST_TIMEOUT = 1053
ERROR_SERVICE_NO_THREAD = 1054
ERROR_SERVICE_DATABASE_LOCKED = 1055
ERROR_SERVICE_ALREADY_RUNNING = 1056
ERROR_INVALID_SERVICE_ACCOUNT = 1057
ERROR_SERVICE_DISABLED = 1058
ERROR_CIRCULAR_DEPENDENCY = 1059
ERROR_SERVICE_DOES_NOT_EXIST = 1060
ERROR_SERVICE_CANNOT_ACCEPT_CTRL = 1061
ERROR_SERVICE_NOT_ACTIVE = 1062
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063
ERROR_EXCEPTION_IN_SERVICE = 1064
ERROR_DATABASE_DOES_NOT_EXIST = 1065
ERROR_SERVICE_SPECIFIC_ERROR = 1066
ERROR_PROCESS_ABORTED = 1067
ERROR_SERVICE_DEPENDENCY_FAIL = 1068 | ERROR_INVALID_SERVICE_LOCK = 1071
ERROR_SERVICE_MARKED_FOR_DELETE = 1072
ERROR_SERVICE_EXISTS = 1073
ERROR_ALREADY_RUNNING_LKG = 1074
ERROR_SERVICE_DEPENDENCY_DELETED = 1075
ERROR_BOOT_ALREADY_ACCEPTED = 1076
ERROR_SERVICE_NEVER_STARTED = 1077
ERROR_DUPLICATE_SERVICE_NAME = 1078
ERROR_DIFFERENT_SERVICE_ACCOUNT = 1079
ERROR_CANNOT_DETECT_DRIVER_FAILURE = 1080
ERROR_CANNOT_DETECT_PROCESS_ABORT = 1081
ERROR_NO_RECOVERY_PROGRAM = 1082
ERROR_SERVICE_NOT_IN_EXE = 1083
ERROR_NOT_SAFEBOOT_SERVICE = 1084
ERROR_END_OF_MEDIA = 1100
ERROR_FILEMARK_DETECTED = 1101
ERROR_BEGINNING_OF_MEDIA = 1102
ERROR_SETMARK_DETECTED = 1103
ERROR_NO_DATA_DETECTED = 1104
ERROR_PARTITION_FAILURE = 1105
ERROR_INVALID_BLOCK_LENGTH = 1106
ERROR_DEVICE_NOT_PARTITIONED = 1107
ERROR_UNABLE_TO_LOCK_MEDIA = 1108
ERROR_UNABLE_TO_UNLOAD_MEDIA = 1109
ERROR_MEDIA_CHANGED = 1110
ERROR_BUS_RESET = 1111
ERROR_NO_MEDIA_IN_DRIVE = 1112
ERROR_NO_UNICODE_TRANSLATION = 1113
ERROR_DLL_INIT_FAILED = 1114
ERROR_SHUTDOWN_IN_PROGRESS = 1115
ERROR_NO_SHUTDOWN_IN_PROGRESS = 1116
ERROR_IO_DEVICE = 1117
ERROR_SERIAL_NO_DEVICE = 1118
ERROR_IRQ_BUSY = 1119
ERROR_MORE_WRITES = 1120
ERROR_COUNTER_TIMEOUT = 1121
ERROR_FLOPPY_ID_MARK_NOT_FOUND = 1122
ERROR_FLOPPY_WRONG_CYLINDER = 1123
ERROR_FLOPPY_UNKNOWN_ERROR = 1124
ERROR_FLOPPY_BAD_REGISTERS = 1125
ERROR_DISK_RECALIBRATE_FAILED = 1126
ERROR_DISK_OPERATION_FAILED = 1127
ERROR_DISK_RESET_FAILED = 1128
ERROR_EOM_OVERFLOW = 1129
ERROR_NOT_ENOUGH_SERVER_MEMORY = 1130
ERROR_POSSIBLE_DEADLOCK = 1131
ERROR_MAPPED_ALIGNMENT = 1132
ERROR_SET_POWER_STATE_VETOED = 1140
ERROR_SET_POWER_STATE_FAILED = 1141
ERROR_TOO_MANY_LINKS = 1142
ERROR_OLD_WIN_VERSION = 1150
ERROR_APP_WRONG_OS = 1151
ERROR_SINGLE_INSTANCE_APP = 1152
ERROR_RMODE_APP = 1153
ERROR_INVALID_DLL = 1154
ERROR_NO_ASSOCIATION = 1155
ERROR_DDE_FAIL = 1156
ERROR_DLL_NOT_FOUND = 1157
ERROR_NO_MORE_USER_HANDLES = 1158
ERROR_MESSAGE_SYNC_ONLY = 1159
ERROR_SOURCE_ELEMENT_EMPTY = 1160
ERROR_DESTINATION_ELEMENT_FULL = 1161
ERROR_ILLEGAL_ELEMENT_ADDRESS = 1162
ERROR_MAGAZINE_NOT_PRESENT = 1163
ERROR_DEVICE_REINITIALIZATION_NEEDED = 1164
ERROR_DEVICE_REQUIRES_CLEANING = 1165
ERROR_DEVICE_DOOR_OPEN = 1166
ERROR_DEVICE_NOT_CONNECTED = 1167
ERROR_NOT_FOUND = 1168
ERROR_NO_MATCH = 1169
ERROR_SET_NOT_FOUND = 1170
ERROR_POINT_NOT_FOUND = 1171
ERROR_NO_TRACKING_SERVICE = 1172
ERROR_NO_VOLUME_ID = 1173
ERROR_UNABLE_TO_REMOVE_REPLACED = 1175
ERROR_UNABLE_TO_MOVE_REPLACEMENT = 1176
ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177
ERROR_JOURNAL_DELETE_IN_PROGRESS = 1178
ERROR_JOURNAL_NOT_ACTIVE = 1179
ERROR_POTENTIAL_FILE_FOUND = 1180
ERROR_JOURNAL_ENTRY_DELETED = 1181
ERROR_SHUTDOWN_IS_SCHEDULED = 1190
ERROR_SHUTDOWN_USERS_LOGGED_ON = 1191
ERROR_BAD_DEVICE = 1200
ERROR_CONNECTION_UNAVAIL = 1201
ERROR_DEVICE_ALREADY_REMEMBERED = 1202
ERROR_NO_NET_OR_BAD_PATH = 1203
ERROR_BAD_PROVIDER = 1204
ERROR_CANNOT_OPEN_PROFILE = 1205
ERROR_BAD_PROFILE = 1206
ERROR_NOT_CONTAINER = 1207
ERROR_EXTENDED_ERROR = 1208
ERROR_INVALID_GROUPNAME = 1209
ERROR_INVALID_COMPUTERNAME = 1210
ERROR_INVALID_EVENTNAME = 1211
ERROR_INVALID_DOMAINNAME = 1212
ERROR_INVALID_SERVICENAME = 1213
ERROR_INVALID_NETNAME = 1214
ERROR_INVALID_SHARENAME = 1215
ERROR_INVALID_PASSWORDNAME = 1216
ERROR_INVALID_MESSAGENAME = 1217
ERROR_INVALID_MESSAGEDEST = 1218
ERROR_SESSION_CREDENTIAL_CONFLICT = 1219
ERROR_REMOTE_SESSION_LIMIT_EXCEEDED = 1220
ERROR_DUP_DOMAINNAME = 1221
ERROR_NO_NETWORK = 1222
ERROR_CANCELLED = 1223
ERROR_USER_MAPPED_FILE = 1224
ERROR_CONNECTION_REFUSED = 1225
ERROR_GRACEFUL_DISCONNECT = 1226
ERROR_ADDRESS_ALREADY_ASSOCIATED = 1227
ERROR_ADDRESS_NOT_ASSOCIATED = 1228
ERROR_CONNECTION_INVALID = 1229
ERROR_CONNECTION_ACTIVE = 1230
ERROR_NETWORK_UNREACHABLE = 1231
ERROR_HOST_UNREACHABLE = 1232
ERROR_PROTOCOL_UNREACHABLE = 1233
ERROR_PORT_UNREACHABLE = 1234
ERROR_REQUEST_ABORTED = 1235
ERROR_CONNECTION_ABORTED = 1236
ERROR_RETRY = 1237
ERROR_CONNECTION_COUNT_LIMIT = 1238
ERROR_LOGIN_TIME_RESTRICTION = 1239
ERROR_LOGIN_WKSTA_RESTRICTION = 1240
ERROR_INCORRECT_ADDRESS = 1241
ERROR_ALREADY_REGISTERED = 1242
ERROR_SERVICE_NOT_FOUND = 1243
ERROR_NOT_AUTHENTICATED = 1244
ERROR_NOT_LOGGED_ON = 1245
ERROR_CONTINUE = 1246
ERROR_ALREADY_INITIALIZED = 1247
ERROR_NO_MORE_DEVICES = 1248
ERROR_NO_SUCH_SITE = 1249
ERROR_DOMAIN_CONTROLLER_EXISTS = 1250
ERROR_ONLY_IF_CONNECTED = 1251
ERROR_OVERRIDE_NOCHANGES = 1252
ERROR_BAD_USER_PROFILE = 1253
ERROR_NOT_SUPPORTED_ON_SBS = 1254
ERROR_SERVER_SHUTDOWN_IN_PROGRESS = 1255
ERROR_HOST_DOWN = 1256
ERROR_NON_ACCOUNT_SID = 1257
ERROR_NON_DOMAIN_SID = 1258
ERROR_APPHELP_BLOCK = 1259
ERROR_ACCESS_DISABLED_BY_POLICY = 1260
ERROR_REG_NAT_CONSUMPTION = 1261
ERROR_CSCSHARE_OFFLINE = 1262
ERROR_PKINIT_FAILURE = 1263
ERROR_SMARTCARD_SUBSYSTEM_FAILURE = 1264
ERROR_DOWNGRADE_DETECTED = 1265
ERROR_MACHINE_LOCKED = 1271
ERROR_CALLBACK_SUPPLIED_INVALID_DATA = 1273
ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED = 1274
ERROR_DRIVER_BLOCKED = 1275
ERROR_INVALID_IMPORT_OF_NON_DLL = 1276
ERROR_ACCESS_DISABLED_WEBBLADE = 1277
ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER = 1278
ERROR_RECOVERY_FAILURE = 1279
ERROR_ALREADY_FIBER = 1280
ERROR_ALREADY_THREAD = 1281
ERROR_STACK_BUFFER_OVERRUN = 1282
ERROR_PARAMETER_QUOTA_EXCEEDED = 1283
ERROR_DEBUGGER_INACTIVE = 1284
ERROR_DELAY_LOAD_FAILED = 1285
ERROR_VDM_DISALLOWED = 1286
ERROR_UNIDENTIFIED_ERROR = 1287
ERROR_INVALID_CRUNTIME_PARAMETER = 1288
ERROR_BEYOND_VDL = 1289
ERROR_INCOMPATIBLE_SERVICE_SID_TYPE = 1290
ERROR_DRIVER_PROCESS_TERMINATED = 1291
ERROR_IMPLEMENTATION_LIMIT = 1292
ERROR_PROCESS_IS_PROTECTED = 1293
ERROR_SERVICE_NOTIFY_CLIENT_LAGGING = 1294
ERROR_DISK_QUOTA_EXCEEDED = 1295
ERROR_CONTENT_BLOCKED = 1296
ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE = 1297
ERROR_APP_HANG = 1298
ERROR_INVALID_LABEL = 1299
ERROR_NOT_ALL_ASSIGNED = 1300
ERROR_SOME_NOT_MAPPED = 1301
ERROR_NO_QUOTAS_FOR_ACCOUNT = 1302
ERROR_LOCAL_USER_SESSION_KEY = 1303
ERROR_NULL_LM_PASSWORD = 1304
ERROR_UNKNOWN_REVISION = 1305
ERROR_REVISION_MISMATCH = 1306
ERROR_INVALID_OWNER = 1307
ERROR_INVALID_PRIMARY_GROUP = 1308
ERROR_NO_IMPERSONATION_TOKEN = 1309
ERROR_CANT_DISABLE_MANDATORY = 1310
ERROR_NO_LOGON_SERVERS = 1311
ERROR_NO_SUCH_LOGON_SESSION = 1312
ERROR_NO_SUCH_PRIVILEGE = 1313
ERROR_PRIVILEGE_NOT_HELD = 1314
ERROR_INVALID_ACCOUNT_NAME = 1315
ERROR_USER_EXISTS = 1316
ERROR_NO_SUCH_USER = 1317
ERROR_GROUP_EXISTS = 1318
ERROR_NO_SUCH_GROUP = 1319
ERROR_MEMBER_IN_GROUP = 1320
ERROR_MEMBER_NOT_IN_GROUP = 1321
ERROR_LAST_ADMIN = 1322
ERROR_WRONG_PASSWORD = 1323
ERROR_ILL_FORMED_PASSWORD = 1324
ERROR_PASSWORD_RESTRICTION = 1325
ERROR_LOGON_FAILURE = 1326
ERROR_ACCOUNT_RESTRICTION = 1327
ERROR_INVALID_LOGON_HOURS = 1328
ERROR_INVALID_WORKSTATION = 1329
ERROR_PASSWORD_EXPIRED = 1330
ERROR_ACCOUNT_DISABLED = 1331
ERROR_NONE_MAPPED = 1332
ERROR_TOO_MANY_LUIDS_REQUESTED = 1333
ERROR_LUIDS_EXHAUSTED = 1334
ERROR_INVALID_SUB_AUTHORITY = 1335
ERROR_INVALID_ACL = 1336
ERROR_INVALID_SID = 1337
ERROR_INVALID_SECURITY_DESCR = 1338
ERROR_BAD_INHERITANCE_ACL = 1340
ERROR_SERVER_DISABLED = 1341
ERROR_SERVER_NOT_DISABLED = 1342
ERROR_INVALID_ID_AUTHORITY = 1343
ERROR_ALLOTTED_SPACE_EXCEEDED = 1344
ERROR_INVALID_GROUP_ATTRIBUTES = 1345
ERROR_BAD_IMPERSONATION_LEVEL = 1346
ERROR_CANT_OPEN_ANONYMOUS = 1347
ERROR_BAD_VALIDATION_CLASS = 1348
ERROR_BAD_TOKEN_TYPE = 1349
ERROR_NO_SECURITY_ON_OBJECT = 1350
ERROR_CANT_ACCESS_DOMAIN_INFO = 1351
ERROR_INVALID_SERVER_STATE = 1352
ERROR_INVALID_DOMAIN_STATE = 1353
ERROR_INVALID_DOMAIN_ROLE = 1354
ERROR_NO_SUCH_DOMAIN = 1355
ERROR_DOMAIN_EXISTS = 1356
ERROR_DOMAIN_LIMIT_EXCEEDED = 1357
ERROR_INTERNAL_DB_CORRUPTION = 1358
ERROR_INTERNAL_ERROR = 1359
ERROR_GENERIC_NOT_MAPPED = 1360
ERROR_BAD_DESCRIPTOR_FORMAT = 1361
ERROR_NOT_LOGON_PROCESS = 1362
ERROR_LOGON_SESSION_EXISTS = 1363
ERROR_NO_SUCH_PACKAGE = 1364
ERROR_BAD_LOGON_SESSION_STATE = 1365
ERROR_LOGON_SESSION_COLLISION = 1366
ERROR_INVALID_LOGON_TYPE = 1367
ERROR_CANNOT_IMPERSONATE = 1368
ERROR_RXACT_INVALID_STATE = 1369
ERROR_RXACT_COMMIT_FAILURE = 1370
ERROR_SPECIAL_ACCOUNT = 1371
ERROR_SPECIAL_GROUP = 1372
ERROR_SPECIAL_USER = 1373
ERROR_MEMBERS_PRIMARY_GROUP = 1374
ERROR_TOKEN_ALREADY_IN_USE = 1375
ERROR_NO_SUCH_ALIAS = 1376
ERROR_MEMBER_NOT_IN_ALIAS = 1377
ERROR_MEMBER_IN_ALIAS = 1378
ERROR_ALIAS_EXISTS = 1379
ERROR_LOGON_NOT_GRANTED = 1380
ERROR_TOO_MANY_SECRETS = 1381
ERROR_SECRET_TOO_LONG = 1382
ERROR_INTERNAL_DB_ERROR = 1383
ERROR_TOO_MANY_CONTEXT_IDS = 1384
ERROR_LOGON_TYPE_NOT_GRANTED = 1385
ERROR_NT_CROSS_ENCRYPTION_REQUIRED = 1386
ERROR_NO_SUCH_MEMBER = 1387
ERROR_INVALID_MEMBER = 1388
ERROR_TOO_MANY_SIDS = 1389
ERROR_LM_CROSS_ENCRYPTION_REQUIRED = 1390
ERROR_NO_INHERITANCE = 1391
ERROR_FILE_CORRUPT = 1392
ERROR_DISK_CORRUPT = 1393
ERROR_NO_USER_SESSION_KEY = 1394
ERROR_LICENSE_QUOTA_EXCEEDED = 1395
ERROR_WRONG_TARGET_NAME = 1396
ERROR_MUTUAL_AUTH_FAILED = 1397
ERROR_TIME_SKEW = 1398
ERROR_CURRENT_DOMAIN_NOT_ALLOWED = 1399
ERROR_INVALID_WINDOW_HANDLE = 1400
ERROR_INVALID_MENU_HANDLE = 1401
ERROR_INVALID_CURSOR_HANDLE = 1402
ERROR_INVALID_ACCEL_HANDLE = 1403
ERROR_INVALID_HOOK_HANDLE = 1404
ERROR_INVALID_DWP_HANDLE = 1405
ERROR_TLW_WITH_WSCHILD = 1406
ERROR_CANNOT_FIND_WND_CLASS = 1407
ERROR_WINDOW_OF_OTHER_THREAD = 1408
ERROR_HOTKEY_ALREADY_REGISTERED = 1409
ERROR_CLASS_ALREADY_EXISTS = 1410
ERROR_CLASS_DOES_NOT_EXIST = 1411
ERROR_CLASS_HAS_WINDOWS = 1412
ERROR_INVALID_INDEX = 1413
ERROR_INVALID_ICON_HANDLE = 1414
ERROR_PRIVATE_DIALOG_INDEX = 1415
ERROR_LISTBOX_ID_NOT_FOUND = 1416
ERROR_NO_WILDCARD_CHARACTERS = 1417
ERROR_CLIPBOARD_NOT_OPEN = 1418
ERROR_HOTKEY_NOT_REGISTERED = 1419
ERROR_WINDOW_NOT_DIALOG = 1420
ERROR_CONTROL_ID_NOT_FOUND = 1421
ERROR_INVALID_COMBOBOX_MESSAGE = 1422
ERROR_WINDOW_NOT_COMBOBOX = 1423
ERROR_INVALID_EDIT_HEIGHT = 1424
ERROR_DC_NOT_FOUND = 1425
ERROR_INVALID_HOOK_FILTER = 1426
ERROR_INVALID_FILTER_PROC = 1427
ERROR_HOOK_NEEDS_HMOD = 1428
ERROR_GLOBAL_ONLY_HOOK = 1429
ERROR_JOURNAL_HOOK_SET = 1430
ERROR_HOOK_NOT_INSTALLED = 1431
ERROR_INVALID_LB_MESSAGE = 1432
ERROR_SETCOUNT_ON_BAD_LB = 1433
ERROR_LB_WITHOUT_TABSTOPS = 1434
ERROR_DESTROY_OBJECT_OF_OTHER_THREAD = 1435
ERROR_CHILD_WINDOW_MENU = 1436
ERROR_NO_SYSTEM_MENU = 1437
ERROR_INVALID_MSGBOX_STYLE = 1438
ERROR_INVALID_SPI_VALUE = 1439
ERROR_SCREEN_ALREADY_LOCKED = 1440
ERROR_HWNDS_HAVE_DIFF_PARENT = 1441
ERROR_NOT_CHILD_WINDOW = 1442
ERROR_INVALID_GW_COMMAND = 1443
ERROR_INVALID_THREAD_ID = 1444
ERROR_NON_MDICHILD_WINDOW = 1445
ERROR_POPUP_ALREADY_ACTIVE = 1446
ERROR_NO_SCROLLBARS = 1447
ERROR_INVALID_SCROLLBAR_RANGE = 1448
ERROR_INVALID_SHOWWIN_COMMAND = 1449
ERROR_NO_SYSTEM_RESOURCES = 1450
ERROR_NONPAGED_SYSTEM_RESOURCES = 1451
ERROR_PAGED_SYSTEM_RESOURCES = 1452
ERROR_WORKING_SET_QUOTA = 1453
ERROR_PAGEFILE_QUOTA = 1454
ERROR_COMMITMENT_LIMIT = 1455
ERROR_MENU_ITEM_NOT_FOUND = 1456
ERROR_INVALID_KEYBOARD_HANDLE = 1457
ERROR_HOOK_TYPE_NOT_ALLOWED = 1458
ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION = 1459
ERROR_TIMEOUT = 1460
ERROR_INVALID_MONITOR_HANDLE = 1461
ERROR_INCORRECT_SIZE = 1462
ERROR_SYMLINK_CLASS_DISABLED = 1463
ERROR_SYMLINK_NOT_SUPPORTED = 1464
ERROR_XML_PARSE_ERROR = 1465
ERROR_XMLDSIG_ERROR = 1466
ERROR_RESTART_APPLICATION = 1467
ERROR_WRONG_COMPARTMENT = 1468
ERROR_AUTHIP_FAILURE = 1469
ERROR_NO_NVRAM_RESOURCES = 1470
ERROR_EVENTLOG_FILE_CORRUPT = 1500
ERROR_EVENTLOG_CANT_START = 1501
ERROR_LOG_FILE_FULL = 1502
ERROR_EVENTLOG_FILE_CHANGED = 1503
ERROR_INVALID_TASK_NAME = 1550
ERROR_INVALID_TASK_INDEX = 1551
ERROR_THREAD_ALREADY_IN_TASK = 1552
ERROR_INSTALL_SERVICE_FAILURE = 1601
ERROR_INSTALL_USEREXIT = 1602
ERROR_INSTALL_FAILURE = 1603
ERROR_INSTALL_SUSPEND = 1604
ERROR_UNKNOWN_PRODUCT = 1605
ERROR_UNKNOWN_FEATURE = 1606
ERROR_UNKNOWN_COMPONENT = 1607
ERROR_UNKNOWN_PROPERTY = 1608
ERROR_INVALID_HANDLE_STATE = 1609
ERROR_BAD_CONFIGURATION = 1610
ERROR_INDEX_ABSENT = 1611
ERROR_INSTALL_SOURCE_ABSENT = 1612
ERROR_INSTALL_PACKAGE_VERSION = 1613
ERROR_PRODUCT_UNINSTALLED = 1614
ERROR_BAD_QUERY_SYNTAX = 1615
ERROR_INVALID_FIELD = 1616
ERROR_DEVICE_REMOVED = 1617
ERROR_INSTALL_ALREADY_RUNNING = 1618
ERROR_INSTALL_PACKAGE_OPEN_FAILED = 1619
ERROR_INSTALL_PACKAGE_INVALID = 1620
ERROR_INSTALL_UI_FAILURE = 1621
ERROR_INSTALL_LOG_FAILURE = 1622
ERROR_INSTALL_LANGUAGE_UNSUPPORTED = 1623
ERROR_INSTALL_TRANSFORM_FAILURE = 1624
ERROR_INSTALL_PACKAGE_REJECTED = 1625
ERROR_FUNCTION_NOT_CALLED = 1626
ERROR_FUNCTION_FAILED = 1627
ERROR_INVALID_TABLE = 1628
ERROR_DATATYPE_MISMATCH = 1629
ERROR_UNSUPPORTED_TYPE = 1630
ERROR_CREATE_FAILED = 1631
ERROR_INSTALL_TEMP_UNWRITABLE = 1632
ERROR_INSTALL_PLATFORM_UNSUPPORTED = 1633
ERROR_INSTALL_NOTUSED = 1634
ERROR_PATCH_PACKAGE_OPEN_FAILED = 1635
ERROR_PATCH_PACKAGE_INVALID = 1636
ERROR_PATCH_PACKAGE_UNSUPPORTED = 1637
ERROR_PRODUCT_VERSION = 1638
ERROR_INVALID_COMMAND_LINE = 1639
ERROR_INSTALL_REMOTE_DISALLOWED = 1640
ERROR_SUCCESS_REBOOT_INITIATED = 1641
ERROR_PATCH_TARGET_NOT_FOUND = 1642
ERROR_PATCH_PACKAGE_REJECTED = 1643
ERROR_INSTALL_TRANSFORM_REJECTED = 1644
ERROR_INSTALL_REMOTE_PROHIBITED = 1645
ERROR_PATCH_REMOVAL_UNSUPPORTED = 1646
ERROR_UNKNOWN_PATCH = 1647
ERROR_PATCH_NO_SEQUENCE = 1648
ERROR_PATCH_REMOVAL_DISALLOWED = 1649
ERROR_INVALID_PATCH_XML = 1650
ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT = 1651
ERROR_INSTALL_SERVICE_SAFEBOOT = 1652
ERROR_FAIL_FAST_EXCEPTION = 1653
RPC_S_INVALID_STRING_BINDING = 1700
RPC_S_WRONG_KIND_OF_BINDING = 1701
RPC_S_INVALID_BINDING = 1702
RPC_S_PROTSEQ_NOT_SUPPORTED = 1703
RPC_S_INVALID_RPC_PROTSEQ = 1704
RPC_S_INVALID_STRING_UUID = 1705
RPC_S_INVALID_ENDPOINT_FORMAT = 1706
RPC_S_INVALID_NET_ADDR = 1707
RPC_S_NO_ENDPOINT_FOUND = 1708
RPC_S_INVALID_TIMEOUT = 1709
RPC_S_OBJECT_NOT_FOUND = 1710
RPC_S_ALREADY_REGISTERED = 1711
RPC_S_TYPE_ALREADY_REGISTERED = 1712
RPC_S_ALREADY_LISTENING = 1713
RPC_S_NO_PROTSEQS_REGISTERED = 1714
RPC_S_NOT_LISTENING = 1715
RPC_S_UNKNOWN_MGR_TYPE = 1716
RPC_S_UNKNOWN_IF = 1717
RPC_S_NO_BINDINGS = 1718
RPC_S_NO_PROTSEQS = 1719
RPC_S_CANT_CREATE_ENDPOINT = 1720
RPC_S_OUT_OF_RESOURCES = 1721
RPC_S_SERVER_UNAVAILABLE = 1722
RPC_S_SERVER_TOO_BUSY = 1723
RPC_S_INVALID_NETWORK_OPTIONS = 1724
RPC_S_NO_CALL_ACTIVE = 1725
RPC_S_CALL_FAILED = 1726
RPC_S_CALL_FAILED_DNE = 1727
RPC_S_PROTOCOL_ERROR = 1728
RPC_S_PROXY_ACCESS_DENIED = 1729
RPC_S_UNSUPPORTED_TRANS_SYN = 1730
RPC_S_UNSUPPORTED_TYPE = 1732
RPC_S_INVALID_TAG = 1733
RPC_S_INVALID_BOUND = 1734
RPC_S_NO_ENTRY_NAME = 1735
RPC_S_INVALID_NAME_SYNTAX = 1736
RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737
RPC_S_UUID_NO_ADDRESS = 1739
RPC_S_DUPLICATE_ENDPOINT = 1740
RPC_S_UNKNOWN_AUTHN_TYPE = 1741
RPC_S_MAX_CALLS_TOO_SMALL = 1742
RPC_S_STRING_TOO_LONG = 1743
RPC_S_PROTSEQ_NOT_FOUND = 1744
RPC_S_PROCNUM_OUT_OF_RANGE = 1745
RPC_S_BINDING_HAS_NO_AUTH = 1746
RPC_S_UNKNOWN_AUTHN_SERVICE = 1747
RPC_S_UNKNOWN_AUTHN_LEVEL = 1748
RPC_S_INVALID_AUTH_IDENTITY = 1749
RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750
EPT_S_INVALID_ENTRY = 1751
EPT_S_CANT_PERFORM_OP = 1752
EPT_S_NOT_REGISTERED = 1753
RPC_S_NOTHING_TO_EXPORT = 1754
RPC_S_INCOMPLETE_NAME = 1755
RPC_S_INVALID_VERS_OPTION = 1756
RPC_S_NO_MORE_MEMBERS = 1757
RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758
RPC_S_INTERFACE_NOT_FOUND = 1759
RPC_S_ENTRY_ALREADY_EXISTS = 1760
RPC_S_ENTRY_NOT_FOUND = 1761
RPC_S_NAME_SERVICE_UNAVAILABLE = 1762
RPC_S_INVALID_NAF_ID = 1763
RPC_S_CANNOT_SUPPORT = 1764
RPC_S_NO_CONTEXT_AVAILABLE = 1765
RPC_S_INTERNAL_ERROR = 1766
RPC_S_ZERO_DIVIDE = 1767
RPC_S_ADDRESS_ERROR = 1768
RPC_S_FP_DIV_ZERO = 1769
RPC_S_FP_UNDERFLOW = 1770
RPC_S_FP_OVERFLOW = 1771
RPC_X_NO_MORE_ENTRIES = 1772
RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773
RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774
RPC_X_SS_IN_NULL_CONTEXT = 1775
RPC_X_SS_CONTEXT_DAMAGED = 1777
RPC_X_SS_HANDLES_MISMATCH = 1778
RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779
RPC_X_NULL_REF_POINTER = 1780
RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781
RPC_X_BYTE_COUNT_TOO_SMALL = 1782
RPC_X_BAD_STUB_DATA = 1783
ERROR_INVALID_USER_BUFFER = 1784
ERROR_UNRECOGNIZED_MEDIA = 1785
ERROR_NO_TRUST_LSA_SECRET = 1786
ERROR_NO_TRUST_SAM_ACCOUNT = 1787
ERROR_TRUSTED_DOMAIN_FAILURE = 1788
ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789
ERROR_TRUST_FAILURE = 1790
RPC_S_CALL_IN_PROGRESS = 1791
ERROR_NETLOGON_NOT_STARTED = 1792
ERROR_ACCOUNT_EXPIRED = 1793
ERROR_REDIRECTOR_HAS_OPEN_HANDLES = 1794
ERROR_PRINTER_DRIVER_ALREADY_INSTALLED = 1795
ERROR_UNKNOWN_PORT = 1796
ERROR_UNKNOWN_PRINTER_DRIVER = 1797
ERROR_UNKNOWN_PRINTPROCESSOR = 1798
ERROR_INVALID_SEPARATOR_FILE = 1799
ERROR_INVALID_PRIORITY = 1800
ERROR_INVALID_PRINTER_NAME = 1801
ERROR_PRINTER_ALREADY_EXISTS = 1802
ERROR_INVALID_PRINTER_COMMAND = 1803
ERROR_INVALID_DATATYPE = 1804
ERROR_INVALID_ENVIRONMENT = 1805
RPC_S_NO_MORE_BINDINGS = 1806
ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807
ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808
ERROR_NOLOGON_SERVER_TRUST_ACCOUNT = 1809
ERROR_DOMAIN_TRUST_INCONSISTENT = 1810
ERROR_SERVER_HAS_OPEN_HANDLES = 1811
ERROR_RESOURCE_DATA_NOT_FOUND = 1812
ERROR_RESOURCE_TYPE_NOT_FOUND = 1813
ERROR_RESOURCE_NAME_NOT_FOUND = 1814
ERROR_RESOURCE_LANG_NOT_FOUND = 1815
ERROR_NOT_ENOUGH_QUOTA = 1816
RPC_S_NO_INTERFACES = 1817
RPC_S_CALL_CANCELLED = 1818
RPC_S_BINDING_INCOMPLETE = 1819
RPC_S_COMM_FAILURE = 1820
RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821
RPC_S_NO_PRINC_NAME = 1822
RPC_S_NOT_RPC_ERROR = 1823
RPC_S_UUID_LOCAL_ONLY = 1824
RPC_S_SEC_PKG_ERROR = 1825
RPC_S_NOT_CANCELLED = 1826
RPC_X_INVALID_ES_ACTION = 1827
RPC_X_WRONG_ES_VERSION = 1828
RPC_X_WRONG_STUB_VERSION = 1829
RPC_X_INVALID_PIPE_OBJECT = 1830
RPC_X_WRONG_PIPE_ORDER = 1831
RPC_X_WRONG_PIPE_VERSION = 1832
RPC_S_COOKIE_AUTH_FAILED = 1833
RPC_S_GROUP_MEMBER_NOT_FOUND = 1898
EPT_S_CANT_CREATE = 1899
RPC_S_INVALID_OBJECT = 1900
ERROR_INVALID_TIME = 1901
ERROR_INVALID_FORM_NAME = 1902
ERROR_INVALID_FORM_SIZE = 1903
ERROR_ALREADY_WAITING = 1904
ERROR_PRINTER_DELETED = 1905
ERROR_INVALID_PRINTER_STATE = 1906
ERROR_PASSWORD_MUST_CHANGE = 1907
ERROR_DOMAIN_CONTROLLER_NOT_FOUND = 1908
ERROR_ACCOUNT_LOCKED_OUT = 1909
OR_INVALID_OXID = 1910
OR_INVALID_OID = 1911
OR_INVALID_SET = 1912
RPC_S_SEND_INCOMPLETE = 1913
RPC_S_INVALID_ASYNC_HANDLE = 1914
RPC_S_INVALID_ASYNC_CALL = 1915
RPC_X_PIPE_CLOSED = 1916
RPC_X_PIPE_DISCIPLINE_ERROR = 1917
RPC_X_PIPE_EMPTY = 1918
ERROR_NO_SITENAME = 1919
ERROR_CANT_ACCESS_FILE = 1920
ERROR_CANT_RESOLVE_FILENAME = 1921
RPC_S_ENTRY_TYPE_MISMATCH = 1922
RPC_S_NOT_ALL_OBJS_EXPORTED = 1923
RPC_S_INTERFACE_NOT_EXPORTED = 1924
RPC_S_PROFILE_NOT_ADDED = 1925
RPC_S_PRF_ELT_NOT_ADDED = 1926
RPC_S_PRF_ELT_NOT_REMOVED = 1927
RPC_S_GRP_ELT_NOT_ADDED = 1928
RPC_S_GRP_ELT_NOT_REMOVED = 1929
ERROR_KM_DRIVER_BLOCKED = 1930
ERROR_CONTEXT_EXPIRED = 1931
ERROR_PER_USER_TRUST_QUOTA_EXCEEDED = 1932
ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED = 1933
ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934
ERROR_AUTHENTICATION_FIREWALL_FAILED = 1935
ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936
ERROR_NTLM_BLOCKED = 1937
ERROR_PASSWORD_CHANGE_REQUIRED = 1938
ERROR_INVALID_PIXEL_FORMAT = 2000
ERROR_BAD_DRIVER = 2001
ERROR_INVALID_WINDOW_STYLE = 2002
ERROR_METAFILE_NOT_SUPPORTED = 2003
ERROR_TRANSFORM_NOT_SUPPORTED = 2004
ERROR_CLIPPING_NOT_SUPPORTED = 2005
ERROR_INVALID_CMM = 2010
ERROR_INVALID_PROFILE = 2011
ERROR_TAG_NOT_FOUND = 2012
ERROR_TAG_NOT_PRESENT = 2013
ERROR_DUPLICATE_TAG = 2014
ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015
ERROR_PROFILE_NOT_FOUND = 2016
ERROR_INVALID_COLORSPACE = 2017
ERROR_ICM_NOT_ENABLED = 2018
ERROR_DELETING_ICM_XFORM = 2019
ERROR_INVALID_TRANSFORM = 2020
ERROR_COLORSPACE_MISMATCH = 2021
ERROR_INVALID_COLORINDEX = 2022
ERROR_PROFILE_DOES_NOT_MATCH_DEVICE = 2023
ERROR_CONNECTED_OTHER_PASSWORD = 2108
ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT = 2109
ERROR_BAD_USERNAME = 2202
ERROR_NOT_CONNECTED = 2250
ERROR_OPEN_FILES = 2401
ERROR_ACTIVE_CONNECTIONS = 2402
ERROR_DEVICE_IN_USE = 2404
ERROR_UNKNOWN_PRINT_MONITOR = 3000
ERROR_PRINTER_DRIVER_IN_USE = 3001
ERROR_SPOOL_FILE_NOT_FOUND = 3002
ERROR_SPL_NO_STARTDOC = 3003
ERROR_SPL_NO_ADDJOB = 3004
ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED = 3005
ERROR_PRINT_MONITOR_ALREADY_INSTALLED = 3006
ERROR_INVALID_PRINT_MONITOR = 3007
ERROR_PRINT_MONITOR_IN_USE = 3008
ERROR_PRINTER_HAS_JOBS_QUEUED = 3009
ERROR_SUCCESS_REBOOT_REQUIRED = 3010
ERROR_SUCCESS_RESTART_REQUIRED = 3011
ERROR_PRINTER_NOT_FOUND = 3012
ERROR_PRINTER_DRIVER_WARNED = 3013
ERROR_PRINTER_DRIVER_BLOCKED = 3014
ERROR_PRINTER_DRIVER_PACKAGE_IN_USE = 3015
ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND = 3016
ERROR_FAIL_REBOOT_REQUIRED = 3017
ERROR_FAIL_REBOOT_INITIATED = 3018
ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019
ERROR_PRINT_JOB_RESTART_REQUIRED = 3020
ERROR_REQUEST_PAUSED = 3050
ERROR_IO_REISSUE_AS_CACHED = 3950
ERROR_WINS_INTERNAL = 4000
ERROR_CAN_NOT_DEL_LOCAL_WINS = 4001
ERROR_STATIC_INIT = 4002
ERROR_INC_BACKUP = 4003
ERROR_FULL_BACKUP = 4004
ERROR_REC_NON_EXISTENT = 4005
ERROR_RPL_NOT_ALLOWED = 4006
PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED = 4050
PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO = 4051
PEERDIST_ERROR_MISSING_DATA = 4052
PEERDIST_ERROR_NO_MORE = 4053
PEERDIST_ERROR_NOT_INITIALIZED = 4054
PEERDIST_ERROR_ALREADY_INITIALIZED = 4055
PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS = 4056
PEERDIST_ERROR_INVALIDATED = 4057
PEERDIST_ERROR_ALREADY_EXISTS = 4058
PEERDIST_ERROR_OPERATION_NOTFOUND = 4059
PEERDIST_ERROR_ALREADY_COMPLETED = 4060
PEERDIST_ERROR_OUT_OF_BOUNDS = 4061
PEERDIST_ERROR_VERSION_UNSUPPORTED = 4062
PEERDIST_ERROR_INVALID_CONFIGURATION = 4063
PEERDIST_ERROR_NOT_LICENSED = 4064
PEERDIST_ERROR_SERVICE_UNAVAILABLE = 4065
PEERDIST_ERROR_TRUST_FAILURE = 4066
ERROR_DHCP_ADDRESS_CONFLICT = 4100
ERROR_WMI_GUID_NOT_FOUND = 4200
ERROR_WMI_INSTANCE_NOT_FOUND = 4201
ERROR_WMI_ITEMID_NOT_FOUND = 4202
ERROR_WMI_TRY_AGAIN = 4203
ERROR_WMI_DP_NOT_FOUND = 4204
ERROR_WMI_UNRESOLVED_INSTANCE_REF = 4205
ERROR_WMI_ALREADY_ENABLED = 4206
ERROR_WMI_GUID_DISCONNECTED = 4207
ERROR_WMI_SERVER_UNAVAILABLE = 4208
ERROR_WMI_DP_FAILED = 4209
ERROR_WMI_INVALID_MOF = 4210
ERROR_WMI_INVALID_REGINFO = 4211
ERROR_WMI_ALREADY_DISABLED = 4212
ERROR_WMI_READ_ONLY = 4213
ERROR_WMI_SET_FAILURE = 4214
ERROR_NOT_APPCONTAINER = 4250
ERROR_APPCONTAINER_REQUIRED = 4251
ERROR_NOT_SUPPORTED_IN_APPCONTAINER = 4252
ERROR_INVALID_PACKAGE_SID_LENGTH = 4253
ERROR_INVALID_MEDIA = 4300
ERROR_INVALID_LIBRARY = 4301
ERROR_INVALID_MEDIA_POOL = 4302
ERROR_DRIVE_MEDIA_MISMATCH = 4303
ERROR_MEDIA_OFFLINE = 4304
ERROR_LIBRARY_OFFLINE = 4305
ERROR_EMPTY = 4306
ERROR_NOT_EMPTY = 4307
ERROR_MEDIA_UNAVAILABLE = 4308
ERROR_RESOURCE_DISABLED = 4309
ERROR_INVALID_CLEANER = 4310
ERROR_UNABLE_TO_CLEAN = 4311
ERROR_OBJECT_NOT_FOUND = 4312
ERROR_DATABASE_FAILURE = 4313
ERROR_DATABASE_FULL = 4314
ERROR_MEDIA_INCOMPATIBLE = 4315
ERROR_RESOURCE_NOT_PRESENT = 4316
ERROR_INVALID_OPERATION = 4317
ERROR_MEDIA_NOT_AVAILABLE = 4318
ERROR_DEVICE_NOT_AVAILABLE = 4319
ERROR_REQUEST_REFUSED = 4320
ERROR_INVALID_DRIVE_OBJECT = 4321
ERROR_LIBRARY_FULL = 4322
ERROR_MEDIUM_NOT_ACCESSIBLE = 4323
ERROR_UNABLE_TO_LOAD_MEDIUM = 4324
ERROR_UNABLE_TO_INVENTORY_DRIVE = 4325
ERROR_UNABLE_TO_INVENTORY_SLOT = 4326
ERROR_UNABLE_TO_INVENTORY_TRANSPORT = 4327
ERROR_TRANSPORT_FULL = 4328
ERROR_CONTROLLING_IEPORT = 4329
ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA = 4330
ERROR_CLEANER_SLOT_SET = 4331
ERROR_CLEANER_SLOT_NOT_SET = 4332
ERROR_CLEANER_CARTRIDGE_SPENT = 4333
ERROR_UNEXPECTED_OMID = 4334
ERROR_CANT_DELETE_LAST_ITEM = 4335
ERROR_MESSAGE_EXCEEDS_MAX_SIZE = 4336
ERROR_VOLUME_CONTAINS_SYS_FILES = 4337
ERROR_INDIGENOUS_TYPE = 4338
ERROR_NO_SUPPORTING_DRIVES = 4339
ERROR_CLEANER_CARTRIDGE_INSTALLED = 4340
ERROR_IEPORT_FULL = 4341
ERROR_FILE_OFFLINE = 4350
ERROR_REMOTE_STORAGE_NOT_ACTIVE = 4351
ERROR_REMOTE_STORAGE_MEDIA_ERROR = 4352
ERROR_NOT_A_REPARSE_POINT = 4390
ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391
ERROR_INVALID_REPARSE_DATA = 4392
ERROR_REPARSE_TAG_INVALID = 4393
ERROR_REPARSE_TAG_MISMATCH = 4394
ERROR_APP_DATA_NOT_FOUND = 4400
ERROR_APP_DATA_EXPIRED = 4401
ERROR_APP_DATA_CORRUPT = 4402
ERROR_APP_DATA_LIMIT_EXCEEDED = 4403
ERROR_APP_DATA_REBOOT_REQUIRED = 4404
ERROR_SECUREBOOT_ROLLBACK_DETECTED = 4420
ERROR_SECUREBOOT_POLICY_VIOLATION = 4421
ERROR_SECUREBOOT_INVALID_POLICY = 4422
ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND = 4423
ERROR_SECUREBOOT_POLICY_NOT_SIGNED = 4424
ERROR_SECUREBOOT_NOT_ENABLED = 4425
ERROR_SECUREBOOT_FILE_REPLACED = 4426
ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED = 4440
ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED = 4441
ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED = 4442
ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED = 4443
ERROR_VOLUME_NOT_SIS_ENABLED = 4500
ERROR_DEPENDENT_RESOURCE_EXISTS = 5001
ERROR_DEPENDENCY_NOT_FOUND = 5002
ERROR_DEPENDENCY_ALREADY_EXISTS = 5003
ERROR_RESOURCE_NOT_ONLINE = 5004
ERROR_HOST_NODE_NOT_AVAILABLE = 5005
ERROR_RESOURCE_NOT_AVAILABLE = 5006
ERROR_RESOURCE_NOT_FOUND = 5007
ERROR_SHUTDOWN_CLUSTER = 5008
ERROR_CANT_EVICT_ACTIVE_NODE = 5009
ERROR_OBJECT_ALREADY_EXISTS = 5010
ERROR_OBJECT_IN_LIST = 5011
ERROR_GROUP_NOT_AVAILABLE = 5012
ERROR_GROUP_NOT_FOUND = 5013
ERROR_GROUP_NOT_ONLINE = 5014
ERROR_HOST_NODE_NOT_RESOURCE_OWNER = 5015
ERROR_HOST_NODE_NOT_GROUP_OWNER = 5016
ERROR_RESMON_CREATE_FAILED = 5017
ERROR_RESMON_ONLINE_FAILED = 5018
ERROR_RESOURCE_ONLINE = 5019
ERROR_QUORUM_RESOURCE = 5020
ERROR_NOT_QUORUM_CAPABLE = 5021
ERROR_CLUSTER_SHUTTING_DOWN = 5022
ERROR_INVALID_STATE = 5023
ERROR_RESOURCE_PROPERTIES_STORED = 5024
ERROR_NOT_QUORUM_CLASS = 5025
ERROR_CORE_RESOURCE = 5026
ERROR_QUORUM_RESOURCE_ONLINE_FAILED = 5027
ERROR_QUORUMLOG_OPEN_FAILED = 5028
ERROR_CLUSTERLOG_CORRUPT = 5029
ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE = 5030
ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE = 5031
ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND = 5032
ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE = 5033
ERROR_QUORUM_OWNER_ALIVE = 5034
ERROR_NETWORK_NOT_AVAILABLE = 5035
ERROR_NODE_NOT_AVAILABLE = 5036
ERROR_ALL_NODES_NOT_AVAILABLE = 5037
ERROR_RESOURCE_FAILED = 5038
ERROR_CLUSTER_INVALID_NODE = 5039
ERROR_CLUSTER_NODE_EXISTS = 5040
ERROR_CLUSTER_JOIN_IN_PROGRESS = 5041
ERROR_CLUSTER_NODE_NOT_FOUND = 5042
ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND = 5043
ERROR_CLUSTER_NETWORK_EXISTS = 5044
ERROR_CLUSTER_NETWORK_NOT_FOUND = 5045
ERROR_CLUSTER_NETINTERFACE_EXISTS = 5046
ERROR_CLUSTER_NETINTERFACE_NOT_FOUND = 5047
ERROR_CLUSTER_INVALID_REQUEST = 5048
ERROR_CLUSTER_INVALID_NETWORK_PROVIDER = 5049
ERROR_CLUSTER_NODE_DOWN = 5050
ERROR_CLUSTER_NODE_UNREACHABLE = 5051
ERROR_CLUSTER_NODE_NOT_MEMBER = 5052
ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS = 5053
ERROR_CLUSTER_INVALID_NETWORK = 5054
ERROR_CLUSTER_NODE_UP = 5056
ERROR_CLUSTER_IPADDR_IN_USE = 5057
ERROR_CLUSTER_NODE_NOT_PAUSED = 5058
ERROR_CLUSTER_NO_SECURITY_CONTEXT = 5059
ERROR_CLUSTER_NETWORK_NOT_INTERNAL = 5060
ERROR_CLUSTER_NODE_ALREADY_UP = 5061
ERROR_CLUSTER_NODE_ALREADY_DOWN = 5062
ERROR_CLUSTER_NETWORK_ALREADY_ONLINE = 5063
ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE = 5064
ERROR_CLUSTER_NODE_ALREADY_MEMBER = 5065
ERROR_CLUSTER_LAST_INTERNAL_NETWORK = 5066
ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS = 5067
ERROR_INVALID_OPERATION_ON_QUORUM = 5068
ERROR_DEPENDENCY_NOT_ALLOWED = 5069
ERROR_CLUSTER_NODE_PAUSED = 5070
ERROR_NODE_CANT_HOST_RESOURCE = 5071
ERROR_CLUSTER_NODE_NOT_READY = 5072
ERROR_CLUSTER_NODE_SHUTTING_DOWN = 5073
ERROR_CLUSTER_JOIN_ABORTED = 5074
ERROR_CLUSTER_INCOMPATIBLE_VERSIONS = 5075
ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED = 5076
ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED = 5077
ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND = 5078
ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED = 5079
ERROR_CLUSTER_RESNAME_NOT_FOUND = 5080
ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED = 5081
ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST = 5082
ERROR_CLUSTER_DATABASE_SEQMISMATCH = 5083
ERROR_RESMON_INVALID_STATE = 5084
ERROR_CLUSTER_GUM_NOT_LOCKER = 5085
ERROR_QUORUM_DISK_NOT_FOUND = 5086
ERROR_DATABASE_BACKUP_CORRUPT = 5087
ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT = 5088
ERROR_RESOURCE_PROPERTY_UNCHANGEABLE = 5089
ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE = 5890
ERROR_CLUSTER_QUORUMLOG_NOT_FOUND = 5891
ERROR_CLUSTER_MEMBERSHIP_HALT = 5892
ERROR_CLUSTER_INSTANCE_ID_MISMATCH = 5893
ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP = 5894
ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH = 5895
ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP = 5896
ERROR_CLUSTER_PARAMETER_MISMATCH = 5897
ERROR_NODE_CANNOT_BE_CLUSTERED = 5898
ERROR_CLUSTER_WRONG_OS_VERSION = 5899
ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME = 5900
ERROR_CLUSCFG_ALREADY_COMMITTED = 5901
ERROR_CLUSCFG_ROLLBACK_FAILED = 5902
ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT = 5903
ERROR_CLUSTER_OLD_VERSION = 5904
ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME = 5905
ERROR_CLUSTER_NO_NET_ADAPTERS = 5906
ERROR_CLUSTER_POISONED = 5907
ERROR_CLUSTER_GROUP_MOVING = 5908
ERROR_CLUSTER_RESOURCE_TYPE_BUSY = 5909
ERROR_RESOURCE_CALL_TIMED_OUT = 5910
ERROR_INVALID_CLUSTER_IPV6_ADDRESS = 5911
ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION = 5912
ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS = 5913
ERROR_CLUSTER_PARTIAL_SEND = 5914
ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION = 5915
ERROR_CLUSTER_INVALID_STRING_TERMINATION = 5916
ERROR_CLUSTER_INVALID_STRING_FORMAT = 5917
ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS = 5918
ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS = 5919
ERROR_CLUSTER_NULL_DATA = 5920
ERROR_CLUSTER_PARTIAL_READ = 5921
ERROR_CLUSTER_PARTIAL_WRITE = 5922
ERROR_CLUSTER_CANT_DESERIALIZE_DATA = 5923
ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT = 5924
ERROR_CLUSTER_NO_QUORUM = 5925
ERROR_CLUSTER_INVALID_IPV6_NETWORK = 5926
ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK = 5927
ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP = 5928
ERROR_DEPENDENCY_TREE_TOO_COMPLEX = 5929
ERROR_EXCEPTION_IN_RESOURCE_CALL = 5930
ERROR_CLUSTER_RHS_FAILED_INITIALIZATION = 5931
ERROR_CLUSTER_NOT_INSTALLED = 5932
ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE = 5933
ERROR_CLUSTER_MAX_NODES_IN_CLUSTER = 5934
ERROR_CLUSTER_TOO_MANY_NODES = 5935
ERROR_CLUSTER_OBJECT_ALREADY_USED = 5936
ERROR_NONCORE_GROUPS_FOUND = 5937
ERROR_FILE_SHARE_RESOURCE_CONFLICT = 5938
ERROR_CLUSTER_EVICT_INVALID_REQUEST = 5939
ERROR_CLUSTER_SINGLETON_RESOURCE = 5940
ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE = 5941
ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED = 5942
ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR = 5943
ERROR_CLUSTER_GROUP_BUSY = 5944
ERROR_CLUSTER_NOT_SHARED_VOLUME = 5945
ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR = 5946
ERROR_CLUSTER_SHARED_VOLUMES_IN_USE = 5947
ERROR_CLUSTER_USE_SHARED_VOLUMES_API = 5948
ERROR_CLUSTER_BACKUP_IN_PROGRESS = 5949
ERROR_NON_CSV_PATH = 5950
ERROR_CSV_VOLUME_NOT_LOCAL = 5951
ERROR_CLUSTER_WATCHDOG_TERMINATING = 5952
ERROR_ENCRYPTION_FAILED = 6000
ERROR_DECRYPTION_FAILED = 6001
ERROR_FILE_ENCRYPTED = 6002
ERROR_NO_RECOVERY_POLICY = 6003
ERROR_NO_EFS = 6004
ERROR_WRONG_EFS = 6005
ERROR_NO_USER_KEYS = 6006
ERROR_FILE_NOT_ENCRYPTED = 6007
ERROR_NOT_EXPORT_FORMAT = 6008
ERROR_FILE_READ_ONLY = 6009
ERROR_DIR_EFS_DISALLOWED = 6010
ERROR_EFS_SERVER_NOT_TRUSTED = 6011
ERROR_BAD_RECOVERY_POLICY = 6012
ERROR_EFS_ALG_BLOB_TOO_BIG = 6013
ERROR_VOLUME_NOT_SUPPORT_EFS = 6014
ERROR_EFS_DISABLED = 6015
ERROR_EFS_VERSION_NOT_SUPPORT = 6016
ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE = 6017
ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER = 6018
ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE = 6019
ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE = 6020
ERROR_CS_ENCRYPTION_FILE_NOT_CSE = 6021
ERROR_ENCRYPTION_POLICY_DENIES_OPERATION = 6022
ERROR_NO_BROWSER_SERVERS_FOUND = 6118
SCHED_E_SERVICE_NOT_LOCALSYSTEM = 6200
ERROR_LOG_SECTOR_INVALID = 6600
ERROR_LOG_SECTOR_PARITY_INVALID = 6601
ERROR_LOG_SECTOR_REMAPPED = 6602
ERROR_LOG_BLOCK_INCOMPLETE = 6603
ERROR_LOG_INVALID_RANGE = 6604
ERROR_LOG_BLOCKS_EXHAUSTED = 6605
ERROR_LOG_READ_CONTEXT_INVALID = 6606
ERROR_LOG_RESTART_INVALID = 6607
ERROR_LOG_BLOCK_VERSION = 6608
ERROR_LOG_BLOCK_INVALID = 6609
ERROR_LOG_READ_MODE_INVALID = 6610
ERROR_LOG_NO_RESTART = 6611
ERROR_LOG_METADATA_CORRUPT = 6612
ERROR_LOG_METADATA_INVALID = 6613
ERROR_LOG_METADATA_INCONSISTENT = 6614
ERROR_LOG_RESERVATION_INVALID = 6615
ERROR_LOG_CANT_DELETE = 6616
ERROR_LOG_CONTAINER_LIMIT_EXCEEDED = 6617
ERROR_LOG_START_OF_LOG = 6618
ERROR_LOG_POLICY_ALREADY_INSTALLED = 6619
ERROR_LOG_POLICY_NOT_INSTALLED = 6620
ERROR_LOG_POLICY_INVALID = 6621
ERROR_LOG_POLICY_CONFLICT = 6622
ERROR_LOG_PINNED_ARCHIVE_TAIL = 6623
ERROR_LOG_RECORD_NONEXISTENT = 6624
ERROR_LOG_RECORDS_RESERVED_INVALID = 6625
ERROR_LOG_SPACE_RESERVED_INVALID = 6626
ERROR_LOG_TAIL_INVALID = 6627
ERROR_LOG_FULL = 6628
ERROR_COULD_NOT_RESIZE_LOG = 6629
ERROR_LOG_MULTIPLEXED = 6630
ERROR_LOG_DEDICATED = 6631
ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS = 6632
ERROR_LOG_ARCHIVE_IN_PROGRESS = 6633
ERROR_LOG_EPHEMERAL = 6634
ERROR_LOG_NOT_ENOUGH_CONTAINERS = 6635
ERROR_LOG_CLIENT_ALREADY_REGISTERED = 6636
ERROR_LOG_CLIENT_NOT_REGISTERED = 6637
ERROR_LOG_FULL_HANDLER_IN_PROGRESS = 6638
ERROR_LOG_CONTAINER_READ_FAILED = 6639
ERROR_LOG_CONTAINER_WRITE_FAILED = 6640
ERROR_LOG_CONTAINER_OPEN_FAILED = 6641
ERROR_LOG_CONTAINER_STATE_INVALID = 6642
ERROR_LOG_STATE_INVALID = 6643
ERROR_LOG_PINNED = 6644
ERROR_LOG_METADATA_FLUSH_FAILED = 6645
ERROR_LOG_INCONSISTENT_SECURITY = 6646
ERROR_LOG_APPENDED_FLUSH_FAILED = 6647
ERROR_LOG_PINNED_RESERVATION = 6648
ERROR_INVALID_TRANSACTION = 6700
ERROR_TRANSACTION_NOT_ACTIVE = 6701
ERROR_TRANSACTION_REQUEST_NOT_VALID = 6702
ERROR_TRANSACTION_NOT_REQUESTED = 6703
ERROR_TRANSACTION_ALREADY_ABORTED = 6704
ERROR_TRANSACTION_ALREADY_COMMITTED = 6705
ERROR_TM_INITIALIZATION_FAILED = 6706
ERROR_RESOURCEMANAGER_READ_ONLY = 6707
ERROR_TRANSACTION_NOT_JOINED = 6708
ERROR_TRANSACTION_SUPERIOR_EXISTS = 6709
ERROR_CRM_PROTOCOL_ALREADY_EXISTS = 6710
ERROR_TRANSACTION_PROPAGATION_FAILED = 6711
ERROR_CRM_PROTOCOL_NOT_FOUND = 6712
ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER = 6713
ERROR_CURRENT_TRANSACTION_NOT_VALID = 6714
ERROR_TRANSACTION_NOT_FOUND = 6715
ERROR_RESOURCEMANAGER_NOT_FOUND = 6716
ERROR_ENLISTMENT_NOT_FOUND = 6717
ERROR_TRANSACTIONMANAGER_NOT_FOUND = 6718
ERROR_TRANSACTIONMANAGER_NOT_ONLINE = 6719
ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION = 6720
ERROR_TRANSACTION_NOT_ROOT = 6721
ERROR_TRANSACTION_OBJECT_EXPIRED = 6722
ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED = 6723
ERROR_TRANSACTION_RECORD_TOO_LONG = 6724
ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED = 6725
ERROR_TRANSACTION_INTEGRITY_VIOLATED = 6726
ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH = 6727
ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT = 6728
ERROR_TRANSACTION_MUST_WRITETHROUGH = 6729
ERROR_TRANSACTION_NO_SUPERIOR = 6730
ERROR_HEURISTIC_DAMAGE_POSSIBLE = 6731
ERROR_TRANSACTIONAL_CONFLICT = 6800
ERROR_RM_NOT_ACTIVE = 6801
ERROR_RM_METADATA_CORRUPT = 6802
ERROR_DIRECTORY_NOT_RM = 6803
ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE = 6805
ERROR_LOG_RESIZE_INVALID_SIZE = 6806
ERROR_OBJECT_NO_LONGER_EXISTS = 6807
ERROR_STREAM_MINIVERSION_NOT_FOUND = 6808
ERROR_STREAM_MINIVERSION_NOT_VALID = 6809
ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION = 6810
ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT = 6811
ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS = 6812
ERROR_REMOTE_FILE_VERSION_MISMATCH = 6814
ERROR_HANDLE_NO_LONGER_VALID = 6815
ERROR_NO_TXF_METADATA = 6816
ERROR_LOG_CORRUPTION_DETECTED = 6817
ERROR_CANT_RECOVER_WITH_HANDLE_OPEN = 6818
ERROR_RM_DISCONNECTED = 6819
ERROR_ENLISTMENT_NOT_SUPERIOR = 6820
ERROR_RECOVERY_NOT_NEEDED = 6821
ERROR_RM_ALREADY_STARTED = 6822
ERROR_FILE_IDENTITY_NOT_PERSISTENT = 6823
ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY = 6824
ERROR_CANT_CROSS_RM_BOUNDARY = 6825
ERROR_TXF_DIR_NOT_EMPTY = 6826
ERROR_INDOUBT_TRANSACTIONS_EXIST = 6827
ERROR_TM_VOLATILE = 6828
ERROR_ROLLBACK_TIMER_EXPIRED = 6829
ERROR_TXF_ATTRIBUTE_CORRUPT = 6830
ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION = 6831
ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED = 6832
ERROR_LOG_GROWTH_FAILED = 6833
ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE = 6834
ERROR_TXF_METADATA_ALREADY_PRESENT = 6835
ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET = 6836
ERROR_TRANSACTION_REQUIRED_PROMOTION = 6837
ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION = 6838
ERROR_TRANSACTIONS_NOT_FROZEN = 6839
ERROR_TRANSACTION_FREEZE_IN_PROGRESS = 6840
ERROR_NOT_SNAPSHOT_VOLUME = 6841
ERROR_NO_SAVEPOINT_WITH_OPEN_FILES = 6842
ERROR_DATA_LOST_REPAIR = 6843
ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION = 6844
ERROR_TM_IDENTITY_MISMATCH = 6845
ERROR_FLOATED_SECTION = 6846
ERROR_CANNOT_ACCEPT_TRANSACTED_WORK = 6847
ERROR_CANNOT_ABORT_TRANSACTIONS = 6848
ERROR_BAD_CLUSTERS = 6849
ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION = 6850
ERROR_VOLUME_DIRTY = 6851
ERROR_NO_LINK_TRACKING_IN_TRANSACTION = 6852
ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION = 6853
ERROR_EXPIRED_HANDLE = 6854
ERROR_TRANSACTION_NOT_ENLISTED = 6855
ERROR_CTX_WINSTATION_NAME_INVALID = 7001
ERROR_CTX_INVALID_PD = 7002
ERROR_CTX_PD_NOT_FOUND = 7003
ERROR_CTX_WD_NOT_FOUND = 7004
ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY = 7005
ERROR_CTX_SERVICE_NAME_COLLISION = 7006
ERROR_CTX_CLOSE_PENDING = 7007
ERROR_CTX_NO_OUTBUF = 7008
ERROR_CTX_MODEM_INF_NOT_FOUND = 7009
ERROR_CTX_INVALID_MODEMNAME = 7010
ERROR_CTX_MODEM_RESPONSE_ERROR = 7011
ERROR_CTX_MODEM_RESPONSE_TIMEOUT = 7012
ERROR_CTX_MODEM_RESPONSE_NO_CARRIER = 7013
ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE = 7014
ERROR_CTX_MODEM_RESPONSE_BUSY = 7015
ERROR_CTX_MODEM_RESPONSE_VOICE = 7016
ERROR_CTX_TD_ERROR = 7017
ERROR_CTX_WINSTATION_NOT_FOUND = 7022
ERROR_CTX_WINSTATION_ALREADY_EXISTS = 7023
ERROR_CTX_WINSTATION_BUSY = 7024
ERROR_CTX_BAD_VIDEO_MODE = 7025
ERROR_CTX_GRAPHICS_INVALID = 7035
ERROR_CTX_LOGON_DISABLED = 7037
ERROR_CTX_NOT_CONSOLE = 7038
ERROR_CTX_CLIENT_QUERY_TIMEOUT = 7040
ERROR_CTX_CONSOLE_DISCONNECT = 7041
ERROR_CTX_CONSOLE_CONNECT = 7042
ERROR_CTX_SHADOW_DENIED = 7044
ERROR_CTX_WINSTATION_ACCESS_DENIED = 7045
ERROR_CTX_INVALID_WD = 7049
ERROR_CTX_SHADOW_INVALID = 7050
ERROR_CTX_SHADOW_DISABLED = 7051
ERROR_CTX_CLIENT_LICENSE_IN_USE = 7052
ERROR_CTX_CLIENT_LICENSE_NOT_SET = 7053
ERROR_CTX_LICENSE_NOT_AVAILABLE = 7054
ERROR_CTX_LICENSE_CLIENT_INVALID = 7055
ERROR_CTX_LICENSE_EXPIRED = 7056
ERROR_CTX_SHADOW_NOT_RUNNING = 7057
ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE = 7058
ERROR_ACTIVATION_COUNT_EXCEEDED = 7059
ERROR_CTX_WINSTATIONS_DISABLED = 7060
ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED = 7061
ERROR_CTX_SESSION_IN_USE = 7062
ERROR_CTX_NO_FORCE_LOGOFF = 7063
ERROR_CTX_ACCOUNT_RESTRICTION = 7064
ERROR_RDP_PROTOCOL_ERROR = 7065
ERROR_CTX_CDM_CONNECT = 7066
ERROR_CTX_CDM_DISCONNECT = 7067
ERROR_CTX_SECURITY_LAYER_ERROR = 7068
ERROR_TS_INCOMPATIBLE_SESSIONS = 7069
ERROR_TS_VIDEO_SUBSYSTEM_ERROR = 7070
FRS_ERR_INVALID_API_SEQUENCE = 8001
FRS_ERR_STARTING_SERVICE = 8002
FRS_ERR_STOPPING_SERVICE = 8003
FRS_ERR_INTERNAL_API = 8004
FRS_ERR_INTERNAL = 8005
FRS_ERR_SERVICE_COMM = 8006
FRS_ERR_INSUFFICIENT_PRIV = 8007
FRS_ERR_AUTHENTICATION = 8008
FRS_ERR_PARENT_INSUFFICIENT_PRIV = 8009
FRS_ERR_PARENT_AUTHENTICATION = 8010
FRS_ERR_CHILD_TO_PARENT_COMM = 8011
FRS_ERR_PARENT_TO_CHILD_COMM = 8012
FRS_ERR_SYSVOL_POPULATE = 8013
FRS_ERR_SYSVOL_POPULATE_TIMEOUT = 8014
FRS_ERR_SYSVOL_IS_BUSY = 8015
FRS_ERR_SYSVOL_DEMOTE = 8016
FRS_ERR_INVALID_SERVICE_PARAMETER = 8017
ERROR_DS_NOT_INSTALLED = 8200
ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY = 8201
ERROR_DS_NO_ATTRIBUTE_OR_VALUE = 8202
ERROR_DS_INVALID_ATTRIBUTE_SYNTAX = 8203
ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED = 8204
ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS = 8205
ERROR_DS_BUSY = 8206
ERROR_DS_UNAVAILABLE = 8207
ERROR_DS_NO_RIDS_ALLOCATED = 8208
ERROR_DS_NO_MORE_RIDS = 8209
ERROR_DS_INCORRECT_ROLE_OWNER = 8210
ERROR_DS_RIDMGR_INIT_ERROR = 8211
ERROR_DS_OBJ_CLASS_VIOLATION = 8212
ERROR_DS_CANT_ON_NON_LEAF = 8213
ERROR_DS_CANT_ON_RDN = 8214
ERROR_DS_CANT_MOD_OBJ_CLASS = 8215
ERROR_DS_CROSS_DOM_MOVE_ERROR = 8216
ERROR_DS_GC_NOT_AVAILABLE = 8217
ERROR_SHARED_POLICY = 8218
ERROR_POLICY_OBJECT_NOT_FOUND = 8219
ERROR_POLICY_ONLY_IN_DS = 8220
ERROR_PROMOTION_ACTIVE = 8221
ERROR_NO_PROMOTION_ACTIVE = 8222
ERROR_DS_OPERATIONS_ERROR = 8224
ERROR_DS_PROTOCOL_ERROR = 8225
ERROR_DS_TIMELIMIT_EXCEEDED = 8226
ERROR_DS_SIZELIMIT_EXCEEDED = 8227
ERROR_DS_ADMIN_LIMIT_EXCEEDED = 8228
ERROR_DS_COMPARE_FALSE = 8229
ERROR_DS_COMPARE_TRUE = 8230
ERROR_DS_AUTH_METHOD_NOT_SUPPORTED = 8231
ERROR_DS_STRONG_AUTH_REQUIRED = 8232
ERROR_DS_INAPPROPRIATE_AUTH = 8233
ERROR_DS_AUTH_UNKNOWN = 8234
ERROR_DS_REFERRAL = 8235
ERROR_DS_UNAVAILABLE_CRIT_EXTENSION = 8236
ERROR_DS_CONFIDENTIALITY_REQUIRED = 8237
ERROR_DS_INAPPROPRIATE_MATCHING = 8238
ERROR_DS_CONSTRAINT_VIOLATION = 8239
ERROR_DS_NO_SUCH_OBJECT = 8240
ERROR_DS_ALIAS_PROBLEM = 8241
ERROR_DS_INVALID_DN_SYNTAX = 8242
ERROR_DS_IS_LEAF = 8243
ERROR_DS_ALIAS_DEREF_PROBLEM = 8244
ERROR_DS_UNWILLING_TO_PERFORM = 8245
ERROR_DS_LOOP_DETECT = 8246
ERROR_DS_NAMING_VIOLATION = 8247
ERROR_DS_OBJECT_RESULTS_TOO_LARGE = 8248
ERROR_DS_AFFECTS_MULTIPLE_DSAS = 8249
ERROR_DS_SERVER_DOWN = 8250
ERROR_DS_LOCAL_ERROR = 8251
ERROR_DS_ENCODING_ERROR = 8252
ERROR_DS_DECODING_ERROR = 8253
ERROR_DS_FILTER_UNKNOWN = 8254
ERROR_DS_PARAM_ERROR = 8255
ERROR_DS_NOT_SUPPORTED = 8256
ERROR_DS_NO_RESULTS_RETURNED = 8257
ERROR_DS_CONTROL_NOT_FOUND = 8258
ERROR_DS_CLIENT_LOOP = 8259
ERROR_DS_REFERRAL_LIMIT_EXCEEDED = 8260
ERROR_DS_SORT_CONTROL_MISSING = 8261
ERROR_DS_OFFSET_RANGE_ERROR = 8262
ERROR_DS_ROOT_MUST_BE_NC = 8301
ERROR_DS_ADD_REPLICA_INHIBITED = 8302
ERROR_DS_ATT_NOT_DEF_IN_SCHEMA = 8303
ERROR_DS_MAX_OBJ_SIZE_EXCEEDED = 8304
ERROR_DS_OBJ_STRING_NAME_EXISTS = 8305
ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA = 8306
ERROR_DS_RDN_DOESNT_MATCH_SCHEMA = 8307
ERROR_DS_NO_REQUESTED_ATTS_FOUND = 8308
ERROR_DS_USER_BUFFER_TO_SMALL = 8309
ERROR_DS_ATT_IS_NOT_ON_OBJ = 8310
ERROR_DS_ILLEGAL_MOD_OPERATION = 8311
ERROR_DS_OBJ_TOO_LARGE = 8312
ERROR_DS_BAD_INSTANCE_TYPE = 8313
ERROR_DS_MASTERDSA_REQUIRED = 8314
ERROR_DS_OBJECT_CLASS_REQUIRED = 8315
ERROR_DS_MISSING_REQUIRED_ATT = 8316
ERROR_DS_ATT_NOT_DEF_FOR_CLASS = 8317
ERROR_DS_ATT_ALREADY_EXISTS = 8318
ERROR_DS_CANT_ADD_ATT_VALUES = 8320
ERROR_DS_SINGLE_VALUE_CONSTRAINT = 8321
ERROR_DS_RANGE_CONSTRAINT = 8322
ERROR_DS_ATT_VAL_ALREADY_EXISTS = 8323
ERROR_DS_CANT_REM_MISSING_ATT = 8324
ERROR_DS_CANT_REM_MISSING_ATT_VAL = 8325
ERROR_DS_ROOT_CANT_BE_SUBREF = 8326
ERROR_DS_NO_CHAINING = 8327
ERROR_DS_NO_CHAINED_EVAL = 8328
ERROR_DS_NO_PARENT_OBJECT = 8329
ERROR_DS_PARENT_IS_AN_ALIAS = 8330
ERROR_DS_CANT_MIX_MASTER_AND_REPS = 8331
ERROR_DS_CHILDREN_EXIST = 8332
ERROR_DS_OBJ_NOT_FOUND = 8333
ERROR_DS_ALIASED_OBJ_MISSING = 8334
ERROR_DS_BAD_NAME_SYNTAX = 8335
ERROR_DS_ALIAS_POINTS_TO_ALIAS = 8336
ERROR_DS_CANT_DEREF_ALIAS = 8337
ERROR_DS_OUT_OF_SCOPE = 8338
ERROR_DS_OBJECT_BEING_REMOVED = 8339
ERROR_DS_CANT_DELETE_DSA_OBJ = 8340
ERROR_DS_GENERIC_ERROR = 8341
ERROR_DS_DSA_MUST_BE_INT_MASTER = 8342
ERROR_DS_CLASS_NOT_DSA = 8343
ERROR_DS_INSUFF_ACCESS_RIGHTS = 8344
ERROR_DS_ILLEGAL_SUPERIOR = 8345
ERROR_DS_ATTRIBUTE_OWNED_BY_SAM = 8346
ERROR_DS_NAME_TOO_MANY_PARTS = 8347
ERROR_DS_NAME_TOO_LONG = 8348
ERROR_DS_NAME_VALUE_TOO_LONG = 8349
ERROR_DS_NAME_UNPARSEABLE = 8350
ERROR_DS_NAME_TYPE_UNKNOWN = 8351
ERROR_DS_NOT_AN_OBJECT = 8352
ERROR_DS_SEC_DESC_TOO_SHORT = 8353
ERROR_DS_SEC_DESC_INVALID = 8354
ERROR_DS_NO_DELETED_NAME = 8355
ERROR_DS_SUBREF_MUST_HAVE_PARENT = 8356
ERROR_DS_NCNAME_MUST_BE_NC = 8357
ERROR_DS_CANT_ADD_SYSTEM_ONLY = 8358
ERROR_DS_CLASS_MUST_BE_CONCRETE = 8359
ERROR_DS_INVALID_DMD = 8360
ERROR_DS_OBJ_GUID_EXISTS = 8361
ERROR_DS_NOT_ON_BACKLINK = 8362
ERROR_DS_NO_CROSSREF_FOR_NC = 8363
ERROR_DS_SHUTTING_DOWN = 8364
ERROR_DS_UNKNOWN_OPERATION = 8365
ERROR_DS_INVALID_ROLE_OWNER = 8366
ERROR_DS_COULDNT_CONTACT_FSMO = 8367
ERROR_DS_CROSS_NC_DN_RENAME = 8368
ERROR_DS_CANT_MOD_SYSTEM_ONLY = 8369
ERROR_DS_REPLICATOR_ONLY = 8370
ERROR_DS_OBJ_CLASS_NOT_DEFINED = 8371
ERROR_DS_OBJ_CLASS_NOT_SUBCLASS = 8372
ERROR_DS_NAME_REFERENCE_INVALID = 8373
ERROR_DS_CROSS_REF_EXISTS = 8374
ERROR_DS_CANT_DEL_MASTER_CROSSREF = 8375
ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD = 8376
ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX = 8377
ERROR_DS_DUP_RDN = 8378
ERROR_DS_DUP_OID = 8379
ERROR_DS_DUP_MAPI_ID = 8380
ERROR_DS_DUP_SCHEMA_ID_GUID = 8381
ERROR_DS_DUP_LDAP_DISPLAY_NAME = 8382
ERROR_DS_SEMANTIC_ATT_TEST = 8383
ERROR_DS_SYNTAX_MISMATCH = 8384
ERROR_DS_EXISTS_IN_MUST_HAVE = 8385
ERROR_DS_EXISTS_IN_MAY_HAVE = 8386
ERROR_DS_NONEXISTENT_MAY_HAVE = 8387
ERROR_DS_NONEXISTENT_MUST_HAVE = 8388
ERROR_DS_AUX_CLS_TEST_FAIL = 8389
ERROR_DS_NONEXISTENT_POSS_SUP = 8390
ERROR_DS_SUB_CLS_TEST_FAIL = 8391
ERROR_DS_BAD_RDN_ATT_ID_SYNTAX = 8392
ERROR_DS_EXISTS_IN_AUX_CLS = 8393
ERROR_DS_EXISTS_IN_SUB_CLS = 8394
ERROR_DS_EXISTS_IN_POSS_SUP = 8395
ERROR_DS_RECALCSCHEMA_FAILED = 8396
ERROR_DS_TREE_DELETE_NOT_FINISHED = 8397
ERROR_DS_CANT_DELETE = 8398
ERROR_DS_ATT_SCHEMA_REQ_ID = 8399
ERROR_DS_BAD_ATT_SCHEMA_SYNTAX = 8400
ERROR_DS_CANT_CACHE_ATT = 8401
ERROR_DS_CANT_CACHE_CLASS = 8402
ERROR_DS_CANT_REMOVE_ATT_CACHE = 8403
ERROR_DS_CANT_REMOVE_CLASS_CACHE = 8404
ERROR_DS_CANT_RETRIEVE_DN = 8405
ERROR_DS_MISSING_SUPREF = 8406
ERROR_DS_CANT_RETRIEVE_INSTANCE = 8407
ERROR_DS_CODE_INCONSISTENCY = 8408
ERROR_DS_DATABASE_ERROR = 8409
ERROR_DS_GOVERNSID_MISSING = 8410
ERROR_DS_MISSING_EXPECTED_ATT = 8411
ERROR_DS_NCNAME_MISSING_CR_REF = 8412
ERROR_DS_SECURITY_CHECKING_ERROR = 8413
ERROR_DS_SCHEMA_NOT_LOADED = 8414
ERROR_DS_SCHEMA_ALLOC_FAILED = 8415
ERROR_DS_ATT_SCHEMA_REQ_SYNTAX = 8416
ERROR_DS_GCVERIFY_ERROR = 8417
ERROR_DS_DRA_SCHEMA_MISMATCH = 8418
ERROR_DS_CANT_FIND_DSA_OBJ = 8419
ERROR_DS_CANT_FIND_EXPECTED_NC = 8420
ERROR_DS_CANT_FIND_NC_IN_CACHE = 8421
ERROR_DS_CANT_RETRIEVE_CHILD = 8422
ERROR_DS_SECURITY_ILLEGAL_MODIFY = 8423
ERROR_DS_CANT_REPLACE_HIDDEN_REC = 8424
ERROR_DS_BAD_HIERARCHY_FILE = 8425
ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED = 8426
ERROR_DS_CONFIG_PARAM_MISSING = 8427
ERROR_DS_COUNTING_AB_INDICES_FAILED = 8428
ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED = 8429
ERROR_DS_INTERNAL_FAILURE = 8430
ERROR_DS_UNKNOWN_ERROR = 8431
ERROR_DS_ROOT_REQUIRES_CLASS_TOP = 8432
ERROR_DS_REFUSING_FSMO_ROLES = 8433
ERROR_DS_MISSING_FSMO_SETTINGS = 8434
ERROR_DS_UNABLE_TO_SURRENDER_ROLES = 8435
ERROR_DS_DRA_GENERIC = 8436
ERROR_DS_DRA_INVALID_PARAMETER = 8437
ERROR_DS_DRA_BUSY = 8438
ERROR_DS_DRA_BAD_DN = 8439
ERROR_DS_DRA_BAD_NC = 8440
ERROR_DS_DRA_DN_EXISTS = 8441
ERROR_DS_DRA_INTERNAL_ERROR = 8442
ERROR_DS_DRA_INCONSISTENT_DIT = 8443
ERROR_DS_DRA_CONNECTION_FAILED = 8444
ERROR_DS_DRA_BAD_INSTANCE_TYPE = 8445
ERROR_DS_DRA_OUT_OF_MEM = 8446
ERROR_DS_DRA_MAIL_PROBLEM = 8447
ERROR_DS_DRA_REF_ALREADY_EXISTS = 8448
ERROR_DS_DRA_REF_NOT_FOUND = 8449
ERROR_DS_DRA_OBJ_IS_REP_SOURCE = 8450
ERROR_DS_DRA_DB_ERROR = 8451
ERROR_DS_DRA_NO_REPLICA = 8452
ERROR_DS_DRA_ACCESS_DENIED = 8453
ERROR_DS_DRA_NOT_SUPPORTED = 8454
ERROR_DS_DRA_RPC_CANCELLED = 8455
ERROR_DS_DRA_SOURCE_DISABLED = 8456
ERROR_DS_DRA_SINK_DISABLED = 8457
ERROR_DS_DRA_NAME_COLLISION = 8458
ERROR_DS_DRA_SOURCE_REINSTALLED = 8459
ERROR_DS_DRA_MISSING_PARENT = 8460
ERROR_DS_DRA_PREEMPTED = 8461
ERROR_DS_DRA_ABANDON_SYNC = 8462
ERROR_DS_DRA_SHUTDOWN = 8463
ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET = 8464
ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA = 8465
ERROR_DS_DRA_EXTN_CONNECTION_FAILED = 8466
ERROR_DS_INSTALL_SCHEMA_MISMATCH = 8467
ERROR_DS_DUP_LINK_ID = 8468
ERROR_DS_NAME_ERROR_RESOLVING = 8469
ERROR_DS_NAME_ERROR_NOT_FOUND = 8470
ERROR_DS_NAME_ERROR_NOT_UNIQUE = 8471
ERROR_DS_NAME_ERROR_NO_MAPPING = 8472
ERROR_DS_NAME_ERROR_DOMAIN_ONLY = 8473
ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 8474
ERROR_DS_CONSTRUCTED_ATT_MOD = 8475
ERROR_DS_WRONG_OM_OBJ_CLASS = 8476
ERROR_DS_DRA_REPL_PENDING = 8477
ERROR_DS_DS_REQUIRED = 8478
ERROR_DS_INVALID_LDAP_DISPLAY_NAME = 8479
ERROR_DS_NON_BASE_SEARCH = 8480
ERROR_DS_CANT_RETRIEVE_ATTS = 8481
ERROR_DS_BACKLINK_WITHOUT_LINK = 8482
ERROR_DS_EPOCH_MISMATCH = 8483
ERROR_DS_SRC_NAME_MISMATCH = 8484
ERROR_DS_SRC_AND_DST_NC_IDENTICAL = 8485
ERROR_DS_DST_NC_MISMATCH = 8486
ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC = 8487
ERROR_DS_SRC_GUID_MISMATCH = 8488
ERROR_DS_CANT_MOVE_DELETED_OBJECT = 8489
ERROR_DS_PDC_OPERATION_IN_PROGRESS = 8490
ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD = 8491
ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION = 8492
ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS = 8493
ERROR_DS_NC_MUST_HAVE_NC_PARENT = 8494
ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE = 8495
ERROR_DS_DST_DOMAIN_NOT_NATIVE = 8496
ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER = 8497
ERROR_DS_CANT_MOVE_ACCOUNT_GROUP = 8498
ERROR_DS_CANT_MOVE_RESOURCE_GROUP = 8499
ERROR_DS_INVALID_SEARCH_FLAG = 8500
ERROR_DS_NO_TREE_DELETE_ABOVE_NC = 8501
ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE = 8502
ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE = 8503
ERROR_DS_SAM_INIT_FAILURE = 8504
ERROR_DS_SENSITIVE_GROUP_VIOLATION = 8505
ERROR_DS_CANT_MOD_PRIMARYGROUPID = 8506
ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD = 8507
ERROR_DS_NONSAFE_SCHEMA_CHANGE = 8508
ERROR_DS_SCHEMA_UPDATE_DISALLOWED = 8509
ERROR_DS_CANT_CREATE_UNDER_SCHEMA = 8510
ERROR_DS_INSTALL_NO_SRC_SCH_VERSION = 8511
ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE = 8512
ERROR_DS_INVALID_GROUP_TYPE = 8513
ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN = 8514
ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN = 8515
ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER = 8516
ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER = 8517
ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER = 8518
ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER = 8519
ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER = 8520
ERROR_DS_HAVE_PRIMARY_MEMBERS = 8521
ERROR_DS_STRING_SD_CONVERSION_FAILED = 8522
ERROR_DS_NAMING_MASTER_GC = 8523
ERROR_DS_DNS_LOOKUP_FAILURE = 8524
ERROR_DS_COULDNT_UPDATE_SPNS = 8525
ERROR_DS_CANT_RETRIEVE_SD = 8526
ERROR_DS_KEY_NOT_UNIQUE = 8527
ERROR_DS_WRONG_LINKED_ATT_SYNTAX = 8528
ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD = 8529
ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY = 8530
ERROR_DS_CANT_START = 8531
ERROR_DS_INIT_FAILURE = 8532
ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION = 8533
ERROR_DS_SOURCE_DOMAIN_IN_FOREST = 8534
ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST = 8535
ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED = 8536
ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN = 8537
ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER = 8538
ERROR_DS_SRC_SID_EXISTS_IN_FOREST = 8539
ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH = 8540
ERROR_SAM_INIT_FAILURE = 8541
ERROR_DS_DRA_SCHEMA_INFO_SHIP = 8542
ERROR_DS_DRA_SCHEMA_CONFLICT = 8543
ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT = 8544
ERROR_DS_DRA_OBJ_NC_MISMATCH = 8545
ERROR_DS_NC_STILL_HAS_DSAS = 8546
ERROR_DS_GC_REQUIRED = 8547
ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY = 8548
ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS = 8549
ERROR_DS_CANT_ADD_TO_GC = 8550
ERROR_DS_NO_CHECKPOINT_WITH_PDC = 8551
ERROR_DS_SOURCE_AUDITING_NOT_ENABLED = 8552
ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC = 8553
ERROR_DS_INVALID_NAME_FOR_SPN = 8554
ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS = 8555
ERROR_DS_UNICODEPWD_NOT_IN_QUOTES = 8556
ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED = 8557
ERROR_DS_MUST_BE_RUN_ON_DST_DC = 8558
ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER = 8559
ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ = 8560
ERROR_DS_INIT_FAILURE_CONSOLE = 8561
ERROR_DS_SAM_INIT_FAILURE_CONSOLE = 8562
ERROR_DS_FOREST_VERSION_TOO_HIGH = 8563
ERROR_DS_DOMAIN_VERSION_TOO_HIGH = 8564
ERROR_DS_FOREST_VERSION_TOO_LOW = 8565
ERROR_DS_DOMAIN_VERSION_TOO_LOW = 8566
ERROR_DS_INCOMPATIBLE_VERSION = 8567
ERROR_DS_LOW_DSA_VERSION = 8568
ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN = 8569
ERROR_DS_NOT_SUPPORTED_SORT_ORDER = 8570
ERROR_DS_NAME_NOT_UNIQUE = 8571
ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4 = 8572
ERROR_DS_OUT_OF_VERSION_STORE = 8573
ERROR_DS_INCOMPATIBLE_CONTROLS_USED = 8574
ERROR_DS_NO_REF_DOMAIN = 8575
ERROR_DS_RESERVED_LINK_ID = 8576
ERROR_DS_LINK_ID_NOT_AVAILABLE = 8577
ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER = 8578
ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE = 8579
ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC = 8580
ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG = 8581
ERROR_DS_MODIFYDN_WRONG_GRANDPARENT = 8582
ERROR_DS_NAME_ERROR_TRUST_REFERRAL = 8583
ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER = 8584
ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD = 8585
ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2 = 8586
ERROR_DS_THREAD_LIMIT_EXCEEDED = 8587
ERROR_DS_NOT_CLOSEST = 8588
ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF = 8589
ERROR_DS_SINGLE_USER_MODE_FAILED = 8590
ERROR_DS_NTDSCRIPT_SYNTAX_ERROR = 8591
ERROR_DS_NTDSCRIPT_PROCESS_ERROR = 8592
ERROR_DS_DIFFERENT_REPL_EPOCHS = 8593
ERROR_DS_DRS_EXTENSIONS_CHANGED = 8594
ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR = 8595
ERROR_DS_NO_MSDS_INTID = 8596
ERROR_DS_DUP_MSDS_INTID = 8597
ERROR_DS_EXISTS_IN_RDNATTID = 8598
ERROR_DS_AUTHORIZATION_FAILED = 8599
ERROR_DS_INVALID_SCRIPT = 8600
ERROR_DS_REMOTE_CROSSREF_OP_FAILED = 8601
ERROR_DS_CROSS_REF_BUSY = 8602
ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN = 8603
ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC = 8604
ERROR_DS_DUPLICATE_ID_FOUND = 8605
ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT = 8606
ERROR_DS_GROUP_CONVERSION_ERROR = 8607
ERROR_DS_CANT_MOVE_APP_BASIC_GROUP = 8608
ERROR_DS_CANT_MOVE_APP_QUERY_GROUP = 8609
ERROR_DS_ROLE_NOT_VERIFIED = 8610
ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL = 8611
ERROR_DS_DOMAIN_RENAME_IN_PROGRESS = 8612
ERROR_DS_EXISTING_AD_CHILD_NC = 8613
ERROR_DS_REPL_LIFETIME_EXCEEDED = 8614
ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER = 8615
ERROR_DS_LDAP_SEND_QUEUE_FULL = 8616
ERROR_DS_DRA_OUT_SCHEDULE_WINDOW = 8617
ERROR_DS_POLICY_NOT_KNOWN = 8618
ERROR_NO_SITE_SETTINGS_OBJECT = 8619
ERROR_NO_SECRETS = 8620
ERROR_NO_WRITABLE_DC_FOUND = 8621
ERROR_DS_NO_SERVER_OBJECT = 8622
ERROR_DS_NO_NTDSA_OBJECT = 8623
ERROR_DS_NON_ASQ_SEARCH = 8624
ERROR_DS_AUDIT_FAILURE = 8625
ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE = 8626
ERROR_DS_INVALID_SEARCH_FLAG_TUPLE = 8627
ERROR_DS_HIERARCHY_TABLE_TOO_DEEP = 8628
ERROR_DS_DRA_CORRUPT_UTD_VECTOR = 8629
ERROR_DS_DRA_SECRETS_DENIED = 8630
ERROR_DS_RESERVED_MAPI_ID = 8631
ERROR_DS_MAPI_ID_NOT_AVAILABLE = 8632
ERROR_DS_DRA_MISSING_KRBTGT_SECRET = 8633
ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST = 8634
ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST = 8635
ERROR_INVALID_USER_PRINCIPAL_NAME = 8636
ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS = 8637
ERROR_DS_OID_NOT_FOUND = 8638
ERROR_DS_DRA_RECYCLED_TARGET = 8639
DNS_ERROR_RCODE_FORMAT_ERROR = 9001
DNS_ERROR_RCODE_SERVER_FAILURE = 9002
DNS_ERROR_RCODE_NAME_ERROR = 9003
DNS_ERROR_RCODE_NOT_IMPLEMENTED = 9004
DNS_ERROR_RCODE_REFUSED = 9005
DNS_ERROR_RCODE_YXDOMAIN = 9006
DNS_ERROR_RCODE_YXRRSET = 9007
DNS_ERROR_RCODE_NXRRSET = 9008
DNS_ERROR_RCODE_NOTAUTH = 9009
DNS_ERROR_RCODE_NOTZONE = 9010
DNS_ERROR_RCODE_BADSIG = 9016
DNS_ERROR_RCODE_BADKEY = 9017
DNS_ERROR_RCODE_BADTIME = 9018
DNS_ERROR_PACKET_FMT_BASE = 9500
DNS_INFO_NO_RECORDS = 9501
DNS_ERROR_BAD_PACKET = 9502
DNS_ERROR_NO_PACKET = 9503
DNS_ERROR_RCODE = 9504
DNS_ERROR_UNSECURE_PACKET = 9505
DNS_ERROR_GENERAL_API_BASE = 9550
DNS_ERROR_INVALID_TYPE = 9551
DNS_ERROR_INVALID_IP_ADDRESS = 9552
DNS_ERROR_INVALID_PROPERTY = 9553
DNS_ERROR_TRY_AGAIN_LATER = 9554
DNS_ERROR_NOT_UNIQUE = 9555
DNS_ERROR_NON_RFC_NAME = 9556
DNS_STATUS_FQDN = 9557
DNS_STATUS_DOTTED_NAME = 9558
DNS_STATUS_SINGLE_PART_NAME = 9559
DNS_ERROR_INVALID_NAME_CHAR = 9560
DNS_ERROR_NUMERIC_NAME = 9561
DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER = 9562
DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION = 9563
DNS_ERROR_CANNOT_FIND_ROOT_HINTS = 9564
DNS_ERROR_INCONSISTENT_ROOT_HINTS = 9565
DNS_ERROR_DWORD_VALUE_TOO_SMALL = 9566
DNS_ERROR_DWORD_VALUE_TOO_LARGE = 9567
DNS_ERROR_BACKGROUND_LOADING = 9568
DNS_ERROR_NOT_ALLOWED_ON_RODC = 9569
DNS_ERROR_NOT_ALLOWED_UNDER_DNAME = 9570
DNS_ERROR_DELEGATION_REQUIRED = 9571
DNS_ERROR_INVALID_POLICY_TABLE = 9572
DNS_ERROR_ZONE_BASE = 9600
DNS_ERROR_ZONE_DOES_NOT_EXIST = 9601
DNS_ERROR_NO_ZONE_INFO = 9602
DNS_ERROR_INVALID_ZONE_OPERATION = 9603
DNS_ERROR_ZONE_CONFIGURATION_ERROR = 9604
DNS_ERROR_ZONE_HAS_NO_SOA_RECORD = 9605
DNS_ERROR_ZONE_HAS_NO_NS_RECORDS = 9606
DNS_ERROR_ZONE_LOCKED = 9607
DNS_ERROR_ZONE_CREATION_FAILED = 9608
DNS_ERROR_ZONE_ALREADY_EXISTS = 9609
DNS_ERROR_AUTOZONE_ALREADY_EXISTS = 9610
DNS_ERROR_INVALID_ZONE_TYPE = 9611
DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP = 9612
DNS_ERROR_ZONE_NOT_SECONDARY = 9613
DNS_ERROR_NEED_SECONDARY_ADDRESSES = 9614
DNS_ERROR_WINS_INIT_FAILED = 9615
DNS_ERROR_NEED_WINS_SERVERS = 9616
DNS_ERROR_NBSTAT_INIT_FAILED = 9617
DNS_ERROR_SOA_DELETE_INVALID = 9618
DNS_ERROR_FORWARDER_ALREADY_EXISTS = 9619
DNS_ERROR_ZONE_REQUIRES_MASTER_IP = 9620
DNS_ERROR_ZONE_IS_SHUTDOWN = 9621
DNS_ERROR_DATAFILE_BASE = 9650
DNS_ERROR_PRIMARY_REQUIRES_DATAFILE = 9651
DNS_ERROR_INVALID_DATAFILE_NAME = 9652
DNS_ERROR_DATAFILE_OPEN_FAILURE = 9653
DNS_ERROR_FILE_WRITEBACK_FAILED = 9654
DNS_ERROR_DATAFILE_PARSING = 9655
DNS_ERROR_DATABASE_BASE = 9700
DNS_ERROR_RECORD_DOES_NOT_EXIST = 9701
DNS_ERROR_RECORD_FORMAT = 9702
DNS_ERROR_NODE_CREATION_FAILED = 9703
DNS_ERROR_UNKNOWN_RECORD_TYPE = 9704
DNS_ERROR_RECORD_TIMED_OUT = 9705
DNS_ERROR_NAME_NOT_IN_ZONE = 9706
DNS_ERROR_CNAME_LOOP = 9707
DNS_ERROR_NODE_IS_CNAME = 9708
DNS_ERROR_CNAME_COLLISION = 9709
DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT = 9710
DNS_ERROR_RECORD_ALREADY_EXISTS = 9711
DNS_ERROR_SECONDARY_DATA = 9712
DNS_ERROR_NO_CREATE_CACHE_DATA = 9713
DNS_ERROR_NAME_DOES_NOT_EXIST = 9714
DNS_WARNING_PTR_CREATE_FAILED = 9715
DNS_WARNING_DOMAIN_UNDELETED = 9716
DNS_ERROR_DS_UNAVAILABLE = 9717
DNS_ERROR_DS_ZONE_ALREADY_EXISTS = 9718
DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE = 9719
DNS_ERROR_NODE_IS_DNAME = 9720
DNS_ERROR_DNAME_COLLISION = 9721
DNS_ERROR_ALIAS_LOOP = 9722
DNS_ERROR_OPERATION_BASE = 9750
DNS_INFO_AXFR_COMPLETE = 9751
DNS_ERROR_AXFR = 9752
DNS_INFO_ADDED_LOCAL_WINS = 9753
DNS_ERROR_SECURE_BASE = 9800
DNS_STATUS_CONTINUE_NEEDED = 9801
DNS_ERROR_SETUP_BASE = 9850
DNS_ERROR_NO_TCPIP = 9851
DNS_ERROR_NO_DNS_SERVERS = 9852
DNS_ERROR_DP_BASE = 9900
DNS_ERROR_DP_DOES_NOT_EXIST = 9901
DNS_ERROR_DP_ALREADY_EXISTS = 9902
DNS_ERROR_DP_NOT_ENLISTED = 9903
DNS_ERROR_DP_ALREADY_ENLISTED = 9904
DNS_ERROR_DP_NOT_AVAILABLE = 9905
DNS_ERROR_DP_FSMO_ERROR = 9906
WSABASEERR = 10000
WSAEINTR = 10004
WSAEBADF = 10009
WSAEACCES = 10013
WSAEFAULT = 10014
WSAEINVAL = 10022
WSAEMFILE = 10024
WSAEWOULDBLOCK = 10035
WSAEINPROGRESS = 10036
WSAEALREADY = 10037
WSAENOTSOCK = 10038
WSAEDESTADDRREQ = 10039
WSAEMSGSIZE = 10040
WSAEPROTOTYPE = 10041
WSAENOPROTOOPT = 10042
WSAEPROTONOSUPPORT = 10043
WSAESOCKTNOSUPPORT = 10044
WSAEOPNOTSUPP = 10045
WSAEPFNOSUPPORT = 10046
WSAEAFNOSUPPORT = 10047
WSAEADDRINUSE = 10048
WSAEADDRNOTAVAIL = 10049
WSAENETDOWN = 10050
WSAENETUNREACH = 10051
WSAENETRESET = 10052
WSAECONNABORTED = 10053
WSAECONNRESET = 10054
WSAENOBUFS = 10055
WSAEISCONN = 10056
WSAENOTCONN = 10057
WSAESHUTDOWN = 10058
WSAETOOMANYREFS = 10059
WSAETIMEDOUT = 10060
WSAECONNREFUSED = 10061
WSAELOOP = 10062
WSAENAMETOOLONG = 10063
WSAEHOSTDOWN = 10064
WSAEHOSTUNREACH = 10065
WSAENOTEMPTY = 10066
WSAEPROCLIM = 10067
WSAEUSERS = 10068
WSAEDQUOT = 10069
WSAESTALE = 10070
WSAEREMOTE = 10071
WSASYSNOTREADY = 10091
WSAVERNOTSUPPORTED = 10092
WSANOTINITIALISED = 10093
WSAEDISCON = 10101
WSAENOMORE = 10102
WSAECANCELLED = 10103
WSAEINVALIDPROCTABLE = 10104
WSAEINVALIDPROVIDER = 10105
WSAEPROVIDERFAILEDINIT = 10106
WSASYSCALLFAILURE = 10107
WSASERVICE_NOT_FOUND = 10108
WSATYPE_NOT_FOUND = 10109
WSA_E_NO_MORE = 10110
WSA_E_CANCELLED = 10111
WSAEREFUSED = 10112
WSAHOST_NOT_FOUND = 11001
WSATRY_AGAIN = 11002
WSANO_RECOVERY = 11003
WSANO_DATA = 11004
WSA_QOS_RECEIVERS = 11005
WSA_QOS_SENDERS = 11006
WSA_QOS_NO_SENDERS = 11007
WSA_QOS_NO_RECEIVERS = 11008
WSA_QOS_REQUEST_CONFIRMED = 11009
WSA_QOS_ADMISSION_FAILURE = 11010
WSA_QOS_POLICY_FAILURE = 11011
WSA_QOS_BAD_STYLE = 11012
WSA_QOS_BAD_OBJECT = 11013
WSA_QOS_TRAFFIC_CTRL_ERROR = 11014
WSA_QOS_GENERIC_ERROR = 11015
WSA_QOS_ESERVICETYPE = 11016
WSA_QOS_EFLOWSPEC = 11017
WSA_QOS_EPROVSPECBUF = 11018
WSA_QOS_EFILTERSTYLE = 11019
WSA_QOS_EFILTERTYPE = 11020
WSA_QOS_EFILTERCOUNT = 11021
WSA_QOS_EOBJLENGTH = 11022
WSA_QOS_EFLOWCOUNT = 11023
WSA_QOS_EUNKOWNPSOBJ = 11024
WSA_QOS_EPOLICYOBJ = 11025
WSA_QOS_EFLOWDESC = 11026
WSA_QOS_EPSFLOWSPEC = 11027
WSA_QOS_EPSFILTERSPEC = 11028
WSA_QOS_ESDMODEOBJ = 11029
WSA_QOS_ESHAPERATEOBJ = 11030
WSA_QOS_RESERVED_PETYPE = 11031
WSA_SECURE_HOST_NOT_FOUND = 11032
WSA_IPSEC_NAME_POLICY_ERROR = 11033
ERROR_WINHTTP_OUT_OF_HANDLES = 12001
ERROR_WINHTTP_TIMEOUT = 12002
ERROR_WINHTTP_INTERNAL_ERROR = 12004
ERROR_WINHTTP_INVALID_URL = 12005
ERROR_WINHTTP_UNRECOGNIZED_SCHEME = 12006
ERROR_WINHTTP_NAME_NOT_RESOLVED = 12007
ERROR_WINHTTP_INVALID_OPTION = 12009
ERROR_WINHTTP_OPTION_NOT_SETTABLE = 12011
ERROR_WINHTTP_SHUTDOWN = 12012
ERROR_WINHTTP_LOGIN_FAILURE = 12015
ERROR_WINHTTP_OPERATION_CANCELLED = 12017
ERROR_WINHTTP_INCORRECT_HANDLE_TYPE = 12018
ERROR_WINHTTP_INCORRECT_HANDLE_STATE = 12019
ERROR_WINHTTP_CANNOT_CONNECT = 12029
ERROR_WINHTTP_CONNECTION_ERROR = 12030
ERROR_WINHTTP_RESEND_REQUEST = 12032
ERROR_WINHTTP_SECURE_CERT_DATE_INVALID = 12037
ERROR_WINHTTP_SECURE_CERT_CN_INVALID = 12038
ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED = 12044
ERROR_WINHTTP_SECURE_INVALID_CA = 12045
ERROR_WINHTTP_SECURE_CERT_REV_FAILED = 12057
ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN = 12100
ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND = 12101
ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND = 12102
ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN = 12103
ERROR_WINHTTP_HEADER_NOT_FOUND = 12150
ERROR_WINHTTP_INVALID_SERVER_RESPONSE = 12152
ERROR_WINHTTP_INVALID_HEADER = 12153
ERROR_WINHTTP_SECURE_CHANNEL_ERROR = 12157
ERROR_WINHTTP_INVALID_QUERY_REQUEST = 12154
ERROR_WINHTTP_HEADER_ALREADY_EXISTS = 12155
ERROR_WINHTTP_REDIRECT_FAILED = 12156
ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT = 12166
ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT = 12167
ERROR_WINHTTP_SECURE_INVALID_CERT = 12169
ERROR_WINHTTP_SECURE_CERT_REVOKED = 12170
ERROR_WINHTTP_NOT_INITIALIZED = 12172
ERROR_WINHTTP_SECURE_FAILURE = 12175
ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE = 12176
ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR = 12177
ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR = 12178
ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE = 12179
ERROR_WINHTTP_AUTODETECTION_FAILED = 12180
ERROR_WINHTTP_HEADER_COUNT_EXCEEDED = 12181
ERROR_WINHTTP_HEADER_SIZE_OVERFLOW = 12182
ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW = 12183
ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW = 12184
ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY = 12185
ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY = 12186
ERROR_IPSEC_QM_POLICY_EXISTS = 13000
ERROR_IPSEC_QM_POLICY_NOT_FOUND = 13001
ERROR_IPSEC_QM_POLICY_IN_USE = 13002
ERROR_IPSEC_MM_POLICY_EXISTS = 13003
ERROR_IPSEC_MM_POLICY_NOT_FOUND = 13004
ERROR_IPSEC_MM_POLICY_IN_USE = 13005
ERROR_IPSEC_MM_FILTER_EXISTS = 13006
ERROR_IPSEC_MM_FILTER_NOT_FOUND = 13007
ERROR_IPSEC_TRANSPORT_FILTER_EXISTS = 13008
ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND = 13009
ERROR_IPSEC_MM_AUTH_EXISTS = 13010
ERROR_IPSEC_MM_AUTH_NOT_FOUND = 13011
ERROR_IPSEC_MM_AUTH_IN_USE = 13012
ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND = 13013
ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND = 13014
ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND = 13015
ERROR_IPSEC_TUNNEL_FILTER_EXISTS = 13016
ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND = 13017
ERROR_IPSEC_MM_FILTER_PENDING_DELETION = 13018
ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION = 13019
ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION = 13020
ERROR_IPSEC_MM_POLICY_PENDING_DELETION = 13021
ERROR_IPSEC_MM_AUTH_PENDING_DELETION = 13022
ERROR_IPSEC_QM_POLICY_PENDING_DELETION = 13023
WARNING_IPSEC_MM_POLICY_PRUNED = 13024
WARNING_IPSEC_QM_POLICY_PRUNED = 13025
ERROR_IPSEC_IKE_NEG_STATUS_BEGIN = 13800
ERROR_IPSEC_IKE_AUTH_FAIL = 13801
ERROR_IPSEC_IKE_ATTRIB_FAIL = 13802
ERROR_IPSEC_IKE_NEGOTIATION_PENDING = 13803
ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR = 13804
ERROR_IPSEC_IKE_TIMED_OUT = 13805
ERROR_IPSEC_IKE_NO_CERT = 13806
ERROR_IPSEC_IKE_SA_DELETED = 13807
ERROR_IPSEC_IKE_SA_REAPED = 13808
ERROR_IPSEC_IKE_MM_ACQUIRE_DROP = 13809
ERROR_IPSEC_IKE_QM_ACQUIRE_DROP = 13810
ERROR_IPSEC_IKE_QUEUE_DROP_MM = 13811
ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM = 13812
ERROR_IPSEC_IKE_DROP_NO_RESPONSE = 13813
ERROR_IPSEC_IKE_MM_DELAY_DROP = 13814
ERROR_IPSEC_IKE_QM_DELAY_DROP = 13815
ERROR_IPSEC_IKE_ERROR = 13816
ERROR_IPSEC_IKE_CRL_FAILED = 13817
ERROR_IPSEC_IKE_INVALID_KEY_USAGE = 13818
ERROR_IPSEC_IKE_INVALID_CERT_TYPE = 13819
ERROR_IPSEC_IKE_NO_PRIVATE_KEY = 13820
ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY = 13821
ERROR_IPSEC_IKE_DH_FAIL = 13822
ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED = 13823
ERROR_IPSEC_IKE_INVALID_HEADER = 13824
ERROR_IPSEC_IKE_NO_POLICY = 13825
ERROR_IPSEC_IKE_INVALID_SIGNATURE = 13826
ERROR_IPSEC_IKE_KERBEROS_ERROR = 13827
ERROR_IPSEC_IKE_NO_PUBLIC_KEY = 13828
ERROR_IPSEC_IKE_PROCESS_ERR = 13829
ERROR_IPSEC_IKE_PROCESS_ERR_SA = 13830
ERROR_IPSEC_IKE_PROCESS_ERR_PROP = 13831
ERROR_IPSEC_IKE_PROCESS_ERR_TRANS = 13832
ERROR_IPSEC_IKE_PROCESS_ERR_KE = 13833
ERROR_IPSEC_IKE_PROCESS_ERR_ID = 13834
ERROR_IPSEC_IKE_PROCESS_ERR_CERT = 13835
ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ = 13836
ERROR_IPSEC_IKE_PROCESS_ERR_HASH = 13837
ERROR_IPSEC_IKE_PROCESS_ERR_SIG = 13838
ERROR_IPSEC_IKE_PROCESS_ERR_NONCE = 13839
ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY = 13840
ERROR_IPSEC_IKE_PROCESS_ERR_DELETE = 13841
ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR = 13842
ERROR_IPSEC_IKE_INVALID_PAYLOAD = 13843
ERROR_IPSEC_IKE_LOAD_SOFT_SA = 13844
ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN = 13845
ERROR_IPSEC_IKE_INVALID_COOKIE = 13846
ERROR_IPSEC_IKE_NO_PEER_CERT = 13847
ERROR_IPSEC_IKE_PEER_CRL_FAILED = 13848
ERROR_IPSEC_IKE_POLICY_CHANGE = 13849
ERROR_IPSEC_IKE_NO_MM_POLICY = 13850
ERROR_IPSEC_IKE_NOTCBPRIV = 13851
ERROR_IPSEC_IKE_SECLOADFAIL = 13852
ERROR_IPSEC_IKE_FAILSSPINIT = 13853
ERROR_IPSEC_IKE_FAILQUERYSSP = 13854
ERROR_IPSEC_IKE_SRVACQFAIL = 13855
ERROR_IPSEC_IKE_SRVQUERYCRED = 13856
ERROR_IPSEC_IKE_GETSPIFAIL = 13857
ERROR_IPSEC_IKE_INVALID_FILTER = 13858
ERROR_IPSEC_IKE_OUT_OF_MEMORY = 13859
ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED = 13860
ERROR_IPSEC_IKE_INVALID_POLICY = 13861
ERROR_IPSEC_IKE_UNKNOWN_DOI = 13862
ERROR_IPSEC_IKE_INVALID_SITUATION = 13863
ERROR_IPSEC_IKE_DH_FAILURE = 13864
ERROR_IPSEC_IKE_INVALID_GROUP = 13865
ERROR_IPSEC_IKE_ENCRYPT = 13866
ERROR_IPSEC_IKE_DECRYPT = 13867
ERROR_IPSEC_IKE_POLICY_MATCH = 13868
ERROR_IPSEC_IKE_UNSUPPORTED_ID = 13869
ERROR_IPSEC_IKE_INVALID_HASH = 13870
ERROR_IPSEC_IKE_INVALID_HASH_ALG = 13871
ERROR_IPSEC_IKE_INVALID_HASH_SIZE = 13872
ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG = 13873
ERROR_IPSEC_IKE_INVALID_AUTH_ALG = 13874
ERROR_IPSEC_IKE_INVALID_SIG = 13875
ERROR_IPSEC_IKE_LOAD_FAILED = 13876
ERROR_IPSEC_IKE_RPC_DELETE = 13877
ERROR_IPSEC_IKE_BENIGN_REINIT = 13878
ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY = 13879
ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION = 13880
ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN = 13881
ERROR_IPSEC_IKE_MM_LIMIT = 13882
ERROR_IPSEC_IKE_NEGOTIATION_DISABLED = 13883
ERROR_IPSEC_IKE_QM_LIMIT = 13884
ERROR_IPSEC_IKE_MM_EXPIRED = 13885
ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID = 13886
ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH = 13887
ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID = 13888
ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD = 13889
ERROR_IPSEC_IKE_DOS_COOKIE_SENT = 13890
ERROR_IPSEC_IKE_SHUTTING_DOWN = 13891
ERROR_IPSEC_IKE_CGA_AUTH_FAILED = 13892
ERROR_IPSEC_IKE_PROCESS_ERR_NATOA = 13893
ERROR_IPSEC_IKE_INVALID_MM_FOR_QM = 13894
ERROR_IPSEC_IKE_QM_EXPIRED = 13895
ERROR_IPSEC_IKE_TOO_MANY_FILTERS = 13896
ERROR_IPSEC_IKE_NEG_STATUS_END = 13897
ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL = 13898
ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE = 13899
ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING = 13900
ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING = 13901
ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS = 13902
ERROR_IPSEC_IKE_RATELIMIT_DROP = 13903
ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE = 13904
ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE = 13905
ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE = 13906
ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY = 13907
ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE = 13908
ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END = 13909
ERROR_IPSEC_BAD_SPI = 13910
ERROR_IPSEC_SA_LIFETIME_EXPIRED = 13911
ERROR_IPSEC_WRONG_SA = 13912
ERROR_IPSEC_REPLAY_CHECK_FAILED = 13913
ERROR_IPSEC_INVALID_PACKET = 13914
ERROR_IPSEC_INTEGRITY_CHECK_FAILED = 13915
ERROR_IPSEC_CLEAR_TEXT_DROP = 13916
ERROR_IPSEC_AUTH_FIREWALL_DROP = 13917
ERROR_IPSEC_THROTTLE_DROP = 13918
ERROR_IPSEC_DOSP_BLOCK = 13925
ERROR_IPSEC_DOSP_RECEIVED_MULTICAST = 13926
ERROR_IPSEC_DOSP_INVALID_PACKET = 13927
ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED = 13928
ERROR_IPSEC_DOSP_MAX_ENTRIES = 13929
ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED = 13930
ERROR_IPSEC_DOSP_NOT_INSTALLED = 13931
ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES = 13932
ERROR_SXS_SECTION_NOT_FOUND = 14000
ERROR_SXS_CANT_GEN_ACTCTX = 14001
ERROR_SXS_INVALID_ACTCTXDATA_FORMAT = 14002
ERROR_SXS_ASSEMBLY_NOT_FOUND = 14003
ERROR_SXS_MANIFEST_FORMAT_ERROR = 14004
ERROR_SXS_MANIFEST_PARSE_ERROR = 14005
ERROR_SXS_ACTIVATION_CONTEXT_DISABLED = 14006
ERROR_SXS_KEY_NOT_FOUND = 14007
ERROR_SXS_VERSION_CONFLICT = 14008
ERROR_SXS_WRONG_SECTION_TYPE = 14009
ERROR_SXS_THREAD_QUERIES_DISABLED = 14010
ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011
ERROR_SXS_UNKNOWN_ENCODING_GROUP = 14012
ERROR_SXS_UNKNOWN_ENCODING = 14013
ERROR_SXS_INVALID_XML_NAMESPACE_URI = 14014
ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14015
ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED = 14016
ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE = 14017
ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE = 14018
ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE = 14019
ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT = 14020
ERROR_SXS_DUPLICATE_DLL_NAME = 14021
ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME = 14022
ERROR_SXS_DUPLICATE_CLSID = 14023
ERROR_SXS_DUPLICATE_IID = 14024
ERROR_SXS_DUPLICATE_TLBID = 14025
ERROR_SXS_DUPLICATE_PROGID = 14026
ERROR_SXS_DUPLICATE_ASSEMBLY_NAME = 14027
ERROR_SXS_FILE_HASH_MISMATCH = 14028
ERROR_SXS_POLICY_PARSE_ERROR = 14029
ERROR_SXS_XML_E_MISSINGQUOTE = 14030
ERROR_SXS_XML_E_COMMENTSYNTAX = 14031
ERROR_SXS_XML_E_BADSTARTNAMECHAR = 14032
ERROR_SXS_XML_E_BADNAMECHAR = 14033
ERROR_SXS_XML_E_BADCHARINSTRING = 14034
ERROR_SXS_XML_E_XMLDECLSYNTAX = 14035
ERROR_SXS_XML_E_BADCHARDATA = 14036
ERROR_SXS_XML_E_MISSINGWHITESPACE = 14037
ERROR_SXS_XML_E_EXPECTINGTAGEND = 14038
ERROR_SXS_XML_E_MISSINGSEMICOLON = 14039
ERROR_SXS_XML_E_UNBALANCEDPAREN = 14040
ERROR_SXS_XML_E_INTERNALERROR = 14041
ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE = 14042
ERROR_SXS_XML_E_INCOMPLETE_ENCODING = 14043
ERROR_SXS_XML_E_MISSING_PAREN = 14044
ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE = 14045
ERROR_SXS_XML_E_MULTIPLE_COLONS = 14046
ERROR_SXS_XML_E_INVALID_DECIMAL = 14047
ERROR_SXS_XML_E_INVALID_HEXIDECIMAL = 14048
ERROR_SXS_XML_E_INVALID_UNICODE = 14049
ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK = 14050
ERROR_SXS_XML_E_UNEXPECTEDENDTAG = 14051
ERROR_SXS_XML_E_UNCLOSEDTAG = 14052
ERROR_SXS_XML_E_DUPLICATEATTRIBUTE = 14053
ERROR_SXS_XML_E_MULTIPLEROOTS = 14054
ERROR_SXS_XML_E_INVALIDATROOTLEVEL = 14055
ERROR_SXS_XML_E_BADXMLDECL = 14056
ERROR_SXS_XML_E_MISSINGROOT = 14057
ERROR_SXS_XML_E_UNEXPECTEDEOF = 14058
ERROR_SXS_XML_E_BADPEREFINSUBSET = 14059
ERROR_SXS_XML_E_UNCLOSEDSTARTTAG = 14060
ERROR_SXS_XML_E_UNCLOSEDENDTAG = 14061
ERROR_SXS_XML_E_UNCLOSEDSTRING = 14062
ERROR_SXS_XML_E_UNCLOSEDCOMMENT = 14063
ERROR_SXS_XML_E_UNCLOSEDDECL = 14064
ERROR_SXS_XML_E_UNCLOSEDCDATA = 14065
ERROR_SXS_XML_E_RESERVEDNAMESPACE = 14066
ERROR_SXS_XML_E_INVALIDENCODING = 14067
ERROR_SXS_XML_E_INVALIDSWITCH = 14068
ERROR_SXS_XML_E_BADXMLCASE = 14069
ERROR_SXS_XML_E_INVALID_STANDALONE = 14070
ERROR_SXS_XML_E_UNEXPECTED_STANDALONE = 14071
ERROR_SXS_XML_E_INVALID_VERSION = 14072
ERROR_SXS_XML_E_MISSINGEQUALS = 14073
ERROR_SXS_PROTECTION_RECOVERY_FAILED = 14074
ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT = 14075
ERROR_SXS_PROTECTION_CATALOG_NOT_VALID = 14076
ERROR_SXS_UNTRANSLATABLE_HRESULT = 14077
ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING = 14078
ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE = 14079
ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME = 14080
ERROR_SXS_ASSEMBLY_MISSING = 14081
ERROR_SXS_CORRUPT_ACTIVATION_STACK = 14082
ERROR_SXS_CORRUPTION = 14083
ERROR_SXS_EARLY_DEACTIVATION = 14084
ERROR_SXS_INVALID_DEACTIVATION = 14085
ERROR_SXS_MULTIPLE_DEACTIVATION = 14086
ERROR_SXS_PROCESS_TERMINATION_REQUESTED = 14087
ERROR_SXS_RELEASE_ACTIVATION_CONTEXT = 14088
ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY = 14089
ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE = 14090
ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME = 14091
ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE = 14092
ERROR_SXS_IDENTITY_PARSE_ERROR = 14093
ERROR_MALFORMED_SUBSTITUTION_STRING = 14094
ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN = 14095
ERROR_UNMAPPED_SUBSTITUTION_STRING = 14096
ERROR_SXS_ASSEMBLY_NOT_LOCKED = 14097
ERROR_SXS_COMPONENT_STORE_CORRUPT = 14098
ERROR_ADVANCED_INSTALLER_FAILED = 14099
ERROR_XML_ENCODING_MISMATCH = 14100
ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT = 14101
ERROR_SXS_IDENTITIES_DIFFERENT = 14102
ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT = 14103
ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY = 14104
ERROR_SXS_MANIFEST_TOO_BIG = 14105
ERROR_SXS_SETTING_NOT_REGISTERED = 14106
ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE = 14107
ERROR_SMI_PRIMITIVE_INSTALLER_FAILED = 14108
ERROR_GENERIC_COMMAND_FAILED = 14109
ERROR_SXS_FILE_HASH_MISSING = 14110
ERROR_EVT_INVALID_CHANNEL_PATH = 15000
ERROR_EVT_INVALID_QUERY = 15001
ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND = 15002
ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND = 15003
ERROR_EVT_INVALID_PUBLISHER_NAME = 15004
ERROR_EVT_INVALID_EVENT_DATA = 15005
ERROR_EVT_CHANNEL_NOT_FOUND = 15007
ERROR_EVT_MALFORMED_XML_TEXT = 15008
ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL = 15009
ERROR_EVT_CONFIGURATION_ERROR = 15010
ERROR_EVT_QUERY_RESULT_STALE = 15011
ERROR_EVT_QUERY_RESULT_INVALID_POSITION = 15012
ERROR_EVT_NON_VALIDATING_MSXML = 15013
ERROR_EVT_FILTER_ALREADYSCOPED = 15014
ERROR_EVT_FILTER_NOTELTSET = 15015
ERROR_EVT_FILTER_INVARG = 15016
ERROR_EVT_FILTER_INVTEST = 15017
ERROR_EVT_FILTER_INVTYPE = 15018
ERROR_EVT_FILTER_PARSEERR = 15019
ERROR_EVT_FILTER_UNSUPPORTEDOP = 15020
ERROR_EVT_FILTER_UNEXPECTEDTOKEN = 15021
ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL = 15022
ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE = 15023
ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE = 15024
ERROR_EVT_CHANNEL_CANNOT_ACTIVATE = 15025
ERROR_EVT_FILTER_TOO_COMPLEX = 15026
ERROR_EVT_MESSAGE_NOT_FOUND = 15027
ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028
ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029
ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030
ERROR_EVT_MAX_INSERTS_REACHED = 15031
ERROR_EVT_EVENT_DEFINITION_NOT_FOUND = 15032
ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033
ERROR_EVT_VERSION_TOO_OLD = 15034
ERROR_EVT_VERSION_TOO_NEW = 15035
ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY = 15036
ERROR_EVT_PUBLISHER_DISABLED = 15037
ERROR_EVT_FILTER_OUT_OF_RANGE = 15038
ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE = 15080
ERROR_EC_LOG_DISABLED = 15081
ERROR_EC_CIRCULAR_FORWARDING = 15082
ERROR_EC_CREDSTORE_FULL = 15083
ERROR_EC_CRED_NOT_FOUND = 15084
ERROR_EC_NO_ACTIVE_CHANNEL = 15085
ERROR_MUI_FILE_NOT_FOUND = 15100
ERROR_MUI_INVALID_FILE = 15101
ERROR_MUI_INVALID_RC_CONFIG = 15102
ERROR_MUI_INVALID_LOCALE_NAME = 15103
ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME = 15104
ERROR_MUI_FILE_NOT_LOADED = 15105
ERROR_RESOURCE_ENUM_USER_STOP = 15106
ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED = 15107
ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME = 15108
ERROR_MCA_INVALID_CAPABILITIES_STRING = 15200
ERROR_MCA_INVALID_VCP_VERSION = 15201
ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION = 15202
ERROR_MCA_MCCS_VERSION_MISMATCH = 15203
ERROR_MCA_UNSUPPORTED_MCCS_VERSION = 15204
ERROR_MCA_INTERNAL_ERROR = 15205
ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED = 15206
ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE = 15207
ERROR_AMBIGUOUS_SYSTEM_DEVICE = 15250
ERROR_SYSTEM_DEVICE_NOT_FOUND = 15299
ERROR_HASH_NOT_SUPPORTED = 15300
ERROR_HASH_NOT_PRESENT = 15301
ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED = 15321
ERROR_GPIO_CLIENT_INFORMATION_INVALID = 15322
ERROR_GPIO_VERSION_NOT_SUPPORTED = 15323
ERROR_GPIO_INVALID_REGISTRATION_PACKET = 15324
ERROR_GPIO_OPERATION_DENIED = 15325
ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE = 15326
ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED = 15327
ERROR_CANNOT_SWITCH_RUNLEVEL = 15400
ERROR_INVALID_RUNLEVEL_SETTING = 15401
ERROR_RUNLEVEL_SWITCH_TIMEOUT = 15402
ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT = 15403
ERROR_RUNLEVEL_SWITCH_IN_PROGRESS = 15404
ERROR_SERVICES_FAILED_AUTOSTART = 15405
ERROR_COM_TASK_STOP_PENDING = 15501
ERROR_INSTALL_OPEN_PACKAGE_FAILED = 15600
ERROR_INSTALL_PACKAGE_NOT_FOUND = 15601
ERROR_INSTALL_INVALID_PACKAGE = 15602
ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED = 15603
ERROR_INSTALL_OUT_OF_DISK_SPACE = 15604
ERROR_INSTALL_NETWORK_FAILURE = 15605
ERROR_INSTALL_REGISTRATION_FAILURE = 15606
ERROR_INSTALL_DEREGISTRATION_FAILURE = 15607
ERROR_INSTALL_CANCEL = 15608
ERROR_INSTALL_FAILED = 15609
ERROR_REMOVE_FAILED = 15610
ERROR_PACKAGE_ALREADY_EXISTS = 15611
ERROR_NEEDS_REMEDIATION = 15612
ERROR_INSTALL_PREREQUISITE_FAILED = 15613
ERROR_PACKAGE_REPOSITORY_CORRUPTED = 15614
ERROR_INSTALL_POLICY_FAILURE = 15615
ERROR_PACKAGE_UPDATING = 15616
ERROR_DEPLOYMENT_BLOCKED_BY_POLICY = 15617
ERROR_PACKAGES_IN_USE = 15618
ERROR_RECOVERY_FILE_CORRUPT = 15619
ERROR_INVALID_STAGED_SIGNATURE = 15620
ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED = 15621
ERROR_INSTALL_PACKAGE_DOWNGRADE = 15622
ERROR_SYSTEM_NEEDS_REMEDIATION = 15623
ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN = 15624
ERROR_RESILIENCY_FILE_CORRUPT = 15625
ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING = 15626
APPMODEL_ERROR_NO_PACKAGE = 15700
APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT = 15701
APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT = 15702
APPMODEL_ERROR_NO_APPLICATION = 15703
ERROR_STATE_LOAD_STORE_FAILED = 15800
ERROR_STATE_GET_VERSION_FAILED = 15801
ERROR_STATE_SET_VERSION_FAILED = 15802
ERROR_STATE_STRUCTURED_RESET_FAILED = 15803
ERROR_STATE_OPEN_CONTAINER_FAILED = 15804
ERROR_STATE_CREATE_CONTAINER_FAILED = 15805
ERROR_STATE_DELETE_CONTAINER_FAILED = 15806
ERROR_STATE_READ_SETTING_FAILED = 15807
ERROR_STATE_WRITE_SETTING_FAILED = 15808
ERROR_STATE_DELETE_SETTING_FAILED = 15809
ERROR_STATE_QUERY_SETTING_FAILED = 15810
ERROR_STATE_READ_COMPOSITE_SETTING_FAILED = 15811
ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED = 15812
ERROR_STATE_ENUMERATE_CONTAINER_FAILED = 15813
ERROR_STATE_ENUMERATE_SETTINGS_FAILED = 15814
ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED = 15815
ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED = 15816
ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED = 15817
ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED = 15818
ERROR_API_UNAVAILABLE = 15841
STORE_ERROR_UNLICENSED = 15861
STORE_ERROR_UNLICENSED_USER = 15862
ERROR_DHCP_REGISTRY_INIT_FAILED = 0x00004E20
ERROR_DHCP_DATABASE_INIT_FAILED = 0x00004E21
ERROR_DHCP_RPC_INIT_FAILED = 0x00004E22
ERROR_DHCP_NETWORK_INIT_FAILED = 0x00004E23
ERROR_DHCP_SUBNET_EXITS = 0x00004E24
ERROR_DHCP_SUBNET_NOT_PRESENT = 0x00004E25
ERROR_DHCP_PRIMARY_NOT_FOUND = 0x00004E26
ERROR_DHCP_ELEMENT_CANT_REMOVE = 0x00004E27
ERROR_DHCP_OPTION_EXITS = 0x00004E29
ERROR_DHCP_OPTION_NOT_PRESENT = 0x00004E2A
ERROR_DHCP_ADDRESS_NOT_AVAILABLE = 0x00004E2B
ERROR_DHCP_RANGE_FULL = 0x00004E2C
ERROR_DHCP_JET_ERROR = 0x00004E2D
ERROR_DHCP_CLIENT_EXISTS = 0x00004E2E
ERROR_DHCP_INVALID_DHCP_MESSAGE = 0x00004E2F
ERROR_DHCP_INVALID_DHCP_CLIENT = 0x00004E30
ERROR_DHCP_SERVICE_PAUSED = 0x00004E31
ERROR_DHCP_NOT_RESERVED_CLIENT = 0x00004E32
ERROR_DHCP_RESERVED_CLIENT = 0x00004E33
ERROR_DHCP_RANGE_TOO_SMALL = 0x00004E34
ERROR_DHCP_IPRANGE_EXITS = 0x00004E35
ERROR_DHCP_RESERVEDIP_EXITS = 0x00004E36
ERROR_DHCP_INVALID_RANGE = 0x00004E37
ERROR_DHCP_RANGE_EXTENDED = 0x00004E38
ERROR_EXTEND_TOO_SMALL = 0x00004E39
WARNING_EXTENDED_LESS = 0x00004E3A
ERROR_DHCP_JET_CONV_REQUIRED = 0x00004E3B
ERROR_SERVER_INVALID_BOOT_FILE_TABLE = 0x00004E3C
ERROR_SERVER_UNKNOWN_BOOT_FILE_NAME = 0x00004E3D
ERROR_DHCP_SUPER_SCOPE_NAME_TOO_LONG = 0x00004E3E
ERROR_DHCP_IP_ADDRESS_IN_USE = 0x00004E40
ERROR_DHCP_LOG_FILE_PATH_TOO_LONG = 0x00004E41
ERROR_DHCP_UNSUPPORTED_CLIENT = 0x00004E42
ERROR_DHCP_JET97_CONV_REQUIRED = 0x00004E44
ERROR_DHCP_ROGUE_INIT_FAILED = 0x00004E45
ERROR_DHCP_ROGUE_SAMSHUTDOWN = 0x00004E46
ERROR_DHCP_ROGUE_NOT_AUTHORIZED = 0x00004E47
ERROR_DHCP_ROGUE_DS_UNREACHABLE = 0x00004E48
ERROR_DHCP_ROGUE_DS_CONFLICT = 0x00004E49
ERROR_DHCP_ROGUE_NOT_OUR_ENTERPRISE = 0x00004E4A
ERROR_DHCP_ROGUE_STANDALONE_IN_DS = 0x00004E4B
ERROR_DHCP_CLASS_NOT_FOUND = 0x00004E4C
ERROR_DHCP_CLASS_ALREADY_EXISTS = 0x00004E4D
ERROR_DHCP_SCOPE_NAME_TOO_LONG = 0x00004E4E
ERROR_DHCP_DEFAULT_SCOPE_EXITS = 0x00004E4F
ERROR_DHCP_CANT_CHANGE_ATTRIBUTE = 0x00004E50
ERROR_DHCP_IPRANGE_CONV_ILLEGAL = 0x00004E51
ERROR_DHCP_NETWORK_CHANGED = 0x00004E52
ERROR_DHCP_CANNOT_MODIFY_BINDINGS = 0x00004E53
ERROR_DHCP_SUBNET_EXISTS = 0x00004E54
ERROR_DHCP_MSCOPE_EXISTS = 0x00004E55
ERROR_MSCOPE_RANGE_TOO_SMALL = 0x00004E56
ERROR_DHCP_EXEMPTION_EXISTS = 0x00004E57
ERROR_DHCP_EXEMPTION_NOT_PRESENT = 0x00004E58
ERROR_DHCP_INVALID_PARAMETER_OPTION32 = 0x00004E59
ERROR_DDS_NO_DS_AVAILABLE = 0x00004E66
ERROR_DDS_NO_DHCP_ROOT = 0x00004E67
ERROR_DDS_UNEXPECTED_ERROR = 0x00004E68
ERROR_DDS_TOO_MANY_ERRORS = 0x00004E69
ERROR_DDS_DHCP_SERVER_NOT_FOUND = 0x00004E6A
ERROR_DDS_OPTION_ALREADY_EXISTS = 0x00004E6B
ERROR_DDS_OPTION_DOES_NOT_EXIST = 0x00004E6C
ERROR_DDS_CLASS_EXISTS = 0x00004E6D
ERROR_DDS_CLASS_DOES_NOT_EXIST = 0x00004E6E
ERROR_DDS_SERVER_ALREADY_EXISTS = 0x00004E6F
ERROR_DDS_SERVER_DOES_NOT_EXIST = 0x00004E70
ERROR_DDS_SERVER_ADDRESS_MISMATCH = 0x00004E71
ERROR_DDS_SUBNET_EXISTS = 0x00004E72
ERROR_DDS_SUBNET_HAS_DIFF_SSCOPE = 0x00004E73
ERROR_DDS_SUBNET_NOT_PRESENT = 0x00004E74
ERROR_DDS_RESERVATION_NOT_PRESENT = 0x00004E75
ERROR_DDS_RESERVATION_CONFLICT = 0x00004E76
ERROR_DDS_POSSIBLE_RANGE_CONFLICT = 0x00004E77
ERROR_DDS_RANGE_DOES_NOT_EXIST = 0x00004E78
ERROR_DHCP_DELETE_BUILTIN_CLASS = 0x00004E79
ERROR_DHCP_INVALID_SUBNET_PREFIX = 0x00004E7B
ERROR_DHCP_INVALID_DELAY = 0x00004E7C
ERROR_DHCP_LINKLAYER_ADDRESS_EXISTS = 0x00004E7D
ERROR_DHCP_LINKLAYER_ADDRESS_RESERVATION_EXISTS = 0x00004E7E
ERROR_DHCP_LINKLAYER_ADDRESS_DOES_NOT_EXIST = 0x00004E7F
ERROR_DHCP_HARDWARE_ADDRESS_TYPE_ALREADY_EXEMPT = 0x00004E85
ERROR_DHCP_UNDEFINED_HARDWARE_ADDRESS_TYPE = 0x00004E86
ERROR_DHCP_OPTION_TYPE_MISMATCH = 0x00004E87
ERROR_DHCP_POLICY_BAD_PARENT_EXPR = 0x00004E88
ERROR_DHCP_POLICY_EXISTS = 0x00004E89
ERROR_DHCP_POLICY_RANGE_EXISTS = 0x00004E8A
ERROR_DHCP_POLICY_RANGE_BAD = 0x00004E8B
ERROR_DHCP_RANGE_INVALID_IN_SERVER_POLICY = 0x00004E8C
ERROR_DHCP_INVALID_POLICY_EXPRESSION = 0x00004E8D
ERROR_DHCP_INVALID_PROCESSING_ORDER = 0x00004E8E
ERROR_DHCP_POLICY_NOT_FOUND = 0x00004E8F
ERROR_SCOPE_RANGE_POLICY_RANGE_CONFLICT = 0x00004E90
ERROR_DHCP_FO_SCOPE_ALREADY_IN_RELATIONSHIP = 0x00004E91
ERROR_DHCP_FO_RELATIONSHIP_EXISTS = 0x00004E92
ERROR_DHCP_FO_RELATIONSHIP_DOES_NOT_EXIST = 0x00004E93
ERROR_DHCP_FO_SCOPE_NOT_IN_RELATIONSHIP = 0x00004E94
ERROR_DHCP_FO_RELATION_IS_SECONDARY = 0x00004E95
ERROR_DHCP_FO_NOT_SUPPORTED = 0x00004E96
ERROR_DHCP_FO_TIME_OUT_OF_SYNC = 0x00004E97
ERROR_DHCP_FO_STATE_NOT_NORMAL = 0x00004E98
ERROR_DHCP_NO_ADMIN_PERMISSION = 0x00004E99
ERROR_DHCP_SERVER_NOT_REACHABLE = 0x00004E9A
ERROR_DHCP_SERVER_NOT_RUNNING = 0x00004E9B
ERROR_DHCP_SERVER_NAME_NOT_RESOLVED = 0x00004E9C
ERROR_DHCP_FO_RELATIONSHIP_NAME_TOO_LONG = 0x00004E9D
ERROR_DHCP_REACHED_END_OF_SELECTION = 0x00004E9E
ERROR_DHCP_FO_ADDSCOPE_LEASES_NOT_SYNCED = 0x00004E9F
ERROR_DHCP_FO_MAX_RELATIONSHIPS = 0x00004EA0
ERROR_DHCP_FO_IPRANGE_TYPE_CONV_ILLEGAL = 0x00004EA1
ERROR_DHCP_FO_MAX_ADD_SCOPES = 0x00004EA2
ERROR_DHCP_FO_BOOT_NOT_SUPPORTED = 0x00004EA3
ERROR_DHCP_FO_RANGE_PART_OF_REL = 0x00004EA4
ERROR_DHCP_FO_SCOPE_SYNC_IN_PROGRESS = 0x00004EA5
) | ERROR_SERVICE_LOGON_FAILED = 1069
ERROR_SERVICE_START_HANG = 1070 |
delete_range.go | // Copyright 2019 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package sql
import (
"bytes"
"context"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/util/log"
)
// deleteRangeNode implements DELETE on a primary index satisfying certain
// conditions that permit the direct use of the DeleteRange kv operation,
// instead of many point deletes.
type deleteRangeNode struct {
// interleavedFastPath is true if we can take the fast path despite operating
// on an interleaved table.
interleavedFastPath bool
// spans are the spans to delete.
spans roachpb.Spans
// desc is the table descriptor the delete is operating on.
desc *sqlbase.ImmutableTableDescriptor
// tableWriter orchestrates the deletion operation itself.
tableWriter tableWriterBase
// fetcher is around to decode the returned keys from the DeleteRange, so that
// we can count the number of rows deleted.
fetcher row.Fetcher
// rowCount will be set to the count of rows deleted.
rowCount int
}
var _ autoCommitNode = &deleteRangeNode{}
var _ planNode = &deleteRangeNode{}
var _ planNodeFastPath = &deleteRangeNode{}
var _ batchedPlanNode = &deleteRangeNode{}
// canDeleteFast determines if the deletion of `rows` can be done
// without actually scanning them.
// This should be called after plan simplification for optimal results.
//
// This logic should be kept in sync with exec.Builder.canUseDeleteRange.
// TODO(andyk): Remove when the heuristic planner code is removed.
func maybeCreateDeleteFastNode(
ctx context.Context,
source planNode,
desc *ImmutableTableDescriptor,
fastPathInterleaved bool,
rowsNeeded bool,
) (*deleteRangeNode, bool) {
// Check that there are no secondary indexes, interleaving, FK
// references checks, etc., ie. there is no extra work to be done
// per row deleted.
if !fastPathDeleteAvailable(ctx, desc) && !fastPathInterleaved {
return nil, false
}
// If the rows are needed (a RETURNING clause), we can't skip them.
if rowsNeeded |
// Check whether the source plan is "simple": that it contains no remaining
// filtering, limiting, sorting, etc. Note that this logic must be kept in
// sync with the logic for setting scanNode.isDeleteSource (see doExpandPlan.)
// TODO(dt): We could probably be smarter when presented with an
// index-join, but this goes away anyway once we push-down more of
// SQL.
maybeScan := source
if sel, ok := maybeScan.(*renderNode); ok {
// There may be a projection to drop/rename some columns which the
// optimizations did not remove at this point. We just ignore that
// projection for the purpose of this check.
maybeScan = sel.source.plan
}
scan, ok := maybeScan.(*scanNode)
if !ok {
// Not simple enough. Bail.
return nil, false
}
// A scan ought to be simple enough, except when it's not: a scan
// may have a remaining filter. We can't be fast over that.
if scan.filter != nil {
if log.V(2) {
log.Infof(ctx, "delete forced to scan: values required for filter (%s)", scan.filter)
}
return nil, false
}
if scan.hardLimit != 0 {
if log.V(2) {
log.Infof(ctx, "delete forced to scan: scan has limit %d", scan.hardLimit)
}
return nil, false
}
return &deleteRangeNode{
interleavedFastPath: fastPathInterleaved,
spans: scan.spans,
desc: desc,
}, true
}
// BatchedNext implements the batchedPlanNode interface.
func (d *deleteRangeNode) BatchedNext(params runParams) (bool, error) {
return false, nil
}
// BatchedCount implements the batchedPlanNode interface.
func (d *deleteRangeNode) BatchedCount() int {
return d.rowCount
}
// BatchedValues implements the batchedPlanNode interface.
func (d *deleteRangeNode) BatchedValues(rowIdx int) tree.Datums {
panic("invalid")
}
// FastPathResults implements the planNodeFastPath interface.
func (d *deleteRangeNode) FastPathResults() (int, bool) {
return d.rowCount, true
}
// startExec implements the planNode interface.
func (d *deleteRangeNode) startExec(params runParams) error {
if err := params.p.cancelChecker.Check(); err != nil {
return err
}
if err := params.p.maybeSetSystemConfig(d.desc.GetID()); err != nil {
return err
}
if err := d.fetcher.Init(
false, false, false, ¶ms.p.alloc,
row.FetcherTableArgs{
Desc: d.desc,
Index: &d.desc.PrimaryIndex,
}); err != nil {
return err
}
d.tableWriter.init(params.p.txn)
if d.interleavedFastPath {
for i := range d.spans {
d.spans[i].EndKey = d.spans[i].EndKey.PrefixEnd()
}
}
ctx := params.ctx
traceKV := params.p.ExtendedEvalContext().Tracing.KVTracingEnabled()
for _, span := range d.spans {
log.VEvent(ctx, 2, "fast delete: skipping scan")
if traceKV {
log.VEventf(ctx, 2, "DelRange %s - %s", span.Key, span.EndKey)
}
d.tableWriter.b.DelRange(span.Key, span.EndKey, true /* returnKeys */)
}
if err := d.tableWriter.finalize(ctx, d.desc); err != nil {
return err
}
for _, r := range d.tableWriter.b.Results {
var prev []byte
for _, i := range r.Keys {
// If prefix is same, don't bother decoding key.
if len(prev) > 0 && bytes.HasPrefix(i, prev) {
continue
}
after, ok, err := d.fetcher.ReadIndexKey(i)
if err != nil {
return err
}
if !ok {
return pgerror.AssertionFailedf("key did not match descriptor")
}
k := i[:len(i)-len(after)]
if !bytes.Equal(k, prev) {
prev = k
d.rowCount++
}
}
}
// Possibly initiate a run of CREATE STATISTICS.
params.ExecCfg().StatsRefresher.NotifyMutation(d.desc.ID, d.rowCount)
return nil
}
// Next implements the planNode interface.
func (*deleteRangeNode) Next(params runParams) (bool, error) {
panic("invalid")
}
// Values implements the planNode interface.
func (*deleteRangeNode) Values() tree.Datums {
panic("invalid")
}
// Close implements the planNode interface.
func (*deleteRangeNode) Close(ctx context.Context) {}
// enableAutoCommit implements the autoCommitNode interface.
func (d *deleteRangeNode) enableAutoCommit() {
d.tableWriter.enableAutoCommit()
}
| {
return nil, false
} |
cmd.rs | use ibc::{core::ics02_client::events::NewBlock, Height};
use crate::event::monitor::EventBatch;
/// A command for a [`Worker`].
#[derive(Debug, Clone)]
pub enum WorkerCmd {
/// A batch of packet events need to be relayed
IbcEvents { batch: EventBatch },
| ClearPendingPackets,
/// Shutdown the worker
Shutdown,
} | /// A new block has been committed
NewBlock { height: Height, new_block: NewBlock },
/// Trigger a pending packets clear |
config.go | package config
import (
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
"log"
"time"
)
type Config struct {}
func (f *Config) SampleConfig() string {
return ""
}
func (f *Config) Description() string {
return "Collect dummy metrics to send to the ThirdEye server to trigger config update."
}
func (f *Config) Gather(acc telegraf.Accumulator) error {
log.Printf("D! Running config input plugin")
now := time.Now()
fields := map[string]interface{}{
"dummy_field": "dummyValue",
}
acc.AddSummary("config", fields, nil, now)
return nil
}
func | () {
inputs.Add("config", func() telegraf.Input {
return &Config{}
})
}
| init |
example02_query.py | from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
# 1. 코드를 보낸다
# 2. 코드를 읽는다
# 3. 분리한다
PORT = 8080
class Handler(BaseHTTPRequestHandler): | do_GET과 do_POST라는 이름은 바꾸면 안되며 고정이다
# 과제
# do_GET : 검색창 만들기
# do_POST : 검색 결과 보여주기 - 네이버에서 크롤링
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# url 를 쪼개준다
# 주소표시줄에 나타난다
query_text = urlparse(self.path).query
print(query_text)
query_vars = parse_qs(query_text)
# 값이 리스트로 되어있는 이유는 변수명은 하나지만 값을 여러개 보낼 수 있다
print(query_vars)
# 1. 딕셔너리를 다룰 수 있는가?
# 2. 변수형에 대해 인지하고 있는가?
# 3. 연산에 대해 알고 있는가?
# query string으로 키와 몸무게를 전달받아서
# bmi를 계산해서 message로 출력하시오
# BMI = 몸무게/신장^2
message = "welcome"
form_html = """
<form action='' method='post'>
<label>Weight:<input type='text' name='weight'></label>
<label>Height:<input type='text' name='height'></label>
<input type=submit value="Calc">
</form>
"""
if 'weight' in query_vars and 'height' in query_vars:
weight = float(query_vars['weight'][0])
height = float(query_vars['height'][0])
bmi = weight / ((height / 100) ** 2)
message += " BMI " + str(bmi)
message += form_html
# response 메시지를 파일처럼 쓴다
self.wfile.write(bytes(message, "utf-8"))
return
def do_POST(self):
content_length = int(self.headers.get('Content-Length'))
# response 메시지를 파일처럼 읽는다
post_body = self.rfile.read(content_length)
# 파일을 해석해서 해석한
queries = parse_qs(post_body.decode('utf8'))
print(queries)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
if 'weight' in queries and 'height' in queries:
weight = float(queries['weight'][0])
height = float(queries['height'][0])
bmi = weight / ((height / 100) ** 2)
message += " BMI " + str("{:0.2f}".format(bmi))
self.wfile.write(bytes("POST Test {}".format(message), "utf-8"))
return
# 한페이지에서 접속 메소드에따라 기능을 분기
# 회원가입 페이지 domain.com/signup/
# GET : 회원가입 양식 보여주기
# POST : 전달받은 데이터를 처리해서 회원가입 진행하기(데이터베이스에 저장하기)
# 메소드를 통해 분기하는 방식이 좋다
def run():
# example01_http 와 똑같음
server_address = ('127.0.0.1', PORT)
httpd = HTTPServer(server_address, Handler)
print("serving at PORT", PORT)
httpd.serve_forever()
run() |
# |
bsv-block-size-activation-generated-default.py | #!/usr/bin/env python3
# Copyright (c) 2019 Bitcoin Association
# Distributed under the Open BSV software license, see the accompanying file LICENSE.
"""
Test that the new default generated (mined) block size works correctly without the use
of the blockmaxsize parameter.
In short; if the user doesn't override things via the blockmaxsize
parameter then after the NEW_BLOCKSIZE_ACTIVATION_TIME date the default generated block
size should increase to DEFAULT_MAX_BLOCK_SIZE_*_AFTER
"""
import math
from test_framework.test_framework import BitcoinTestFramework, SkipTest
from test_framework.util import *
from test_framework.mininode import *
from test_framework.script import CScript, OP_TRUE, OP_RETURN
from test_framework.blocktools import *
from test_framework.cdefs import (ONE_MEGABYTE, MAX_TX_SIZE,REGTEST_NEW_BLOCKSIZE_ACTIVATION_TIME,
REGTEST_DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE, REGTEST_DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER)
DEFAULT_ACTIVATION_TIME = REGTEST_NEW_BLOCKSIZE_ACTIVATION_TIME # can be orverriden on command line
DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE = REGTEST_DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE
DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER = REGTEST_DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER
class BSVGeneratedBlockSizeActivation(BitcoinTestFramework):
def add_options(self, parser):
super().add_options(parser)
parser.add_option("--blocksizeactivationtime", dest="blocksizeactivationtime", type='int')
def set_test_params(self): | self.setup_clean_chain = True
self.extra_args = [['-whitelist=127.0.0.1', "-datacarriersize=%d" % self.data_carrier_size]]
def setup_nodes(self):
# Append -blocksizeactivationtime only if explicitly specified
# We can not do this in set_test_params, because self.options has yet initialized there
self.activation_time = DEFAULT_ACTIVATION_TIME
if (self.options.blocksizeactivationtime is not None):
self.activation_time = self.options.blocksizeactivationtime
self.extra_args[0].append("-blocksizeactivationtime=%d" % self.options.blocksizeactivationtime)
super().setup_nodes()
# Create an empty block with given block time. Used to move median past time around
def mine_empty_block(self, nTime):
node = self.nodes[0]
hashPrev = int(node.getbestblockhash(),16)
coinbase = create_coinbase(node.getblockcount() + 1 )
block = create_block(hashPrev, coinbase, nTime)
block.solve()
ret = node.submitblock(ToHex(block))
assert(ret is None)
# Ensure funding and returns given number of spend anyone transactions without submitting them
def make_transactions(self, num_transactions, add_op_return_size = 0): # TODO: Consolidate with bsv-broadcast_delay.py
# Sanity check - estimate size of funding transaction and check that it os not be too big
assert(200 + num_transactions * 20 < MAX_TX_SIZE)
node = self.nodes[0]
# Generate and age some blocks to have enough spendable coins
node.generate(101)
# Create funding transactions that will provide funds for other transactions
out_value = 1000000
ftx = CTransaction()
for i in range(num_transactions):
ftx.vout.append(CTxOut(out_value, CScript([OP_TRUE]))) # anyone can spend
# Fund the transaction
ftxHex = node.fundrawtransaction(ToHex(ftx),{ 'changePosition' : len(ftx.vout)})['hex']
ftxHex = node.signrawtransaction(ftxHex)['hex']
ftx = FromHex(CTransaction(), ftxHex)
ftx.rehash()
node.sendrawtransaction(ftxHex)
node.generate(1) # ensure that mempool is empty to avoid 'too-long-mempool-chain' errors in next test
# Create transactions that depends on funding transactions that has just been submitted
txs = []
for i in range(num_transactions):
fee = 200 + add_op_return_size
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(ftx.sha256, i), b''))
tx.vout.append(CTxOut(out_value - fee, CScript([OP_TRUE])))
# Add big output if requested
if (add_op_return_size > 0):
tx.vout.append(CTxOut(int(0), CScript([OP_RETURN, b"a" * add_op_return_size])))
tx.rehash()
txs.append(tx)
return txs
def run_test(self):
if DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE == REGTEST_DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER:
self.log.info("Default generated block size is equal before and after activation. Nothing to test")
return # do not use SkipTest(), since this fails build on Jenkins
node = self.nodes[0]
activation_time = self.activation_time
self.log.info("Using activation time %d " % activation_time)
# Generate cca 10 more transactions that needed to avoid problems with rounding
nrTransactions = math.ceil(
(DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE + DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER
+ 10 * (200 + self.data_carrier_size))
/ (200 + self.data_carrier_size))
self.log.info("Required number of transactions: %d " % nrTransactions)
txs = self.make_transactions(nrTransactions, self.data_carrier_size)
# Bring mock time close to the activation time, so that node will not reject block with time-too-new
node.setmocktime(activation_time-1)
# Create and submit 6 empty block with [activation_time-1 .. activation_time+4] to bring MPT to activation_time-1
for i in range(6):
self.mine_empty_block(activation_time-1 + i )
mpt = node.getblockheader(node.getbestblockhash())['mediantime']
assert_equal(mpt, activation_time-1)
# Send all of the transactions:
for tx in txs:
node.sendrawtransaction(ToHex(tx))
mempool_size_before = node.getmempoolinfo()['bytes']
# Mempool should now contain enough transactions for two blocks
assert(mempool_size_before > DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE + DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER)
# Mine the next block with unique block time. MPT before mining the block
# will be activation_time - 1, so the old rules should apply
# Block size should be near DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE
node.setmocktime(activation_time + 5)
block1Hash = node.generate(1)[0]
block1Hex = node.getblock(block1Hash, False)
block1Size = len(block1Hex) /2 # Hex encoded
# Check if block was mined with the correct time (mpt == activation_time)
block1Header = node.getblockheader(block1Hash)
assert(block1Header['mediantime'] == activation_time)
assert(block1Header['time'] == activation_time + 5)
# Mining should not consume too much of data
assert(block1Size < DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE)
# Mining should consume almost whole block size
assert(block1Size > DEFAULT_MAX_GENERATED_BLOCK_SIZE_BEFORE - 2 * self.data_carrier_size)
# Mine another block with unique time. MPT before mining this block
# should be activation_time. New rules should be activated for this block
node.setmocktime(activation_time + 6)
block2Hash = node.generate(1)[0]
block2hex = node.getblock(block2Hash, False)
block2size = len(block2hex) /2 # Hex encoded
# Check if block was mined at the correct time (mpt = activation_time + 1)
block2Header = node.getblockheader(block2Hash)
assert(block2Header['mediantime'] == activation_time +1)
assert(block2Header['time'] == activation_time + 6)
# Mining should not consume too much of data
assert(block2size < DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER)
# Mining should consume almost whole block size
assert(block2size > DEFAULT_MAX_GENERATED_BLOCK_SIZE_AFTER - 2 * self.data_carrier_size)
if __name__ == '__main__':
BSVGeneratedBlockSizeActivation().main() | self.data_carrier_size = 500000
self.num_nodes = 1 |
27.explicite_type_conversion.py | #Explicit type conversion from int to float
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
#Explicit type conversion from float to int
num1 = 10.2
num2 = 20.6 | print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
#Type Conversion between Numbers and Strings
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + str(totalPrice) ) | num3 = (num1 + num2) |
matery.js | $(function () {
/**
* 添加文章卡片hover效果.
*/
let articleCardHover = function () {
let animateClass = 'animated pulse';
$('article .article').hover(function () {
$(this).addClass(animateClass);
}, function () {
$(this).removeClass(animateClass);
});
};
articleCardHover();
/*菜单切换*/
// $('.sidenav').sidenav();
/* 修复文章卡片 div 的宽度. */
let fixPostCardWidth = function (srcId, targetId) {
let srcDiv = $('#' + srcId);
if (srcDiv.length === 0) {
return;
}
let w = srcDiv.width();
if (w >= 450) {
w = w + 21;
} else if (w >= 350 && w < 450) {
w = w + 18;
} else if (w >= 300 && w < 350) {
w = w + 16;
} else {
w = w + 14;
}
$('#' + targetId).width(w);
};
/**
* 修复footer部分的位置,使得在内容比较少时,footer也会在底部.
*/
let fixFooterPosition = function () {
$('.content').css('min-height', window.innerHeight - 165);
};
/**
* 修复样式.
*/
let fixStyles = function () {
fixPostCardWidth('navContainer', 'articles');
fixPostCardWidth('artDetail', 'prenext-posts');
fixFooterPosition();
};
fixStyles();
/*调整屏幕宽度时重新设置文章列的宽度,修复小间距问题*/
$(window).resize(function () {
fixStyles();
});
/*初始化瀑布流布局*/
// $('#articles').masonry({
// itemSelector: '.article'
// });
AOS.init({
easing: 'ease-in-out-sine',
duration: 700,
delay: 100
});
/*文章内容详情的一些初始化特性*/
let articleInit = function () {
$('#articleContent a').attr('target', '_blank');
$('#articleContent img').each(function () {
let imgPath = $(this).attr('src');
$(this).wrap('<div class="img-item" data-src="' + imgPath + '" data-sub-html=".caption"></div>');
// 图片添加阴影
$(this).addClass("img-shadow img-margin");
// 图片添加字幕
let alt = $(this).attr('alt');
let title = $(this).attr('title');
let captionText = "";
// 如果alt为空,title来替
if (alt === undefined || alt === "") {
if (title !== undefined && title !== "") {
captionText = title;
}
} else {
captionText = alt;
}
// 字幕不空,添加之
if (captionText !== "") {
let captionDiv = document.createElement('div');
captionDiv.className = 'caption';
let captionEle = document.createElement('b');
captionEle.className = 'center-caption';
captionEle.innerText = captionText;
captionDiv.appendChild(captionEle);
this.insertAdjacentElement('afterend', captionDiv)
}
});
$('#articleContent, #myGallery').lightGallery({
selector: '.img-item',
// 启用字幕
subHtmlSelectorRelative: true
});
// progress bar init
const progressElement = window.document.querySelector('.progress-bar');
if (progressElement) {
new ScrollProgress((x, y) => {
progressElement.style.width = y * 100 + '%';
});
}
};
articleInit();
// $('.modal').modal();
| /*回到顶部*/
$('#backTop').click(function () {
$('body,html').animate({scrollTop: 0}, 400);
return false;
});
/*监听滚动条位置*/
let $nav = $('#headNav');
let $backTop = $('.top-scroll');
$(window).scroll(function () {
/* 回到顶部按钮根据滚动条的位置的显示和隐藏.*/
let scroll = $(window).scrollTop();
if (scroll < 100) {
$nav.addClass('nav-transparent');
$backTop.slideUp(300);
} else {
$nav.removeClass('nav-transparent');
$backTop.slideDown(300);
}
});
}); | |
abc-notation-display.js | import React from 'react';
import autoBind from 'auto-bind';
import PropTypes from 'prop-types';
import abcjs from '../../../common/abcjs-import.js';
import { inject } from '../../../components/container-context.js';
import { sectionDisplayProps } from '../../../ui/default-prop-types.js';
import GithubFlavoredMarkdown from '../../../common/github-flavored-markdown.js';
const abcOptions = {
paddingtop: 0,
paddingbottom: 0,
paddingright: 0,
paddingleft: 0,
responsive: 'resize'
};
const midiOptions = {
generateDownload: false,
generateInline: true
};
class AbcNotationDisplay extends React.PureComponent {
constructor(props) {
super(props);
autoBind(this);
this.abcContainerRef = React.createRef();
this.midiContainerRef = React.createRef();
}
componentDidMount() {
const { content } = this.props;
abcjs.renderAbc(this.abcContainerRef.current, content.abcCode, abcOptions);
abcjs.renderMidi(this.midiContainerRef.current, content.abcCode, midiOptions);
}
render() {
const { content, githubFlavoredMarkdown } = this.props;
return (
<div className="AbcNotation fa5">
<div className={`AbcNotation-wrapper u-max-width-${content.maxWidth || 100}`}>
<div ref={this.abcContainerRef} />
{content.displayMidi && <div ref={this.midiContainerRef} />}
<div
className="AbcNotation-copyrightInfo"
dangerouslySetInnerHTML={{ __html: githubFlavoredMarkdown.render(content.text || '') }}
/>
</div>
</div>
);
}
}
AbcNotationDisplay.propTypes = {
...sectionDisplayProps, | githubFlavoredMarkdown: GithubFlavoredMarkdown
}, AbcNotationDisplay); | githubFlavoredMarkdown: PropTypes.instanceOf(GithubFlavoredMarkdown).isRequired
};
export default inject({ |
erSakerFullscreen.ts | import { paths } from '../../../../routes/routing';
import { matchPath } from 'react-router';
export function | (pathname: string): boolean {
return !!matchPath(pathname, paths.sakerFullscreen);
}
| erSakerFullscreen |
ipv6_send.rs | //! This file contains the interface definition for sending an IPv6 packet.
//! The [IP6Sender](trait.IP6Sender.html) trait provides an interface
//! for sending IPv6 packets, while the [IP6SendClient](trait.IP6SendClient) trait
//! must be implemented by upper layers to receive the `send_done` callback
//! when a transmission has completed.
//!
//! This file also includes an implementation of the `IP6Sender` trait, which
//! sends an IPv6 packet using 6LoWPAN.
// Additional Work and Known Problems
// ----------------------------------
// The main areas for additional work is with regards to the interface provided
// by `IP6Sender`. The current interface differs from the one provided in
// the networking stack overview document, and should be changed to better
// reflect that document. Additionally, the specific implementation is
// over 6LoWPAN, and should be separated from the generic IPv6 sending
// interface.
use crate::ieee802154::device::{MacDevice, TxClient};
use crate::net::ieee802154::MacAddress;
use crate::net::ipv6::ip_utils::IPAddr;
use crate::net::ipv6::ipv6::{IP6Header, IP6Packet, TransportHeader};
use crate::net::network_capabilities::{IpVisibilityCapability, NetworkCapability};
use crate::net::sixlowpan::sixlowpan_state::TxState;
use core::cell::Cell;
use kernel::common::cells::{OptionalCell, TakeCell};
use kernel::common::leasable_buffer::LeasableBuffer;
use kernel::debug;
use kernel::hil::time::{self, Frequency};
use kernel::ReturnCode;
/// This trait must be implemented by upper layers in order to receive
/// the `send_done` callback when a transmission has completed. The upper
/// layer must then call `IP6Sender.set_client` in order to receive this
/// callback.
pub trait IP6SendClient {
fn send_done(&self, result: ReturnCode);
}
/// This trait provides a basic IPv6 sending interface. It exposes basic
/// configuration information for the IPv6 layer (setting the source address,
/// setting the gateway MAC address), as well as a way to send an IPv6
/// packet.
pub trait IP6Sender<'a> {
/// This method sets the `IP6SendClient` for the `IP6Sender` instance, which
/// receives the `send_done` callback when transmission has finished.
///
/// # Arguments
/// `client` - Client that implements the `IP6SendClient` trait to receive the
/// `send_done` callback
fn set_client(&self, client: &'a dyn IP6SendClient);
/// This method sets the source address for packets sent from the
/// `IP6Sender` instance.
///
/// # Arguments
/// `src_addr` - `IPAddr` to set as the source address for packets sent
/// from this instance of `IP6Sender`
fn set_addr(&self, src_addr: IPAddr);
/// This method sets the gateway/next hop MAC address for this `IP6Sender`
/// instance.
///
/// # Arguments
/// `gateway` - MAC address to send the constructed packet to
fn set_gateway(&self, gateway: MacAddress);
/// This method sets the `IP6Header` for the `IP6Sender` instance
///
/// # Arguments
/// `ip6_header` - New `IP6Header` that subsequent packets sent via this
/// `IP6Sender` instance will use
fn set_header(&mut self, ip6_header: IP6Header);
/// This method sends the provided transport header and payload to the
/// given destination IP address
///
/// # Arguments
/// `dst` - IPv6 address to send the packet to
/// `transport_header` - The `TransportHeader` for the packet being sent
/// `payload` - The transport payload for the packet being sent
fn send_to(
&self,
dst: IPAddr,
transport_header: TransportHeader,
payload: &LeasableBuffer<'static, u8>,
net_cap: &'static NetworkCapability,
) -> ReturnCode;
}
/// This struct is a specific implementation of the `IP6Sender` trait. This
/// struct sends the packet using 6LoWPAN over a generic `MacDevice` object.
pub struct IP6SendStruct<'a, A: time::Alarm<'a>> {
// We want the ip6_packet field to be a TakeCell so that it is easy to mutate
ip6_packet: TakeCell<'static, IP6Packet<'static>>,
alarm: &'a A, // Alarm so we can introduce a small delay between fragments to ensure
// successful reception on receivers with slow copies out of the radio buffer
// (imix)
src_addr: Cell<IPAddr>,
gateway: Cell<MacAddress>,
tx_buf: TakeCell<'static, [u8]>,
sixlowpan: TxState<'a>,
radio: &'a dyn MacDevice<'a>,
dst_mac_addr: MacAddress,
src_mac_addr: MacAddress,
client: OptionalCell<&'a dyn IP6SendClient>,
ip_vis: &'static IpVisibilityCapability,
}
impl<'a, A: time::Alarm<'a>> IP6Sender<'a> for IP6SendStruct<'a, A> {
fn set_client(&self, client: &'a dyn IP6SendClient) {
self.client.set(client);
}
fn set_addr(&self, src_addr: IPAddr) {
self.src_addr.set(src_addr);
}
fn set_gateway(&self, gateway: MacAddress) {
self.gateway.set(gateway);
}
fn set_header(&mut self, ip6_header: IP6Header) {
self.ip6_packet
.map(|ip6_packet| ip6_packet.header = ip6_header);
}
fn send_to(
&self,
dst: IPAddr,
transport_header: TransportHeader,
payload: &LeasableBuffer<'static, u8>,
net_cap: &'static NetworkCapability,
) -> ReturnCode {
if !net_cap.remote_addr_valid(dst, self.ip_vis) {
return ReturnCode::FAIL;
}
self.sixlowpan.init(
self.src_mac_addr,
self.dst_mac_addr,
self.radio.get_pan(),
None,
);
self.init_packet(dst, transport_header, payload);
let ret = self.send_next_fragment();
ret
}
}
impl<'a, A: time::Alarm<'a>> IP6SendStruct<'a, A> {
pub fn new(
ip6_packet: &'static mut IP6Packet<'static>,
alarm: &'a A,
tx_buf: &'static mut [u8],
sixlowpan: TxState<'a>,
radio: &'a dyn MacDevice<'a>,
dst_mac_addr: MacAddress,
src_mac_addr: MacAddress,
ip_vis: &'static IpVisibilityCapability,
) -> IP6SendStruct<'a, A> {
IP6SendStruct {
ip6_packet: TakeCell::new(ip6_packet),
alarm: alarm,
src_addr: Cell::new(IPAddr::new()),
gateway: Cell::new(dst_mac_addr),
tx_buf: TakeCell::new(tx_buf),
sixlowpan: sixlowpan,
radio: radio,
dst_mac_addr: dst_mac_addr,
src_mac_addr: src_mac_addr,
client: OptionalCell::empty(),
ip_vis: ip_vis,
}
}
fn init_packet(
&self,
dst_addr: IPAddr,
transport_header: TransportHeader,
payload: &LeasableBuffer<'static, u8>,
) {
self.ip6_packet.map_or_else(
|| {
debug!("init packet failed.");
},
|ip6_packet| {
ip6_packet.header = IP6Header::default();
ip6_packet.header.src_addr = self.src_addr.get();
ip6_packet.header.dst_addr = dst_addr;
ip6_packet.set_payload(transport_header, payload);
ip6_packet.set_transport_checksum();
},
);
}
// Returns EBUSY if the tx_buf is not there
fn send_next_fragment(&self) -> ReturnCode {
// Originally send_complete() was called within the below closure.
// However, this led to a race condition where when multiple apps transmitted
// simultaneously, it was possible for send_complete to trigger another
// transmission before the below closure would exit, leading to this function
// being called again by another app before ip6_packet is replaced.
// To fix this, we pass a bool out of the closure to indicate whether send_completed()
// should be called once the closure exits
let (ret, call_send_complete) = self
.ip6_packet
.map(move |ip6_packet| match self.tx_buf.take() {
Some(tx_buf) => {
let next_frame = self.sixlowpan.next_fragment(ip6_packet, tx_buf, self.radio);
match next_frame {
Ok((is_done, frame)) => {
if is_done {
self.tx_buf.replace(frame.into_buf());
//self.send_completed(ReturnCode::SUCCESS);
(ReturnCode::SUCCESS, true)
} else {
let (err, _frame_option) = self.radio.transmit(frame);
(err, false)
}
}
Err((retcode, buf)) => {
self.tx_buf.replace(buf);
//self.send_completed(retcode);
(retcode, true)
}
}
}
None => {
debug!("Missing tx_buf");
(ReturnCode::EBUSY, false)
}
})
.unwrap_or((ReturnCode::ENOMEM, false));
if call_send_complete {
self.send_completed(ret);
return ReturnCode::SUCCESS;
}
ret
}
fn send_completed(&self, result: ReturnCode) |
}
impl<'a, A: time::Alarm<'a>> time::AlarmClient for IP6SendStruct<'a, A> {
fn fired(&self) {
let result = self.send_next_fragment();
if result != ReturnCode::SUCCESS {
self.send_completed(result);
}
}
}
impl<'a, A: time::Alarm<'a>> TxClient for IP6SendStruct<'a, A> {
fn send_done(&self, tx_buf: &'static mut [u8], acked: bool, result: ReturnCode) {
self.tx_buf.replace(tx_buf);
if result != ReturnCode::SUCCESS {
debug!("Send Failed: {:?}, acked: {}", result, acked);
self.client.map(move |client| {
client.send_done(result);
});
} else {
// Below code adds delay between fragments. Despite some efforts
// to fix this bug, I find that without it the receiving imix cannot
// receive more than 2 fragments in a single packet without hanging
// waiting for the third fragments.
// Specifically, here we set a timer, which fires and sends the next fragment
// One flaw with this is that we also introduce a delay after sending the last
// fragment, before passing the send_done callback back to the client. This
// could be optimized by checking if it is the last fragment before setting the timer.
let interval = (100000 as u32) * <A::Frequency>::frequency() / 1000000;
let tics = self.alarm.now().wrapping_add(interval);
self.alarm.set_alarm(tics);
}
}
}
| {
self.client.map(move |client| {
client.send_done(result);
});
} |
forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# RMG Website - A Django-powered website for Reaction Mechanism Generator
#
# Copyright (c) 2011 Prof. William H. Green ([email protected]) and the
# RMG Team ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the 'Software'),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
################################################################################
from django import forms
from django.forms.util import ErrorList
from django.utils.safestring import mark_safe
from rmgpy.molecule.molecule import Molecule
import rmgpy
import copy
import sys
class DivErrorList(ErrorList):
def __unicode__(self):
return self.as_divs()
def as_divs(self):
if not self: return u''
return mark_safe(u'<label> </label>%s' % (''.join([u'<div class="error">%s</div>' % e for e in self])))
class ThermoSearchForm(forms.Form):
"""
This form provides a means of specifying a species to get thermodynamic
data for.
"""
species = forms.CharField(widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}))
def clean_species(self):
"""
Custom validation for the species field to ensure that a valid adjacency
list has been provided.
"""
try:
molecule = Molecule()
molecule.fromAdjacencyList(str(self.cleaned_data['species']))
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid adjacency list.')
return str(self.cleaned_data['species'])
def as_table(self):
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
return self._html_output(
normal_row = u'<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
error_row = u'<tr><td colspan="2">%s</td></tr>',
row_ender = u'</td></tr>',
help_text_html = u'<br />%s',
errors_on_separate_row = False)
class KineticsSearchForm(forms.Form):
"""
This form provides a means of specifying a set of reactants to get
kinetic data for.
"""
reactant1_identifier = forms.CharField(label="Reactant #1 Identifier", widget=forms.TextInput(attrs={'onchange':'resolve("reactant1");','class':'identifier'}), required=False)
reactant1 = forms.CharField(label="Reactant #1", widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}))
reactant2_identifier = forms.CharField(label="Reactant #2 Identifier", widget=forms.TextInput(attrs={'onchange':'resolve("reactant2");','class':'identifier'}), required=False)
reactant2 = forms.CharField(label="Reactant #2", widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}), required=False)
product1_identifier = forms.CharField(label="Product #1 Identifier", widget=forms.TextInput(attrs={'onchange':'resolve("product1");','class':'identifier'}), required=False)
product1 = forms.CharField(label="Product #1", widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}), required=False)
product2_identifier = forms.CharField(label="Product #2 Identifier", widget=forms.TextInput(attrs={'onchange':'resolve("product2");','class':'identifier'}), required=False)
product2 = forms.CharField(label="Product #2", widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}), required=False)
def clean_reactant1(self):
"""
Custom validation for the reactant1 field to ensure that a valid
adjacency list has been provided.
"""
try:
molecule = Molecule()
molecule.fromAdjacencyList(str(self.cleaned_data['reactant1']))
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid adjacency list.')
return str(self.cleaned_data['reactant1'])
def clean_reactant2(self):
"""
Custom validation for the reactant1 field to ensure that a valid
adjacency list has been provided.
"""
try:
adjlist = str(self.cleaned_data['reactant2'])
if adjlist.strip() == '': return ''
molecule = Molecule()
molecule.fromAdjacencyList(adjlist)
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid adjacency list.')
return str(self.cleaned_data['reactant2'])
def clean_product1(self):
"""
Custom validation for the product1 field to ensure that a valid
adjacency list has been provided.
"""
try:
adjlist = str(self.cleaned_data['product1'])
if adjlist.strip() == '': return ''
molecule = Molecule()
molecule.fromAdjacencyList(adjlist)
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid adjacency list.')
return str(self.cleaned_data['product1'])
def clean_product2(self):
"""
Custom validation for the product1 field to ensure that a valid
adjacency list has been provided.
"""
try:
adjlist = str(self.cleaned_data['product2'])
if adjlist.strip() == '': return ''
molecule = Molecule()
molecule.fromAdjacencyList(adjlist)
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid adjacency list.')
return str(self.cleaned_data['product2'])
class MoleculeSearchForm(forms.Form):
"""
Form for drawing molecule from adjacency list
"""
species_identifier = forms.CharField(label="Species Identifier", widget=forms.TextInput(attrs={'onchange':'resolve();', 'style':'width:100%;'}), required=False)
species = forms.CharField(label ="Adjacency List", widget = forms.Textarea(attrs={'cols': 50, 'rows': 20, 'onchange':"$('.result').hide();" }), required=True)
def clean_species(self):
"""
Custom validation for the species field to ensure that a valid adjacency
list has been provided.
"""
try:
adjlist = str(self.cleaned_data['species']) | molecule = Molecule()
molecule.fromAdjacencyList(str(self.cleaned_data['species']))
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid adjacency list.')
return adjlist
class EniSearchForm(forms.Form):
"""
Form for drawing molecule from adjacency list
"""
detergent_identifier = forms.CharField(label="Detergent Identifier", widget=forms.TextInput(attrs={'onchange':'resolve("detergent");','class':'identifier'}), required=False)
detergent = forms.CharField(label="Detergent", widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}))
deposit_identifier = forms.CharField(label="Deposit Identifier", widget=forms.TextInput(attrs={'onchange':'resolve("deposit");','class':'identifier'}), required=False)
deposit = forms.CharField(label="Deposit", widget=forms.widgets.Textarea(attrs={'rows': 6, 'cols': 30}), required=False)
def clean_detergent(self):
"""
Return molecular representation of input detergent structure """
try:
detergent = Molecule()
detergent.fromAdjacencyList(str(self.cleaned_data['detergent']))
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid SMILES entry.')
return str(self.cleaned_data['detergent'])
def clean_deposit(self):
"""
Return molecular representation of input deposit structure
"""
try:
deposit = Molecule()
deposit.fromAdjacencyList(str(self.cleaned_data['deposit']))
except Exception, e:
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid SMILES entry.')
return str(self.cleaned_data['deposit'])
class KineticsEntryEditForm(forms.Form):
"""
Form for editing kinetics database entries
"""
entry = forms.CharField(label="Database Entry", widget = forms.Textarea(attrs={'cols': 80, 'rows': 40, 'class':'data_entry'}), required=True)
change = forms.CharField(label="Summary of changes", widget=forms.TextInput(attrs={'class':'change_summary'}), required=True)
def clean_entry(self):
"""
Custom validation for the entry field to ensure that a valid
entry has been provided.
"""
new_database = rmgpy.data.kinetics.KineticsDatabase()
new_depository = rmgpy.data.kinetics.KineticsDepository()
global_context = {'__builtins__': None} # disable even builtins
local_context = copy.copy(new_database.local_context)
local_context['entry'] = new_depository.loadEntry
for key,value in rmgpy.data.base.Database.local_context.iteritems():
local_context[key]=value
print local_context
try:
entry_string = str(self.cleaned_data['entry'])
entry = eval("entry( index=-1, {0})".format(entry_string), global_context, local_context)
except Exception, e:
print "Invalid entry from KineticsEntryEditForm."
print repr(entry_string)
import traceback
traceback.print_exc(e)
raise forms.ValidationError('Invalid entry.'+ str(sys.exc_info()[1]))
return entry
class TemperatureForm(forms.Form):
"""
This form allows the user to enter a specific temperature and display the resulting rates
on a collection of kinetics search results
"""
temperature = forms.FloatField(label="Specify Temperature (K)") | if adjlist == '' : return '' |
index.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); | var item = new DataValidator_1.DataValidator({ name: 'arn' }, { name: 'arn' });
// console.log("Item", item);
console.log("Testing equality", item.validateInput());
console.log("Testing equality Instance methods", DataValidator_1.DataValidator.compareObjectKeys({ name: 'arn' }, { name: 'arn' })); | var DataValidator_1 = require("./components/errors/DataValidator");
console.log("Achilles Setup"); |
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
|
if __name__ == '__main__':
main()
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tracker_backend.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv) |
execution.rs | use super::cache::QueryCache;
use crossbeam::atomic::AtomicCell;
use graph::{data::schema::META_FIELD_NAME, prelude::CheapClone};
use graphql_parser::query as q;
use graphql_parser::schema as s;
use indexmap::IndexMap;
use lazy_static::lazy_static;
use stable_hash::crypto::SetHasher;
use stable_hash::prelude::*;
use stable_hash::utils::stable_hash;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::iter;
use std::sync::{Mutex, RwLock};
use std::time::Instant;
use graph::data::graphql::*;
use graph::data::query::CacheStatus;
use graph::prelude::*;
use graph::util::lfu_cache::LfuCache;
use crate::introspection::{
is_introspection_field, INTROSPECTION_DOCUMENT, INTROSPECTION_QUERY_TYPE,
};
use crate::prelude::*;
use crate::query::ast as qast;
use crate::schema::ast as sast;
use crate::values::coercion;
type QueryHash = <SetHasher as StableHasher>::Out;
#[derive(Debug)]
struct CacheByBlock {
block: EthereumBlockPointer,
max_weight: usize,
weight: usize,
cache: HashMap<QueryHash, Arc<QueryResult>>,
}
impl CacheByBlock {
fn new(block: EthereumBlockPointer, max_weight: usize) -> Self {
CacheByBlock {
block,
max_weight,
weight: 0,
cache: HashMap::new(),
}
}
/// Returns `true` if the insert was successful or `false` if the cache was full.
fn insert(&mut self, key: QueryHash, value: Arc<QueryResult>, weight: usize) -> bool {
// We never try to insert errors into this cache, and always resolve some value.
assert!(!value.has_errors());
let fits_in_cache = self.weight + weight <= self.max_weight;
if fits_in_cache {
self.weight += weight;
self.cache.insert(key, value);
}
fits_in_cache
}
}
struct WeightedResult {
result: Arc<QueryResult>,
weight: usize,
}
impl CacheWeight for WeightedResult {
fn indirect_weight(&self) -> usize {
self.weight
}
}
impl Default for WeightedResult {
fn default() -> Self {
WeightedResult {
result: Arc::new(QueryResult::new(BTreeMap::default())),
weight: 0,
}
}
}
/// Organize block caches by network names. Since different networks
/// will be at different block heights, we need to keep their `CacheByBlock`
/// separate
struct QueryBlockCache(Vec<(String, VecDeque<CacheByBlock>)>);
impl QueryBlockCache {
fn insert(
&mut self,
network: &str,
block_ptr: EthereumBlockPointer,
key: QueryHash,
result: Arc<QueryResult>,
weight: usize,
) -> bool {
// Get or insert the cache for this network.
let cache = match self
.0
.iter_mut()
.find(|(n, _)| n == network)
.map(|(_, c)| c)
{
Some(c) => c,
None => {
self.0.push((network.to_owned(), VecDeque::new()));
&mut self.0.last_mut().unwrap().1
}
};
// If there is already a cache by the block of this query, just add it there.
let mut cache_insert = false;
if let Some(cache_by_block) = cache.iter_mut().find(|c| c.block == block_ptr) {
cache_insert = cache_by_block.insert(key, result.cheap_clone(), weight);
} else if *QUERY_CACHE_BLOCKS > 0 {
// We're creating a new `CacheByBlock` if:
// - There are none yet, this is the first query being cached, or
// - `block_ptr` is of higher or equal number than the most recent block in the cache.
// Otherwise this is a historical query that does not belong in
// the block cache
let should_insert = match cache.iter().next() {
None => true,
Some(highest) => highest.block.number <= block_ptr.number,
};
if should_insert {
if cache.len() == *QUERY_CACHE_BLOCKS {
// At capacity, so pop the oldest block.
cache.pop_back();
}
// Create a new cache by block, insert this entry, and add it to the QUERY_CACHE.
let max_weight = *QUERY_CACHE_MAX_MEM / *QUERY_CACHE_BLOCKS;
let mut cache_by_block = CacheByBlock::new(block_ptr, max_weight);
cache_insert = cache_by_block.insert(key, result.cheap_clone(), weight);
cache.push_front(cache_by_block);
}
}
cache_insert
}
fn get(
&self,
network: &str,
block_ptr: &EthereumBlockPointer,
key: &QueryHash,
) -> Option<Arc<QueryResult>> {
if let Some(cache) = self.0.iter().find(|(n, _)| n == network).map(|(_, c)| c) {
// Iterate from the most recent block looking for a block that matches.
if let Some(cache_by_block) = cache.iter().find(|c| &c.block == block_ptr) {
if let Some(response) = cache_by_block.cache.get(key) {
return Some(response.cheap_clone());
}
}
}
None
}
}
lazy_static! {
// Comma separated subgraph ids to cache queries for.
// If `*` is present in the list, queries are cached for all subgraphs.
// Defaults to "*".
static ref CACHED_SUBGRAPH_IDS: Vec<String> = {
std::env::var("GRAPH_CACHED_SUBGRAPH_IDS")
.unwrap_or("*".to_string())
.split(',')
.map(|s| s.to_owned())
.collect()
};
static ref CACHE_ALL: bool = CACHED_SUBGRAPH_IDS.contains(&"*".to_string());
// How many blocks per network should be kept in the query cache. When the limit is reached,
// older blocks are evicted. This should be kept small since a lookup to the cache is O(n) on
// this value, and the cache memory usage also increases with larger number. Set to 0 to disable
// the cache. Defaults to 1.
static ref QUERY_CACHE_BLOCKS: usize = {
std::env::var("GRAPH_QUERY_CACHE_BLOCKS")
.unwrap_or("1".to_string())
.parse::<usize>()
.expect("Invalid value for GRAPH_QUERY_CACHE_BLOCKS environment variable")
};
/// Maximum total memory to be used by the cache. Each block has a max size of
/// `QUERY_CACHE_MAX_MEM` / `QUERY_CACHE_BLOCKS`. The env var is in MB.
static ref QUERY_CACHE_MAX_MEM: usize = {
1_000_000 *
std::env::var("GRAPH_QUERY_CACHE_MAX_MEM")
.unwrap_or("1000".to_string())
.parse::<usize>()
.expect("Invalid value for GRAPH_QUERY_CACHE_MAX_MEM environment variable")
};
static ref QUERY_CACHE_STALE_PERIOD: u64 = {
std::env::var("GRAPH_QUERY_CACHE_STALE_PERIOD")
.unwrap_or("100".to_string())
.parse::<u64>()
.expect("Invalid value for GRAPH_QUERY_CACHE_STALE_PERIOD environment variable")
};
// Cache query results for recent blocks by network.
// The `VecDeque` works as a ring buffer with a capacity of `QUERY_CACHE_BLOCKS`.
static ref QUERY_BLOCK_CACHE: RwLock<QueryBlockCache> = RwLock::new(QueryBlockCache(vec![]));
static ref QUERY_HERD_CACHE: QueryCache<Arc<QueryResult>> = QueryCache::new();
static ref QUERY_LFU_CACHE: Mutex<LfuCache<QueryHash, WeightedResult>> = Mutex::new(LfuCache::new());
}
struct HashableQuery<'a> {
query_schema_id: &'a SubgraphDeploymentId,
query_variables: &'a HashMap<q::Name, q::Value>,
query_fragments: &'a HashMap<String, q::FragmentDefinition>,
selection_set: &'a q::SelectionSet,
block_ptr: &'a EthereumBlockPointer,
}
/// Note that the use of StableHash here is a little bit loose. In particular,
/// we are converting items to a string inside here as a quick-and-dirty
/// implementation. This precludes the ability to add new fields (unlikely
/// anyway). So, this hash isn't really Stable in the way that the StableHash
/// crate defines it. Since hashes are only persisted for this process, we don't
/// need that property. The reason we are using StableHash is to get collision
/// resistance and use it's foolproof API to prevent easy mistakes instead.
///
/// This is also only as collision resistant insofar as the to_string impls are
/// collision resistant. It is highly likely that this is ok, since these come
/// from an ast.
///
/// It is possible that multiple asts that are effectively the same query with
/// different representations. This is considered not an issue. The worst
/// possible outcome is that the same query will have multiple cache entries.
/// But, the wrong result should not be served.
impl StableHash for HashableQuery<'_> {
fn | <H: StableHasher>(&self, mut sequence_number: H::Seq, state: &mut H) {
self.query_schema_id
.stable_hash(sequence_number.next_child(), state);
// Not stable! Uses to_string()
self.query_variables
.iter()
.map(|(k, v)| (k, v.to_string()))
.collect::<HashMap<_, _>>()
.stable_hash(sequence_number.next_child(), state);
// Not stable! Uses to_string()
self.query_fragments
.iter()
.map(|(k, v)| (k, v.to_string()))
.collect::<HashMap<_, _>>()
.stable_hash(sequence_number.next_child(), state);
// Not stable! Uses to_string
self.selection_set
.to_string()
.stable_hash(sequence_number.next_child(), state);
self.block_ptr
.stable_hash(sequence_number.next_child(), state);
}
}
// The key is: subgraph id + selection set + variables + fragment definitions
fn cache_key(
ctx: &ExecutionContext<impl Resolver>,
selection_set: &q::SelectionSet,
block_ptr: &EthereumBlockPointer,
) -> QueryHash {
// It is very important that all data used for the query is included.
// Otherwise, incorrect results may be returned.
let query = HashableQuery {
query_schema_id: ctx.query.schema.id(),
query_variables: &ctx.query.variables,
query_fragments: &ctx.query.fragments,
selection_set,
block_ptr,
};
stable_hash::<SetHasher, _>(&query)
}
/// Contextual information passed around during query execution.
pub struct ExecutionContext<R>
where
R: Resolver,
{
/// The logger to use.
pub logger: Logger,
/// The query to execute.
pub query: Arc<crate::execution::Query>,
/// The resolver to use.
pub resolver: R,
/// Time at which the query times out.
pub deadline: Option<Instant>,
/// Max value for `first`.
pub max_first: u32,
/// Max value for `skip`
pub max_skip: u32,
/// Records whether this was a cache hit, used for logging.
pub(crate) cache_status: AtomicCell<CacheStatus>,
pub load_manager: Arc<dyn QueryLoadManager>,
/// Set if this query is being executed in another resolver and therefore reentering functions
/// such as `execute_root_selection_set`.
pub nested_resolver: bool,
}
// Helpers to look for types and fields on both the introspection and regular schemas.
pub(crate) fn get_named_type(schema: &s::Document, name: &Name) -> Option<s::TypeDefinition> {
if name.starts_with("__") {
sast::get_named_type(&INTROSPECTION_DOCUMENT, name).cloned()
} else {
sast::get_named_type(schema, name).cloned()
}
}
pub(crate) fn get_field<'a>(
object_type: impl Into<ObjectOrInterface<'a>>,
name: &Name,
) -> Option<s::Field> {
if name == "__schema" || name == "__type" {
let object_type = *INTROSPECTION_QUERY_TYPE;
sast::get_field(object_type, name).cloned()
} else {
sast::get_field(object_type, name).cloned()
}
}
pub(crate) fn object_or_interface<'a>(
schema: &'a s::Document,
name: &Name,
) -> Option<ObjectOrInterface<'a>> {
if name.starts_with("__") {
INTROSPECTION_DOCUMENT.object_or_interface(name)
} else {
schema.object_or_interface(name)
}
}
impl<R> ExecutionContext<R>
where
R: Resolver,
{
pub fn as_introspection_context(&self) -> ExecutionContext<IntrospectionResolver> {
let introspection_resolver =
IntrospectionResolver::new(&self.logger, self.query.schema.schema());
ExecutionContext {
logger: self.logger.cheap_clone(),
resolver: introspection_resolver,
query: self.query.as_introspection_query(),
deadline: self.deadline,
max_first: std::u32::MAX,
max_skip: std::u32::MAX,
// `cache_status` and `load_manager` are dead values for the introspection context.
cache_status: AtomicCell::new(CacheStatus::Miss),
load_manager: self.load_manager.cheap_clone(),
nested_resolver: self.nested_resolver,
}
}
}
pub fn execute_root_selection_set_uncached(
ctx: &ExecutionContext<impl Resolver>,
selection_set: &q::SelectionSet,
root_type: &s::ObjectType,
) -> Result<BTreeMap<String, q::Value>, Vec<QueryExecutionError>> {
// Split the top-level fields into introspection fields and
// regular data fields
let mut data_set = q::SelectionSet {
span: selection_set.span.clone(),
items: Vec::new(),
};
let mut intro_set = q::SelectionSet {
span: selection_set.span.clone(),
items: Vec::new(),
};
let mut meta_items = Vec::new();
for (_, fields) in collect_fields(ctx, root_type, iter::once(selection_set)) {
let name = fields[0].name.clone();
let selections = fields.into_iter().map(|f| q::Selection::Field(f.clone()));
// See if this is an introspection or data field. We don't worry about
// non-existent fields; those will cause an error later when we execute
// the data_set SelectionSet
if is_introspection_field(&name) {
intro_set.items.extend(selections)
} else if &name == META_FIELD_NAME {
meta_items.extend(selections)
} else {
data_set.items.extend(selections)
}
}
// If we are getting regular data, prefetch it from the database
let mut values = if data_set.items.is_empty() && meta_items.is_empty() {
BTreeMap::default()
} else {
let initial_data = ctx.resolver.prefetch(&ctx, &data_set)?;
data_set.items.extend(meta_items);
execute_selection_set_to_map(&ctx, iter::once(&data_set), root_type, initial_data)?
};
// Resolve introspection fields, if there are any
if !intro_set.items.is_empty() {
let ictx = ctx.as_introspection_context();
values.extend(execute_selection_set_to_map(
&ictx,
iter::once(&intro_set),
&*INTROSPECTION_QUERY_TYPE,
None,
)?);
}
Ok(values)
}
/// Executes the root selection set of a query.
pub async fn execute_root_selection_set<R: Resolver>(
ctx: Arc<ExecutionContext<R>>,
selection_set: Arc<q::SelectionSet>,
root_type: Arc<s::ObjectType>,
block_ptr: Option<EthereumBlockPointer>,
) -> Arc<QueryResult> {
// Cache the cache key to not have to calculate it twice - once for lookup
// and once for insert.
let mut key: Option<QueryHash> = None;
if R::CACHEABLE && (*CACHE_ALL || CACHED_SUBGRAPH_IDS.contains(ctx.query.schema.id())) {
if let (Some(block_ptr), Some(network)) = (block_ptr, &ctx.query.network) {
// JSONB and metadata queries use `BLOCK_NUMBER_MAX`. Ignore this case for two reasons:
// - Metadata queries are not cacheable.
// - Caching `BLOCK_NUMBER_MAX` would make this cache think all other blocks are old.
if block_ptr.number != BLOCK_NUMBER_MAX as u64 {
// Calculate the hash outside of the lock
let cache_key = cache_key(&ctx, &selection_set, &block_ptr);
// Check if the response is cached, first in the recent blocks cache,
// and then in the LfuCache for historical queries
// The blocks are used to delimit how long locks need to be held
{
let cache = QUERY_BLOCK_CACHE.read().unwrap();
if let Some(result) = cache.get(network, &block_ptr, &cache_key) {
ctx.cache_status.store(CacheStatus::Hit);
return result;
}
}
{
let mut cache = QUERY_LFU_CACHE.lock().unwrap();
if let Some(weighted) = cache.get(&cache_key) {
ctx.cache_status.store(CacheStatus::Hit);
return weighted.result.cheap_clone();
}
}
key = Some(cache_key);
}
}
}
let execute_ctx = ctx.cheap_clone();
let execute_selection_set = selection_set.cheap_clone();
let execute_root_type = root_type.cheap_clone();
let nested_resolver = ctx.nested_resolver;
let run_query = async move {
// Limiting the cuncurrent queries prevents increase in resource usage when the DB is
// contended and queries start queing up. This semaphore organizes the queueing so that
// waiting queries consume few resources.
//
// Do not request a permit in a nested resolver, since it is already holding a permit and
// requesting another could deadlock.
let _permit = if !nested_resolver {
execute_ctx.load_manager.query_permit().await
} else {
// Acquire a dummy semaphore.
Arc::new(tokio::sync::Semaphore::new(1))
.acquire_owned()
.await
};
let logger = execute_ctx.logger.clone();
let query_text = execute_ctx.query.query_text.cheap_clone();
let variables_text = execute_ctx.query.variables_text.cheap_clone();
match graph::spawn_blocking_allow_panic(move || {
let mut query_res = QueryResult::from(execute_root_selection_set_uncached(
&execute_ctx,
&execute_selection_set,
&execute_root_type,
));
// Unwrap: In practice should never fail, but if it does we will catch the panic.
execute_ctx.resolver.post_process(&mut query_res).unwrap();
Arc::new(query_res)
})
.await
{
Ok(result) => result,
Err(e) => {
let e = e.into_panic();
let e = match e
.downcast_ref::<String>()
.map(|s| s.as_str())
.or(e.downcast_ref::<&'static str>().map(|&s| s))
{
Some(e) => e.to_string(),
None => "panic is not a string".to_string(),
};
error!(
logger,
"panic when processing graphql query";
"panic" => e.to_string(),
"query" => query_text,
"variables" => variables_text,
);
Arc::new(QueryResult::from(QueryExecutionError::Panic(e)))
}
}
};
let (result, herd_hit) = if let Some(key) = key {
QUERY_HERD_CACHE.cached_query(key, run_query).await
} else {
(run_query.await, false)
};
if herd_hit {
ctx.cache_status.store(CacheStatus::Shared);
}
// Check if this query should be cached.
// Share errors from the herd cache, but don't store them in generational cache.
// In particular, there is a problem where asking for a block pointer beyond the chain
// head can cause the legitimate cache to be thrown out.
// It would be redundant to insert herd cache hits.
let no_cache = herd_hit || result.has_errors();
if let (false, Some(key), Some(block_ptr), Some(network)) =
(no_cache, key, block_ptr, &ctx.query.network)
{
// Calculate the weight outside the lock.
let weight = result.weight();
let mut cache = QUERY_BLOCK_CACHE.write().unwrap();
// Get or insert the cache for this network.
if cache.insert(
network,
block_ptr.clone(),
key,
result.cheap_clone(),
weight,
) {
ctx.cache_status.store(CacheStatus::Insert);
} else {
// Results that are too old for the QUERY_BLOCK_CACHE go into the QUERY_LFU_CACHE
let mut cache = QUERY_LFU_CACHE.lock().unwrap();
cache.evict_with_period(*QUERY_CACHE_MAX_MEM, *QUERY_CACHE_STALE_PERIOD);
cache.insert(
key,
WeightedResult {
result: result.cheap_clone(),
weight,
},
);
ctx.cache_status.store(CacheStatus::Insert);
}
}
result
}
/// Executes a selection set, requiring the result to be of the given object type.
///
/// Allows passing in a parent value during recursive processing of objects and their fields.
fn execute_selection_set<'a>(
ctx: &'a ExecutionContext<impl Resolver>,
selection_sets: impl Iterator<Item = &'a q::SelectionSet>,
object_type: &s::ObjectType,
prefetched_value: Option<q::Value>,
) -> Result<q::Value, Vec<QueryExecutionError>> {
Ok(q::Value::Object(execute_selection_set_to_map(
ctx,
selection_sets,
object_type,
prefetched_value,
)?))
}
fn execute_selection_set_to_map<'a>(
ctx: &'a ExecutionContext<impl Resolver>,
selection_sets: impl Iterator<Item = &'a q::SelectionSet>,
object_type: &s::ObjectType,
prefetched_value: Option<q::Value>,
) -> Result<BTreeMap<String, q::Value>, Vec<QueryExecutionError>> {
let mut prefetched_object = match prefetched_value {
Some(q::Value::Object(object)) => Some(object),
Some(_) => unreachable!(),
None => None,
};
let mut errors: Vec<QueryExecutionError> = Vec::new();
let mut result_map: BTreeMap<String, q::Value> = BTreeMap::new();
// Group fields with the same response key, so we can execute them together
let grouped_field_set = collect_fields(ctx, object_type, selection_sets);
// Gather fields that appear more than once with the same response key.
let multiple_response_keys = {
let mut multiple_response_keys = HashSet::new();
let mut fields = HashSet::new();
for field in grouped_field_set.iter().map(|(_, f)| f.iter()).flatten() {
if !fields.insert(field.name.as_str()) {
multiple_response_keys.insert(field.name.as_str());
}
}
multiple_response_keys
};
// Process all field groups in order
for (response_key, fields) in grouped_field_set {
match ctx.deadline {
Some(deadline) if deadline < Instant::now() => {
errors.push(QueryExecutionError::Timeout);
break;
}
_ => (),
}
// Unwrap: The query was validated to contain only valid fields.
let field = sast::get_field(object_type, &fields[0].name).unwrap();
// Check if we have the value already.
let field_value = prefetched_object
.as_mut()
.map(|o| {
// Prefetched objects are associated to `prefetch:response_key`.
if let Some(val) = o.remove(&format!("prefetch:{}", response_key)) {
return Some(val);
}
// Scalars and scalar lists are associated to the field name.
// If the field has more than one response key, we have to clone.
match multiple_response_keys.contains(fields[0].name.as_str()) {
false => o.remove(&fields[0].name),
true => o.get(&fields[0].name).cloned(),
}
})
.flatten();
match execute_field(&ctx, object_type, field_value, &fields[0], field, fields) {
Ok(v) => {
result_map.insert(response_key.to_owned(), v);
}
Err(mut e) => {
errors.append(&mut e);
}
}
}
if errors.is_empty() {
Ok(result_map)
} else {
Err(errors)
}
}
/// Collects fields from selection sets. Returns a map from response key to fields. There will
/// typically be a single field for a response key. If there are multiple, the overall execution
/// logic will effectively merged them into the output for the response key.
pub fn collect_fields<'a>(
ctx: &'a ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
selection_sets: impl Iterator<Item = &'a q::SelectionSet>,
) -> IndexMap<&'a String, Vec<&'a q::Field>> {
let mut grouped_fields = IndexMap::new();
collect_fields_inner(
ctx,
object_type,
selection_sets,
&mut HashSet::new(),
&mut grouped_fields,
);
grouped_fields
}
pub fn collect_fields_inner<'a>(
ctx: &'a ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
selection_sets: impl Iterator<Item = &'a q::SelectionSet>,
visited_fragments: &mut HashSet<&'a q::Name>,
output: &mut IndexMap<&'a String, Vec<&'a q::Field>>,
) {
for selection_set in selection_sets {
// Only consider selections that are not skipped and should be included
let selections = selection_set
.items
.iter()
.filter(|selection| !qast::skip_selection(selection, &ctx.query.variables))
.filter(|selection| qast::include_selection(selection, &ctx.query.variables));
for selection in selections {
match selection {
q::Selection::Field(ref field) => {
let response_key = qast::get_response_key(field);
output.entry(response_key).or_default().push(field);
}
q::Selection::FragmentSpread(spread) => {
// Only consider the fragment if it hasn't already been included,
// as would be the case if the same fragment spread ...Foo appeared
// twice in the same selection set.
//
// Note: This will skip both duplicate fragments and will break cycles,
// so we support fragments even though the GraphQL spec prohibits them.
if visited_fragments.insert(&spread.fragment_name) {
let fragment = ctx.query.get_fragment(&spread.fragment_name);
if does_fragment_type_apply(ctx, object_type, &fragment.type_condition) {
// We have a fragment that applies to the current object type,
// collect fields recursively
collect_fields_inner(
ctx,
object_type,
iter::once(&fragment.selection_set),
visited_fragments,
output,
);
}
}
}
q::Selection::InlineFragment(fragment) => {
let applies = match &fragment.type_condition {
Some(cond) => does_fragment_type_apply(ctx, object_type, &cond),
None => true,
};
if applies {
collect_fields_inner(
ctx,
object_type,
iter::once(&fragment.selection_set),
visited_fragments,
output,
)
}
}
};
}
}
}
/// Determines whether a fragment is applicable to the given object type.
fn does_fragment_type_apply(
ctx: &ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
fragment_type: &q::TypeCondition,
) -> bool {
// This is safe to do, as TypeCondition only has a single `On` variant.
let q::TypeCondition::On(ref name) = fragment_type;
// Resolve the type the fragment applies to based on its name
let named_type = sast::get_named_type(ctx.query.schema.document(), name);
match named_type {
// The fragment applies to the object type if its type is the same object type
Some(s::TypeDefinition::Object(ot)) => object_type == ot,
// The fragment also applies to the object type if its type is an interface
// that the object type implements
Some(s::TypeDefinition::Interface(it)) => {
object_type.implements_interfaces.contains(&it.name)
}
// The fragment also applies to an object type if its type is a union that
// the object type is one of the possible types for
Some(s::TypeDefinition::Union(ut)) => ut.types.contains(&object_type.name),
// In all other cases, the fragment does not apply
_ => false,
}
}
/// Executes a field.
fn execute_field(
ctx: &ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
field_value: Option<q::Value>,
field: &q::Field,
field_definition: &s::Field,
fields: Vec<&q::Field>,
) -> Result<q::Value, Vec<QueryExecutionError>> {
coerce_argument_values(&ctx.query, object_type, field)
.and_then(|argument_values| {
resolve_field_value(
ctx,
object_type,
field_value,
field,
field_definition,
&field_definition.field_type,
&argument_values,
)
})
.and_then(|value| complete_value(ctx, field, &field_definition.field_type, &fields, value))
}
/// Resolves the value of a field.
fn resolve_field_value(
ctx: &ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
field_value: Option<q::Value>,
field: &q::Field,
field_definition: &s::Field,
field_type: &s::Type,
argument_values: &HashMap<&q::Name, q::Value>,
) -> Result<q::Value, Vec<QueryExecutionError>> {
match field_type {
s::Type::NonNullType(inner_type) => resolve_field_value(
ctx,
object_type,
field_value,
field,
field_definition,
inner_type.as_ref(),
argument_values,
),
s::Type::NamedType(ref name) => resolve_field_value_for_named_type(
ctx,
object_type,
field_value,
field,
field_definition,
name,
argument_values,
),
s::Type::ListType(inner_type) => resolve_field_value_for_list_type(
ctx,
object_type,
field_value,
field,
field_definition,
inner_type.as_ref(),
argument_values,
),
}
}
/// Resolves the value of a field that corresponds to a named type.
fn resolve_field_value_for_named_type(
ctx: &ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
field_value: Option<q::Value>,
field: &q::Field,
field_definition: &s::Field,
type_name: &s::Name,
argument_values: &HashMap<&q::Name, q::Value>,
) -> Result<q::Value, Vec<QueryExecutionError>> {
// Try to resolve the type name into the actual type
let named_type = sast::get_named_type(ctx.query.schema.document(), type_name)
.ok_or_else(|| QueryExecutionError::NamedTypeError(type_name.to_string()))?;
match named_type {
// Let the resolver decide how the field (with the given object type) is resolved
s::TypeDefinition::Object(t) => ctx.resolver.resolve_object(
field_value,
field,
field_definition,
t.into(),
argument_values,
),
// Let the resolver decide how values in the resolved object value
// map to values of GraphQL enums
s::TypeDefinition::Enum(t) => ctx.resolver.resolve_enum_value(field, t, field_value),
// Let the resolver decide how values in the resolved object value
// map to values of GraphQL scalars
s::TypeDefinition::Scalar(t) => {
ctx.resolver
.resolve_scalar_value(object_type, field, t, field_value, argument_values)
}
s::TypeDefinition::Interface(i) => ctx.resolver.resolve_object(
field_value,
field,
field_definition,
i.into(),
argument_values,
),
s::TypeDefinition::Union(_) => Err(QueryExecutionError::Unimplemented("unions".to_owned())),
s::TypeDefinition::InputObject(_) => unreachable!("input objects are never resolved"),
}
.map_err(|e| vec![e])
}
/// Resolves the value of a field that corresponds to a list type.
fn resolve_field_value_for_list_type(
ctx: &ExecutionContext<impl Resolver>,
object_type: &s::ObjectType,
field_value: Option<q::Value>,
field: &q::Field,
field_definition: &s::Field,
inner_type: &s::Type,
argument_values: &HashMap<&q::Name, q::Value>,
) -> Result<q::Value, Vec<QueryExecutionError>> {
match inner_type {
s::Type::NonNullType(inner_type) => resolve_field_value_for_list_type(
ctx,
object_type,
field_value,
field,
field_definition,
inner_type,
argument_values,
),
s::Type::NamedType(ref type_name) => {
let named_type = sast::get_named_type(ctx.query.schema.document(), type_name)
.ok_or_else(|| QueryExecutionError::NamedTypeError(type_name.to_string()))?;
match named_type {
// Let the resolver decide how the list field (with the given item object type)
// is resolved into a entities based on the (potential) parent object
s::TypeDefinition::Object(t) => ctx
.resolver
.resolve_objects(
field_value,
field,
field_definition,
t.into(),
argument_values,
)
.map_err(|e| vec![e]),
// Let the resolver decide how values in the resolved object value
// map to values of GraphQL enums
s::TypeDefinition::Enum(t) => {
ctx.resolver.resolve_enum_values(field, &t, field_value)
}
// Let the resolver decide how values in the resolved object value
// map to values of GraphQL scalars
s::TypeDefinition::Scalar(t) => {
ctx.resolver.resolve_scalar_values(field, &t, field_value)
}
s::TypeDefinition::Interface(t) => ctx
.resolver
.resolve_objects(
field_value,
field,
field_definition,
t.into(),
argument_values,
)
.map_err(|e| vec![e]),
s::TypeDefinition::Union(_) => Err(vec![QueryExecutionError::Unimplemented(
"unions".to_owned(),
)]),
s::TypeDefinition::InputObject(_) => {
unreachable!("input objects are never resolved")
}
}
}
// We don't support nested lists yet
s::Type::ListType(_) => Err(vec![QueryExecutionError::Unimplemented(
"nested list types".to_owned(),
)]),
}
}
/// Ensures that a value matches the expected return type.
fn complete_value(
ctx: &ExecutionContext<impl Resolver>,
field: &q::Field,
field_type: &s::Type,
fields: &Vec<&q::Field>,
resolved_value: q::Value,
) -> Result<q::Value, Vec<QueryExecutionError>> {
match field_type {
// Fail if the field type is non-null but the value is null
s::Type::NonNullType(inner_type) => {
return match complete_value(ctx, field, inner_type, fields, resolved_value)? {
q::Value::Null => Err(vec![QueryExecutionError::NonNullError(
field.position,
field.name.to_string(),
)]),
v => Ok(v),
};
}
// If the resolved value is null, return null
_ if resolved_value == q::Value::Null => {
return Ok(resolved_value);
}
// Complete list values
s::Type::ListType(inner_type) => {
match resolved_value {
// Complete list values individually
q::Value::List(mut values) => {
let mut errors = Vec::new();
// To avoid allocating a new vector this completes the values in place.
for value_place in &mut values {
// Put in a placeholder, complete the value, put the completed value back.
let value = std::mem::replace(value_place, q::Value::Null);
match complete_value(ctx, field, inner_type, fields, value) {
Ok(value) => {
*value_place = value;
}
Err(errs) => errors.extend(errs),
}
}
match errors.is_empty() {
true => Ok(q::Value::List(values)),
false => Err(errors),
}
}
// Return field error if the resolved value for the list is not a list
_ => Err(vec![QueryExecutionError::ListValueError(
field.position,
field.name.to_string(),
)]),
}
}
s::Type::NamedType(name) => {
let named_type = sast::get_named_type(ctx.query.schema.document(), name).unwrap();
match named_type {
// Complete scalar values
s::TypeDefinition::Scalar(scalar_type) => {
resolved_value.coerce(scalar_type).map_err(|value| {
vec![QueryExecutionError::ScalarCoercionError(
field.position.clone(),
field.name.to_owned(),
value,
scalar_type.name.to_owned(),
)]
})
}
// Complete enum values
s::TypeDefinition::Enum(enum_type) => {
resolved_value.coerce(enum_type).map_err(|value| {
vec![QueryExecutionError::EnumCoercionError(
field.position.clone(),
field.name.to_owned(),
value,
enum_type.name.to_owned(),
enum_type
.values
.iter()
.map(|value| value.name.to_owned())
.collect(),
)]
})
}
// Complete object types recursively
s::TypeDefinition::Object(object_type) => execute_selection_set(
ctx,
fields.iter().map(|f| &f.selection_set),
object_type,
Some(resolved_value),
),
// Resolve interface types using the resolved value and complete the value recursively
s::TypeDefinition::Interface(_) => {
let object_type = resolve_abstract_type(ctx, named_type, &resolved_value)?;
execute_selection_set(
ctx,
fields.iter().map(|f| &f.selection_set),
object_type,
Some(resolved_value),
)
}
// Resolve union types using the resolved value and complete the value recursively
s::TypeDefinition::Union(_) => {
let object_type = resolve_abstract_type(ctx, named_type, &resolved_value)?;
execute_selection_set(
ctx,
fields.iter().map(|f| &f.selection_set),
object_type,
Some(resolved_value),
)
}
s::TypeDefinition::InputObject(_) => {
unreachable!("input objects are never resolved")
}
}
}
}
}
/// Resolves an abstract type (interface, union) into an object type based on the given value.
fn resolve_abstract_type<'a>(
ctx: &'a ExecutionContext<impl Resolver>,
abstract_type: &s::TypeDefinition,
object_value: &q::Value,
) -> Result<&'a s::ObjectType, Vec<QueryExecutionError>> {
// Let the resolver handle the type resolution, return an error if the resolution
// yields nothing
ctx.resolver
.resolve_abstract_type(ctx.query.schema.document(), abstract_type, object_value)
.ok_or_else(|| {
vec![QueryExecutionError::AbstractTypeError(
sast::get_type_name(abstract_type).to_string(),
)]
})
}
/// Coerces argument values into GraphQL values.
pub fn coerce_argument_values<'a>(
query: &crate::execution::Query,
ty: impl Into<ObjectOrInterface<'a>>,
field: &q::Field,
) -> Result<HashMap<&'a q::Name, q::Value>, Vec<QueryExecutionError>> {
let mut coerced_values = HashMap::new();
let mut errors = vec![];
let resolver = |name: &Name| sast::get_named_type(&query.schema.document(), name);
for argument_def in sast::get_argument_definitions(ty, &field.name)
.into_iter()
.flatten()
{
let value = qast::get_argument_value(&field.arguments, &argument_def.name).cloned();
match coercion::coerce_input_value(value, &argument_def, &resolver, &query.variables) {
Ok(Some(value)) => {
if argument_def.name == "text".to_string() {
coerced_values.insert(
&argument_def.name,
q::Value::Object(BTreeMap::from_iter(vec![(field.name.clone(), value)])),
);
} else {
coerced_values.insert(&argument_def.name, value);
}
}
Ok(None) => {}
Err(e) => errors.push(e),
}
}
if errors.is_empty() {
Ok(coerced_values)
} else {
Err(errors)
}
}
| stable_hash |
core.ts | import { createjs, loadAssetAsync as _loadAssetAsync, ILoadAssetOption, IAnimateLibrary } from '@tawaship/pixi-animate-core';
import { CreatejsMovieClip } from './MovieClip';
export { createjs, ILoadAssetOption, IAnimateLibrary } from '@tawaship/pixi-animate-core';
/**
* @ignore
*/
declare const AdobeAn: any;
export interface IPrepareTarget {
/**
* "lib.properties.id" in Animate content.
*/
id: string;
/**
* Directory path of Animate content.
*/
basepath: string;
/**
* [[https://tawaship.github.io/pixi-animate-core/interfaces/iloadassetoption.html | PixiAnimateCore.ILoadAssetOption]]
*/
options?: ILoadAssetOption;
};
/**
* Load the assets of createjs content published by Adobe Animate.
* If you use multiple contents, each composition ID must be unique.
* Please run "Pixim.animate.init" before running.
*/
export function | (targets: IPrepareTarget | IPrepareTarget[]) {
if (!Array.isArray(targets)) {
targets = [targets];
}
const promises: Promise<IAnimateLibrary>[] = [];
for (let i = 0; i < targets.length; i++) {
const target = targets[i];
const comp = AdobeAn.getComposition(target.id);
if (!comp) {
throw new Error(`no composition: ${target.id}`);
}
promises.push(_loadAssetAsync(comp, target.basepath, target.options)
.then((lib: IAnimateLibrary) => {
for (let i in lib) {
if (lib[i].prototype instanceof CreatejsMovieClip) {
lib[i].prototype._framerateBase = lib.properties.fps;
}
}
return lib;
})
);
}
return Promise.all(promises)
.then((resolvers: IAnimateLibrary[]) => {
if (resolvers.length === 1) {
return resolvers[0];
}
return resolvers;
});
}
// overrides
createjs.MovieClip = CreatejsMovieClip; | loadAssetAsync |
errors.rs | use diesel::result::Error as DieselResultError;
use iron::prelude::*;
use iron::status;
use std::error::Error;
use std::fmt;
use std::string::FromUtf8Error;
use params::ParamsError;
use time::ParseError;
#[derive(Debug)]
pub enum LughError {
BadRequest(String),
DatabaseError(String),
NotFound(String),
ParseFailed(String),
Unauthorized(String)
}
impl fmt::Display for LughError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LughError::BadRequest(ref message) |
LughError::DatabaseError(ref message) |
LughError::NotFound(ref message) |
LughError::ParseFailed(ref message) |
LughError::Unauthorized(ref message)
=> f.write_str(message),
}
}
}
impl Error for LughError {
fn description(&self) -> &str {
match *self {
LughError::BadRequest(ref message) |
LughError::DatabaseError(ref message) |
LughError::NotFound(ref message) |
LughError::ParseFailed(ref message) |
LughError::Unauthorized(ref message)
=> message.as_str(),
}
}
}
impl From<LughError> for IronError {
fn from(error: LughError) -> IronError {
match error {
LughError::BadRequest(_) => IronError::new(error, status::BadRequest),
LughError::DatabaseError(_) | LughError::ParseFailed(_) => IronError::new(error, status::InternalServerError),
LughError::NotFound(_) => IronError::new(error, status::NotFound),
LughError::Unauthorized(_) => IronError::new(error, status::Unauthorized),
}
}
}
impl PartialEq for LughError {
fn eq(&self, other: &LughError) -> bool {
self.description() == other.description()
}
}
impl From<DieselConnectionError> for LughError {
fn from(_: DieselConnectionError) -> LughError {
LughError::DatabaseError("Diesel connection error".to_string())
}
}
impl From<DieselResultError> for LughError {
fn from(_: DieselResultError) -> LughError {
LughError::DatabaseError("Diesel result error".to_string())
}
}
impl From<FromUtf8Error> for LughError {
fn from(_: FromUtf8Error) -> LughError {
LughError::ParseFailed("Parse from UTF8 error".to_string())
}
}
impl From<ParamsError> for LughError {
fn from(error: ParamsError) -> LughError {
LughError::BadRequest(error.description().to_string())
}
}
impl From<ParseError> for LughError {
fn from(_: ParseError) -> LughError {
LughError::ParseFailed("Parse error".to_string())
}
} | use diesel::ConnectionError as DieselConnectionError; |
|
env_shell.py | import ast
import json
import readline
from cliff.command import Command
import call_server as server
class EnvironmentShell(Command):
def get_parser(self, prog_name):
parser = super(EnvironmentShell, self).get_parser(prog_name)
parser.add_argument(dest='env_name',
help="Environment name")
return parser
def | (self, parsed_args):
env_name = parsed_args.env_name
response = server.TakeAction().get_environment(env_name)
if response:
response_json = json.loads(response)
env_output_config = ast.literal_eval(response_json['data']['env_definition'])
type = env_output_config['environment']['app_deployment']['type']
if type == 'local-docker':
print("Shell functionality not available for local deployment target.")
print("You can use docker commands from command-line instead.")
exit()
if response_json['data']['status'] == 'available':
while True:
command_string = raw_input('("exit" to quit, "help" to see commands) cld>')
command_string = command_string.strip()
if command_string == 'exit':
break
print("Running the command %s in the environment..." % command_string)
response = server.TakeAction().run_command(env_name, command_string)
print(response)
else:
print("Environment %s is not in appropriate state." % env_name)
| take_action |
train.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: train.py
import argparse
import itertools
import numpy as np
import os
import cv2
import six
import shutil
assert six.PY3, "FasterRCNN requires Python 3!"
import tensorflow as tf
import tqdm
import tensorpack.utils.viz as tpviz
from tensorpack import *
from tensorpack.tfutils import optimizer
from tensorpack.tfutils.common import get_tf_version_tuple, get_tensors_by_names
from tensorpack.tfutils.summary import add_moving_summary
from tensorpack.tfutils.varreplace import freeze_variables
import model_frcnn
import model_mrcnn
from basemodel import image_preprocess, resnet_c4_backbone, resnet_conv5, resnet_fpn_backbone, backbone_scope
from dataset import DetectionDataset
from config import finalize_configs, config as cfg
from data import get_all_anchors, get_all_anchors_fpn, get_train_dataflow
from eval_utils import EvalCallback
from model_box import RPNAnchors, clip_boxes, crop_and_resize, roi_align
from model_cascade import CascadeRCNNHead, CascadeRCNNHeadWithHardExamples
from model_fpn import fpn_model, generate_fpn_proposals, multilevel_roi_align, multilevel_rpn_losses
from model_frcnn import BoxProposals, FastRCNNHead, fastrcnn_outputs, fastrcnn_predictions, sample_fast_rcnn_targets
from model_mrcnn import maskrcnn_loss, maskrcnn_upXconv_head
from model_rpn import generate_rpn_proposals, rpn_head, rpn_losses
try:
import horovod.tensorflow as hvd
except ImportError:
pass
class DetectionModel(ModelDesc):
def | (self, image):
image = tf.expand_dims(image, 0)
image = image_preprocess(image, bgr=True)
return tf.transpose(image, [0, 3, 1, 2])
@property
def training(self):
return get_current_tower_context().is_training
def optimizer(self):
lr = tf.get_variable('learning_rate', initializer=0.003, trainable=False)
tf.summary.scalar('learning_rate-summary', lr)
# The learning rate in the config is set for 8 GPUs, and we use trainers with average=False.
lr = lr / 8.
opt = tf.train.MomentumOptimizer(lr, 0.9)
if cfg.TRAIN.NUM_GPUS < 8:
opt = optimizer.AccumGradOptimizer(opt, 8 // cfg.TRAIN.NUM_GPUS)
return opt
def get_inference_tensor_names(self):
"""
Returns two lists of tensor names to be used to create an inference callable.
Returns:
[str]: input names
[str]: output names
"""
if cfg.MODE_THIRD_STAGE:
out = ['output/boxes', 'output/scores', 'third_stage_features_out', 'ff_gt_tracklet_scores',
'sparse_tracklet_scores', 'tracklet_score_indices']
else:
out = ['output/boxes', 'output/scores', 'output/labels']
if cfg.MODE_MASK:
out.append('output/masks')
if cfg.EXTRACT_GT_FEATURES:
return ['image', 'roi_boxes'], ['boxes_for_extraction', 'features_for_extraction']
else:
return ['image'], out
def build_graph(self, *inputs):
inputs = dict(zip(self.input_names, inputs))
image = self.preprocess(inputs['image']) # 1CHW
features = self.backbone(image)
anchor_inputs = {k: v for k, v in inputs.items() if k.startswith('anchor_')}
if cfg.EXTRACT_GT_FEATURES:
anchor_inputs["roi_boxes"] = inputs["roi_boxes"]
proposals, rpn_losses = self.rpn(image, features, anchor_inputs) # inputs?
targets = [inputs[k] for k in ['gt_boxes', 'gt_labels', 'gt_masks'] if k in inputs]
head_losses = self.roi_heads(image, features, proposals, targets)
if self.training:
wd_cost = regularize_cost(
'.*/W', l2_regularizer(cfg.TRAIN.WEIGHT_DECAY), name='wd_cost')
total_cost = tf.add_n(
rpn_losses + head_losses + [wd_cost], 'total_cost')
add_moving_summary(total_cost, wd_cost)
return total_cost
class ResNetC4Model(DetectionModel):
def inputs(self):
ret = [
tf.placeholder(tf.float32, (None, None, 3), 'image'),
tf.placeholder(tf.int32, (None, None, cfg.RPN.NUM_ANCHOR), 'anchor_labels'),
tf.placeholder(tf.float32, (None, None, cfg.RPN.NUM_ANCHOR, 4), 'anchor_boxes'),
tf.placeholder(tf.float32, (None, 4), 'gt_boxes'),
tf.placeholder(tf.int64, (None,), 'gt_labels')] # all > 0
if cfg.MODE_MASK:
ret.append(
tf.placeholder(tf.uint8, (None, None, None), 'gt_masks')
) # NR_GT x height x width
return ret
def backbone(self, image):
return [resnet_c4_backbone(image, cfg.BACKBONE.RESNET_NUM_BLOCKS[:3])]
def rpn(self, image, features, inputs):
featuremap = features[0]
rpn_label_logits, rpn_box_logits = rpn_head('rpn', featuremap, cfg.RPN.HEAD_DIM, cfg.RPN.NUM_ANCHOR)
anchors = RPNAnchors(get_all_anchors(), inputs['anchor_labels'], inputs['anchor_boxes'])
anchors = anchors.narrow_to(featuremap)
image_shape2d = tf.shape(image)[2:] # h,w
pred_boxes_decoded = anchors.decode_logits(rpn_box_logits) # fHxfWxNAx4, floatbox
proposal_boxes, proposal_scores = generate_rpn_proposals(
tf.reshape(pred_boxes_decoded, [-1, 4]),
tf.reshape(rpn_label_logits, [-1]),
image_shape2d,
cfg.RPN.TRAIN_PRE_NMS_TOPK if self.training else cfg.RPN.TEST_PRE_NMS_TOPK,
cfg.RPN.TRAIN_POST_NMS_TOPK if self.training else cfg.RPN.TEST_POST_NMS_TOPK)
if self.training:
losses = rpn_losses(
anchors.gt_labels, anchors.encoded_gt_boxes(), rpn_label_logits, rpn_box_logits)
else:
losses = []
return BoxProposals(proposal_boxes), losses
def roi_heads(self, image, features, proposals, targets):
image_shape2d = tf.shape(image)[2:] # h,w
featuremap = features[0]
gt_boxes, gt_labels, *_ = targets
if self.training:
# sample proposal boxes in training
proposals = sample_fast_rcnn_targets(proposals.boxes, gt_boxes, gt_labels)
# The boxes to be used to crop RoIs.
# Use all proposal boxes in inference
boxes_on_featuremap = proposals.boxes * (1.0 / cfg.RPN.ANCHOR_STRIDE)
roi_resized = roi_align(featuremap, boxes_on_featuremap, 14)
feature_fastrcnn = resnet_conv5(roi_resized, cfg.BACKBONE.RESNET_NUM_BLOCKS[-1]) # nxcx7x7
# Keep C5 feature to be shared with mask branch
feature_gap = GlobalAvgPooling('gap', feature_fastrcnn, data_format='channels_first')
fastrcnn_label_logits, fastrcnn_box_logits = fastrcnn_outputs('fastrcnn', feature_gap, cfg.DATA.NUM_CLASS)
fastrcnn_head = FastRCNNHead(proposals, fastrcnn_box_logits, fastrcnn_label_logits, gt_boxes,
tf.constant(cfg.FRCNN.BBOX_REG_WEIGHTS, dtype=tf.float32))
if self.training:
all_losses = fastrcnn_head.losses()
if cfg.MODE_MASK:
gt_masks = targets[2]
# maskrcnn loss
# In training, mask branch shares the same C5 feature.
fg_feature = tf.gather(feature_fastrcnn, proposals.fg_inds())
mask_logits = maskrcnn_upXconv_head(
'maskrcnn', fg_feature, cfg.DATA.NUM_CATEGORY, num_convs=0) # #fg x #cat x 14x14
target_masks_for_fg = crop_and_resize(
tf.expand_dims(gt_masks, 1),
proposals.fg_boxes(),
proposals.fg_inds_wrt_gt, 14,
pad_border=False) # nfg x 1x14x14
target_masks_for_fg = tf.squeeze(target_masks_for_fg, 1, 'sampled_fg_mask_targets')
all_losses.append(maskrcnn_loss(mask_logits, proposals.fg_labels(), target_masks_for_fg))
return all_losses
else:
decoded_boxes = fastrcnn_head.decoded_output_boxes()
decoded_boxes = clip_boxes(decoded_boxes, image_shape2d, name='fastrcnn_all_boxes')
label_scores = fastrcnn_head.output_scores(name='fastrcnn_all_scores')
final_boxes, final_scores, final_labels = fastrcnn_predictions(
decoded_boxes, label_scores, name_scope='output')
if cfg.MODE_MASK:
roi_resized = roi_align(featuremap, final_boxes * (1.0 / cfg.RPN.ANCHOR_STRIDE), 14)
feature_maskrcnn = resnet_conv5(roi_resized, cfg.BACKBONE.RESNET_NUM_BLOCKS[-1])
mask_logits = maskrcnn_upXconv_head(
'maskrcnn', feature_maskrcnn, cfg.DATA.NUM_CATEGORY, 0) # #result x #cat x 14x14
indices = tf.stack([tf.range(tf.size(final_labels)), tf.cast(final_labels, tf.int32) - 1], axis=1)
final_mask_logits = tf.gather_nd(mask_logits, indices) # #resultx14x14
tf.sigmoid(final_mask_logits, name='output/masks')
return []
class ResNetFPNModel(DetectionModel):
def inputs(self):
ret = [
tf.placeholder(tf.float32, (None, None, 3), 'image')]
num_anchors = len(cfg.RPN.ANCHOR_RATIOS)
for k in range(len(cfg.FPN.ANCHOR_STRIDES)):
ret.extend([
tf.placeholder(tf.int32, (None, None, num_anchors),
'anchor_labels_lvl{}'.format(k + 2)),
tf.placeholder(tf.float32, (None, None, num_anchors, 4),
'anchor_boxes_lvl{}'.format(k + 2))])
ret.extend([
tf.placeholder(tf.float32, (None, 4), 'gt_boxes'),
tf.placeholder(tf.int64, (None,), 'gt_labels')]) # all > 0
if cfg.MODE_MASK:
ret.append(
tf.placeholder(tf.uint8, (None, None, None), 'gt_masks')
) # NR_GT x height x width
if cfg.EXTRACT_GT_FEATURES:
ret.append(tf.placeholder(tf.float32, (None, 4,), 'roi_boxes'))
return ret
def slice_feature_and_anchors(self, p23456, anchors):
for i, stride in enumerate(cfg.FPN.ANCHOR_STRIDES):
with tf.name_scope('FPN_slice_lvl{}'.format(i)):
anchors[i] = anchors[i].narrow_to(p23456[i])
def backbone(self, image):
c2345 = resnet_fpn_backbone(image, cfg.BACKBONE.RESNET_NUM_BLOCKS)
p23456 = fpn_model('fpn', c2345)
return p23456
def rpn(self, image, features, inputs):
if cfg.EXTRACT_GT_FEATURES:
boxes = inputs['roi_boxes']
return BoxProposals(boxes), tf.constant(0, dtype=tf.float32)
assert len(cfg.RPN.ANCHOR_SIZES) == len(cfg.FPN.ANCHOR_STRIDES)
image_shape2d = tf.shape(image)[2:] # h,w
all_anchors_fpn = get_all_anchors_fpn()
multilevel_anchors = [RPNAnchors(
all_anchors_fpn[i],
inputs['anchor_labels_lvl{}'.format(i + 2)],
inputs['anchor_boxes_lvl{}'.format(i + 2)]) for i in range(len(all_anchors_fpn))]
self.slice_feature_and_anchors(features, multilevel_anchors)
# Multi-Level RPN Proposals
rpn_outputs = [rpn_head('rpn', pi, cfg.FPN.NUM_CHANNEL, len(cfg.RPN.ANCHOR_RATIOS))
for pi in features]
multilevel_label_logits = [k[0] for k in rpn_outputs]
multilevel_box_logits = [k[1] for k in rpn_outputs]
multilevel_pred_boxes = [anchor.decode_logits(logits)
for anchor, logits in zip(multilevel_anchors, multilevel_box_logits)]
proposal_boxes, proposal_scores = generate_fpn_proposals(
multilevel_pred_boxes, multilevel_label_logits, image_shape2d)
if self.training:
losses = multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits)
else:
losses = []
return BoxProposals(proposal_boxes), losses
def roi_heads(self, image, features, proposals, targets):
image_shape2d = tf.shape(image)[2:] # h,w
assert len(features) == 5, "Features have to be P23456!"
gt_boxes, gt_labels, *_ = targets
if self.training:
proposals = sample_fast_rcnn_targets(proposals.boxes, gt_boxes, gt_labels)
fastrcnn_head_func = getattr(model_frcnn, cfg.FPN.FRCNN_HEAD_FUNC)
if not cfg.FPN.CASCADE:
roi_feature_fastrcnn = multilevel_roi_align(features[:4], proposals.boxes, 7)
head_feature = fastrcnn_head_func('fastrcnn', roi_feature_fastrcnn)
fastrcnn_label_logits, fastrcnn_box_logits = fastrcnn_outputs(
'fastrcnn/outputs', head_feature, cfg.DATA.NUM_CLASS)
fastrcnn_head = FastRCNNHead(proposals, fastrcnn_box_logits, fastrcnn_label_logits,
gt_boxes, tf.constant(cfg.FRCNN.BBOX_REG_WEIGHTS, dtype=tf.float32))
else:
def roi_func(boxes):
return multilevel_roi_align(features[:4], boxes, 7)
fastrcnn_head = CascadeRCNNHead(
proposals, roi_func, fastrcnn_head_func,
(gt_boxes, gt_labels), image_shape2d, cfg.DATA.NUM_CLASS)
if cfg.EXTRACT_GT_FEATURES:
roi_feature_fastrcnn = multilevel_roi_align(features[:4], proposals.boxes, 7)
tf.identity(roi_feature_fastrcnn, "rpn/feature")
if self.training:
all_losses = fastrcnn_head.losses()
if cfg.MODE_MASK:
gt_masks = targets[2]
# maskrcnn loss
roi_feature_maskrcnn = multilevel_roi_align(
features[:4], proposals.fg_boxes(), 14,
name_scope='multilevel_roi_align_mask')
maskrcnn_head_func = getattr(model_mrcnn, cfg.FPN.MRCNN_HEAD_FUNC)
mask_logits = maskrcnn_head_func(
'maskrcnn', roi_feature_maskrcnn, cfg.DATA.NUM_CATEGORY) # #fg x #cat x 28 x 28
target_masks_for_fg = crop_and_resize(
tf.expand_dims(gt_masks, 1),
proposals.fg_boxes(),
proposals.fg_inds_wrt_gt, 28,
pad_border=False) # fg x 1x28x28
target_masks_for_fg = tf.squeeze(target_masks_for_fg, 1, 'sampled_fg_mask_targets')
all_losses.append(maskrcnn_loss(mask_logits, proposals.fg_labels(), target_masks_for_fg))
return all_losses
else:
decoded_boxes = fastrcnn_head.decoded_output_boxes()
decoded_boxes = clip_boxes(decoded_boxes, image_shape2d, name='fastrcnn_all_boxes')
label_scores = fastrcnn_head.output_scores(name='fastrcnn_all_scores')
final_boxes, final_scores, final_labels = fastrcnn_predictions(
decoded_boxes, label_scores, name_scope='output')
if cfg.MODE_MASK:
# Cascade inference needs roi transform with refined boxes.
roi_feature_maskrcnn = multilevel_roi_align(features[:4], final_boxes, 14)
maskrcnn_head_func = getattr(model_mrcnn, cfg.FPN.MRCNN_HEAD_FUNC)
mask_logits = maskrcnn_head_func(
'maskrcnn', roi_feature_maskrcnn, cfg.DATA.NUM_CATEGORY) # #fg x #cat x 28 x 28
indices = tf.stack([tf.range(tf.size(final_labels)), tf.cast(final_labels, tf.int32) - 1], axis=1)
final_mask_logits = tf.gather_nd(mask_logits, indices) # #resultx28x28
tf.sigmoid(final_mask_logits, name='output/masks')
return []
class ResNetFPNTrackModel(ResNetFPNModel):
def inputs(self):
ret = super().inputs()
if cfg.USE_PRECOMPUTED_REF_FEATURES:
ret.append(tf.placeholder(tf.float32, (256, 7, 7), 'ref_features'))
else:
ret.append(tf.placeholder(tf.float32, (None, None, 3), 'ref_image'))
ret.append(tf.placeholder(tf.float32, (4,), 'ref_box'))
if cfg.MODE_THIRD_STAGE:
ret.append(tf.placeholder(tf.float32, (256, 7, 7), 'ff_gt_tracklet_feat'))
ret.append(tf.placeholder(tf.float32, (None, 256, 7, 7), 'active_tracklets_feats'))
ret.append(tf.placeholder(tf.float32, (None, 4), 'active_tracklets_boxes'))
ret.append(tf.placeholder(tf.float32, (), 'tracklet_distance_threshold'))
if cfg.MODE_HARD_MINING:
ret.append(tf.placeholder(tf.float32, (None, 3, 256, 7, 7), 'hard_negative_features'))
if cfg.MODE_IF_HARD_MINING_THEN_ALSO_POSITIVES:
ret.append(tf.placeholder(tf.float32, (None, 3, 256, 7, 7), 'hard_positive_features'))
ret.append(tf.placeholder(tf.float32, (None, 3), 'hard_positive_ious'))
ret.append(tf.placeholder(tf.float32, (None, 4), 'hard_positive_gt_boxes'))
ret.append(tf.placeholder(tf.float32, (None, 3, 4), 'hard_positive_jitter_boxes'))
if cfg.EXTRACT_GT_FEATURES:
ret.append(tf.placeholder(tf.float32, (None, 4,), 'roi_boxes'))
return ret
def backbone(self, image):
c2345 = resnet_fpn_backbone(image, cfg.BACKBONE.RESNET_NUM_BLOCKS)
with backbone_scope(freeze=cfg.BACKBONE.FREEZE_AT > 3):
p23456 = fpn_model('fpn', c2345)
return p23456, c2345
def rpn(self, image, features, inputs):
if cfg.EXTRACT_GT_FEATURES:
boxes = inputs['roi_boxes']
return BoxProposals(boxes), tf.constant(0, dtype=tf.float32)
if cfg.BACKBONE.FREEZE_AT > 3:
with freeze_variables(stop_gradient=False, skip_collection=True):
return super().rpn(image, features, inputs)
else:
return super().rpn(image, features, inputs)
def roi_heads(self, image, ref_features, ref_box, features, proposals, targets, hard_negative_features=None,
hard_positive_features=None, hard_positive_ious=None, hard_positive_gt_boxes=None,
hard_positive_jitter_boxes=None, precomputed_ref_features=None):
image_shape2d = tf.shape(image)[2:] # h,w
assert len(features) == 5, "Features have to be P23456!"
gt_boxes, gt_labels, *_ = targets
if self.training:
proposals = sample_fast_rcnn_targets(proposals.boxes, gt_boxes, gt_labels)
fastrcnn_head_func = getattr(model_frcnn, cfg.FPN.FRCNN_HEAD_FUNC)
if precomputed_ref_features is None:
roi_aligned_ref_features = multilevel_roi_align(ref_features[:4], ref_box[tf.newaxis], 7)
else:
roi_aligned_ref_features = precomputed_ref_features[tf.newaxis]
if cfg.MODE_SHARED_CONV_REDUCE:
scope = tf.get_variable_scope()
else:
scope = ""
assert cfg.FPN.CASCADE
def roi_func(boxes, already_aligned_features=None):
if already_aligned_features is None:
aligned_features = multilevel_roi_align(features[:4], boxes, 7)
else:
# for hard example mining
aligned_features = already_aligned_features
tiled = tf.tile(roi_aligned_ref_features, [tf.shape(aligned_features)[0], 1, 1, 1])
concat_features = tf.concat((tiled, aligned_features), axis=1)
with argscope(Conv2D, data_format='channels_first',
kernel_initializer=tf.variance_scaling_initializer(
scale=2.0, mode='fan_out',
distribution='untruncated_normal' if get_tf_version_tuple() >= (1, 12) else 'normal')):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
reduced_features = Conv2D('conv_reduce', concat_features, 256, 1, activation=None)
return reduced_features
if cfg.MODE_HARD_MINING and self.training:
fastrcnn_head = CascadeRCNNHeadWithHardExamples(
proposals, roi_func, fastrcnn_head_func,
(gt_boxes, gt_labels), image_shape2d, cfg.DATA.NUM_CLASS, hard_negative_features,
hard_positive_features, cfg.HARD_NEGATIVE_LOSS_SCALING_FACTOR,
cfg.HARD_POSITIVE_LOSS_SCALING_FACTOR, hard_positive_ious, hard_positive_gt_boxes,
hard_positive_jitter_boxes)
else:
fastrcnn_head = CascadeRCNNHead(
proposals, roi_func, fastrcnn_head_func,
(gt_boxes, gt_labels), image_shape2d, cfg.DATA.NUM_CLASS)
if cfg.EXTRACT_GT_FEATURES:
# get boxes and features for each of the three cascade stages!
b0 = proposals.boxes
b1, b2, _ = fastrcnn_head._cascade_boxes
f0 = multilevel_roi_align(features[:4], b0, 7)
f1 = multilevel_roi_align(features[:4], b1, 7)
f2 = multilevel_roi_align(features[:4], b2, 7)
tf.concat([b0, b1, b2], axis=0, name="boxes_for_extraction")
tf.concat([f0, f1, f2], axis=0, name="features_for_extraction")
if self.training:
all_losses = fastrcnn_head.losses()
if cfg.MODE_MASK:
gt_masks = targets[2]
# maskrcnn loss
roi_feature_maskrcnn = multilevel_roi_align(
features[:4], proposals.fg_boxes(), 14,
name_scope='multilevel_roi_align_mask')
maskrcnn_head_func = getattr(model_mrcnn, cfg.FPN.MRCNN_HEAD_FUNC)
mask_logits = maskrcnn_head_func(
'maskrcnn', roi_feature_maskrcnn, cfg.DATA.NUM_CATEGORY) # #fg x #cat x 28 x 28
target_masks_for_fg = crop_and_resize(
tf.expand_dims(gt_masks, 1),
proposals.fg_boxes(),
proposals.fg_inds_wrt_gt, 28,
pad_border=False) # fg x 1x28x28
target_masks_for_fg = tf.squeeze(target_masks_for_fg, 1, 'sampled_fg_mask_targets')
all_losses.append(maskrcnn_loss(mask_logits, proposals.fg_labels(), target_masks_for_fg))
if cfg.MEASURE_IOU_DURING_TRAINING:
decoded_boxes = fastrcnn_head.decoded_output_boxes()
decoded_boxes = clip_boxes(decoded_boxes, image_shape2d, name='fastrcnn_all_boxes')
label_scores = fastrcnn_head.output_scores(name='fastrcnn_all_scores')
final_boxes, final_scores, final_labels = fastrcnn_predictions(
decoded_boxes, label_scores, name_scope='output_train')
# if predictions are empty, this might break...
# to prevent, stack dummy box
boxes_for_iou = tf.concat([final_boxes[:1], tf.constant([[0.0, 0.0, 1.0, 1.0]],
dtype=tf.float32)], axis=0)
from examples.FasterRCNN.utils.box_ops import pairwise_iou
iou_at_1 = tf.identity(pairwise_iou(gt_boxes[:1], boxes_for_iou)[0, 0], name="train_iou_at_1")
add_moving_summary(iou_at_1)
return all_losses
else:
decoded_boxes = fastrcnn_head.decoded_output_boxes()
decoded_boxes = clip_boxes(decoded_boxes, image_shape2d, name='fastrcnn_all_boxes')
label_scores = fastrcnn_head.output_scores(name='fastrcnn_all_scores')
final_boxes, final_scores, final_labels = fastrcnn_predictions(
decoded_boxes, label_scores, name_scope='output')
if cfg.MODE_MASK:
# Cascade inference needs roi transform with refined boxes.
roi_feature_maskrcnn = multilevel_roi_align(features[:4], final_boxes, 14)
maskrcnn_head_func = getattr(model_mrcnn, cfg.FPN.MRCNN_HEAD_FUNC)
mask_logits = maskrcnn_head_func(
'maskrcnn', roi_feature_maskrcnn, cfg.DATA.NUM_CATEGORY) # #fg x #cat x 28 x 28
indices = tf.stack([tf.range(tf.size(final_labels)), tf.cast(final_labels, tf.int32) - 1], axis=1)
final_mask_logits = tf.gather_nd(mask_logits, indices) # #resultx28x28
tf.sigmoid(final_mask_logits, name='output/masks')
return []
def build_graph(self, *inputs):
inputs = dict(zip(self.input_names, inputs))
image = self.preprocess(inputs['image']) # 1CHW
fpn_features, backbone_features = self.backbone(image)
if cfg.USE_PRECOMPUTED_REF_FEATURES:
ref_features = None
ref_box = None
else:
ref_image = self.preprocess(inputs['ref_image']) # 1CHW
ref_box = inputs['ref_box']
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
ref_features, _ = self.backbone(ref_image)
anchor_inputs = {k: v for k, v in inputs.items() if k.startswith('anchor_')}
if cfg.EXTRACT_GT_FEATURES:
anchor_inputs["roi_boxes"] = inputs["roi_boxes"]
proposals, rpn_losses = self.rpn(image, fpn_features, anchor_inputs) # inputs?
second_stage_features = fpn_features
targets = [inputs[k] for k in ['gt_boxes', 'gt_labels', 'gt_masks'] if k in inputs]
hard_negative_features = None
hard_positive_features = None
hard_positive_ious = None
hard_positive_gt_boxes = None
hard_positive_jitter_boxes = None
if cfg.MODE_HARD_MINING:
hard_negative_features = inputs['hard_negative_features']
if cfg.MODE_IF_HARD_MINING_THEN_ALSO_POSITIVES:
hard_positive_features = inputs['hard_positive_features']
hard_positive_ious = inputs['hard_positive_ious']
hard_positive_gt_boxes = inputs['hard_positive_gt_boxes']
hard_positive_jitter_boxes = inputs['hard_positive_jitter_boxes']
precomputed_ref_features = None
if cfg.USE_PRECOMPUTED_REF_FEATURES:
precomputed_ref_features = inputs['ref_features']
# Extend proposals by previous frame detections
if not self.training and cfg.MODE_THIRD_STAGE and cfg.EXTEND_PROPOSALS_BY_ACTIVE_TRACKLETS:
proposal_boxes = proposals.boxes
tracklet_boxes = inputs['active_tracklets_boxes']
concat_boxes = tf.concat([proposal_boxes, tracklet_boxes], axis=0)
proposals = BoxProposals(concat_boxes)
head_losses = self.roi_heads(image, ref_features, ref_box, second_stage_features, proposals, targets,
hard_negative_features, hard_positive_features, hard_positive_ious,
hard_positive_gt_boxes, hard_positive_jitter_boxes,
precomputed_ref_features=precomputed_ref_features)
if cfg.MODE_THIRD_STAGE:
self._run_third_stage(inputs, second_stage_features, tf.shape(image)[2:4])
if self.training:
wd_cost = regularize_cost(
'.*/W', l2_regularizer(cfg.TRAIN.WEIGHT_DECAY), name='wd_cost')
total_cost = tf.add_n(
rpn_losses + head_losses + [wd_cost], 'total_cost')
add_moving_summary(total_cost, wd_cost)
return total_cost
def _run_third_stage(self, inputs, second_stage_features, image_hw):
boxes, scores = get_tensors_by_names(['output/boxes', 'output/scores'])
# let's fix (as in finalize) the boxes, so we can roi align only one time
aligned_features_curr = multilevel_roi_align(second_stage_features[:4], boxes, 7)
# these also need to be extracted!
aligned_features_curr = tf.identity(aligned_features_curr, name='third_stage_features_out')
ff_gt_tracklet_scores, _ = self._score_for_third_stage(ref_feats=inputs['ff_gt_tracklet_feat'][tf.newaxis],
det_feats=aligned_features_curr)
tf.identity(ff_gt_tracklet_scores, name='ff_gt_tracklet_scores')
sparse_tracklet_scores, tracklet_score_indices = self._score_for_third_stage(
ref_feats=inputs['active_tracklets_feats'], det_feats=aligned_features_curr,
dense=False, ref_boxes=inputs['active_tracklets_boxes'], det_boxes=boxes, image_hw=image_hw,
tracklet_distance_threshold=inputs['tracklet_distance_threshold'])
tf.identity(sparse_tracklet_scores, name='sparse_tracklet_scores')
tf.identity(tracklet_score_indices, name='tracklet_score_indices')
def _score_for_third_stage(self, ref_feats, det_feats, dense=True, ref_boxes=None, det_boxes=None, image_hw=None,
tracklet_distance_threshold=0.08):
# build all pairs
n_refs = tf.shape(ref_feats)[0]
n_dets = tf.shape(det_feats)[0]
active_tracklets_tiled = tf.tile(ref_feats[:, tf.newaxis], multiples=[1, n_dets, 1, 1, 1])
dets_tiled = tf.tile(det_feats[tf.newaxis], multiples=[n_refs, 1, 1, 1, 1])
concated = tf.concat([active_tracklets_tiled, dets_tiled], axis=2)
if not dense:
# use boxes to prune the connectivity
assert ref_boxes is not None
assert det_boxes is not None
assert image_hw is not None
def xyxy_to_cxcywh(boxes_xyxy):
wh = boxes_xyxy[:, 2:] - boxes_xyxy[:, :2]
c = boxes_xyxy[:, :2] + wh / 2
boxes_cwh = tf.concat((c, wh), axis=1)
return boxes_cwh
active_tracklets_boxes_cxcywh = xyxy_to_cxcywh(ref_boxes)
boxes_cxcywh = xyxy_to_cxcywh(det_boxes)
# normalize by image size
h = image_hw[0]
w = image_hw[1]
norm = tf.cast(tf.stack([w, h, w, h], axis=0), tf.float32)
diffs = tf.abs(active_tracklets_boxes_cxcywh[:, tf.newaxis] - boxes_cxcywh[tf.newaxis]) / norm[
tf.newaxis, tf.newaxis]
# use distances of boxes, first frame scores ("scores") to prune
thresholds = tf.stack([tracklet_distance_threshold] * 4, axis=0)
keep_mask = tf.reduce_all(diffs < thresholds, axis=2)
indices = tf.where(keep_mask)
flattened = tf.boolean_mask(concated, keep_mask)
else:
indices = None
flattened = tf.reshape(
concated, [tf.shape(concated)[0] * tf.shape(concated)[1]] + [int(x) for x in concated.shape[2:]])
fastrcnn_head_func = getattr(model_frcnn, cfg.FPN.FRCNN_HEAD_FUNC)
if cfg.MODE_SHARED_CONV_REDUCE:
scope = tf.get_variable_scope()
else:
scope = ""
all_posteriors = []
# do this for every cascade stage
for idx in range(3):
with tf.variable_scope('cascade_rcnn_stage{}'.format(idx + 1), reuse=True):
with argscope(Conv2D, data_format='channels_first'):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
reduced_features = Conv2D('conv_reduce', flattened, 256, 1, activation=None)
head_feats = fastrcnn_head_func('head', reduced_features)
with tf.variable_scope('outputs_new', reuse=True):
classification = FullyConnected('class', head_feats, 2)
posteriors = tf.nn.softmax(classification)
all_posteriors.append(posteriors)
posteriors = (all_posteriors[0] + all_posteriors[1] + all_posteriors[2]) / tf.constant(3.0, dtype=tf.float32)
scores = posteriors[:, 1]
return scores, indices
def get_inference_tensor_names(self):
inp, out = super().get_inference_tensor_names()
if cfg.USE_PRECOMPUTED_REF_FEATURES:
inp.append('ref_features')
else:
inp.append('ref_image')
inp.append('ref_box')
if cfg.MODE_THIRD_STAGE:
inp.append('ff_gt_tracklet_feat')
inp.append('active_tracklets_feats')
inp.append('active_tracklets_boxes')
inp.append('tracklet_distance_threshold')
return inp, out
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--load', help='load a model for evaluation or training. Can overwrite BACKBONE.WEIGHTS')
parser.add_argument('--logdir', help='log directory', default='train_log/siamrcnn')
parser.add_argument('--config', help="A list of KEY=VALUE to overwrite those defined in config.py",
nargs='+')
if get_tf_version_tuple() < (1, 6):
# https://github.com/tensorflow/tensorflow/issues/14657
logger.warn("TF<1.6 has a bug which may lead to crash in FasterRCNN if you're unlucky.")
args = parser.parse_args()
if args.config:
cfg.update_args(args.config)
MODEL = ResNetFPNTrackModel()
DetectionDataset() # initialize the config with information from our dataset
is_horovod = cfg.TRAINER == 'horovod'
if is_horovod:
hvd.init()
logger.info("Horovod Rank={}, Size={}".format(hvd.rank(), hvd.size()))
if not is_horovod or hvd.rank() == 0:
# keep the old log folder if already existing! (before it would just delete it)
logger.set_logger_dir(args.logdir, 'k')
# logger.set_logger_dir(args.logdir, 'd')
finalize_configs(is_training=True)
stepnum = cfg.TRAIN.STEPS_PER_EPOCH
# warmup is step based, lr is epoch based
init_lr = cfg.TRAIN.WARMUP_INIT_LR * min(8. / cfg.TRAIN.NUM_GPUS, 1.)
warmup_schedule = [(0, init_lr), (cfg.TRAIN.WARMUP, cfg.TRAIN.BASE_LR)]
warmup_end_epoch = cfg.TRAIN.WARMUP * 1. / stepnum
lr_schedule = [(int(warmup_end_epoch + 0.5), cfg.TRAIN.BASE_LR)]
factor = 8. / cfg.TRAIN.NUM_GPUS
for idx, steps in enumerate(cfg.TRAIN.LR_SCHEDULE[:-1]):
mult = 0.1 ** (idx + 1)
lr_schedule.append(
(steps * factor // stepnum, cfg.TRAIN.BASE_LR * mult))
logger.info("Warm Up Schedule (steps, value): " + str(warmup_schedule))
logger.info("LR Schedule (epochs, value): " + str(lr_schedule))
train_dataflow = get_train_dataflow()
# This is what's commonly referred to as "epochs"
total_passes = cfg.TRAIN.LR_SCHEDULE[-1] * 8 / train_dataflow.size()
logger.info("Total passes of the training set is: {:.5g}".format(total_passes))
callbacks = [
PeriodicCallback(
ModelSaver(max_to_keep=10, keep_checkpoint_every_n_hours=1),
# every_k_epochs=1),
every_k_epochs=20),
# linear warmup
ScheduledHyperParamSetter(
'learning_rate', warmup_schedule, interp='linear', step_based=True),
ScheduledHyperParamSetter('learning_rate', lr_schedule),
PeakMemoryTracker(),
EstimatedTimeLeft(median=True),
SessionRunTimeout(60000).set_chief_only(True), # 1 minute timeout
] + [
EvalCallback(dataset, *MODEL.get_inference_tensor_names(), args.logdir)
for dataset in cfg.DATA.VAL
]
if not is_horovod:
callbacks.append(GPUUtilizationTracker())
start_epoch = cfg.TRAIN.STARTING_EPOCH
if is_horovod and hvd.rank() > 0:
session_init = None
else:
# first try to find existing model
checkpoint_path = os.path.join(args.logdir, "checkpoint")
if os.path.exists(checkpoint_path):
session_init = get_model_loader(checkpoint_path)
start_step = int(session_init.path.split("-")[-1])
start_epoch = start_step // stepnum
logger.info(
"initializing from existing model, " + session_init.path + ", starting from epoch " + str(start_epoch))
else:
if args.load:
session_init = get_model_loader(args.load)
else:
session_init = get_model_loader(cfg.BACKBONE.WEIGHTS) if cfg.BACKBONE.WEIGHTS else None
max_epoch = min(cfg.TRAIN.LR_SCHEDULE[-1] * factor // stepnum, cfg.TRAIN.MAX_NUM_EPOCHS)
traincfg = TrainConfig(
model=MODEL,
data=QueueInput(train_dataflow),
callbacks=callbacks,
steps_per_epoch=stepnum,
# max_epoch=cfg.TRAIN.LR_SCHEDULE[-1] * factor // stepnum,
max_epoch=max_epoch,
session_init=session_init,
starting_epoch=start_epoch
)
if is_horovod:
trainer = HorovodTrainer(average=False)
else:
# nccl mode appears faster than cpu mode
trainer = SyncMultiGPUTrainerReplicated(cfg.TRAIN.NUM_GPUS, average=False, mode='nccl')
launch_train_with_config(traincfg, trainer)
| preprocess |
chevronUp32F.d.ts | export const chevronUp32F: string; |
||
error.rs | use crate::common::*;
#[derive(Debug)]
pub(crate) enum Error<'src> {
ArgumentCountMismatch {
recipe: &'src str,
parameters: Vec<Parameter<'src>>,
found: usize,
min: usize,
max: usize,
},
Backtick {
token: Token<'src>,
output_error: OutputError,
},
ChooserInvoke {
shell_binary: String,
shell_arguments: String,
chooser: OsString,
io_error: io::Error,
},
ChooserRead {
chooser: OsString,
io_error: io::Error,
},
ChooserStatus {
chooser: OsString,
status: ExitStatus,
},
ChooserWrite {
chooser: OsString,
io_error: io::Error,
},
Code {
recipe: &'src str,
line_number: Option<usize>,
code: i32,
},
CommandInvoke {
binary: OsString,
arguments: Vec<OsString>,
io_error: io::Error,
},
CommandStatus {
binary: OsString,
arguments: Vec<OsString>,
status: ExitStatus,
},
Compile {
compile_error: CompileError<'src>,
},
Config {
config_error: ConfigError,
},
Cygpath {
recipe: &'src str,
output_error: OutputError,
},
DefaultRecipeRequiresArguments {
recipe: &'src str,
min_arguments: usize,
},
Dotenv {
dotenv_error: dotenv::Error,
},
EditorInvoke {
editor: OsString,
io_error: io::Error,
},
EditorStatus {
editor: OsString,
status: ExitStatus,
},
EvalUnknownVariable {
variable: String,
suggestion: Option<Suggestion<'src>>,
},
FunctionCall {
function: Name<'src>,
message: String,
},
InitExists {
justfile: PathBuf,
},
Internal {
message: String,
},
Io {
recipe: &'src str,
io_error: io::Error,
},
Load {
path: PathBuf,
io_error: io::Error,
},
NoChoosableRecipes,
NoRecipes,
RegexCompile {
source: regex::Error,
},
Search {
search_error: SearchError,
},
Shebang {
recipe: &'src str,
command: String,
argument: Option<String>,
io_error: io::Error,
},
Signal {
recipe: &'src str,
line_number: Option<usize>,
signal: i32,
},
TmpdirIo {
recipe: &'src str,
io_error: io::Error,
},
Unknown {
recipe: &'src str,
line_number: Option<usize>,
},
UnknownOverrides {
overrides: Vec<String>,
},
UnknownRecipes {
recipes: Vec<String>,
suggestion: Option<Suggestion<'src>>,
},
Unstable {
message: String,
},
WriteJustfile {
justfile: PathBuf,
io_error: io::Error,
},
}
impl<'src> Error<'src> {
pub(crate) fn code(&self) -> Option<i32> {
match self {
Self::Code { code, .. }
| Self::Backtick {
output_error: OutputError::Code(code),
..
} => Some(*code),
Self::ChooserStatus { status, .. } | Self::EditorStatus { status, .. } => status.code(),
_ => None,
}
}
fn context(&self) -> Option<Token<'src>> {
match self {
Self::Backtick { token, .. } => Some(*token),
Self::Compile { compile_error } => Some(compile_error.context()),
Self::FunctionCall { function, .. } => Some(function.token()),
_ => None,
}
}
pub(crate) fn internal(message: impl Into<String>) -> Self {
Self::Internal {
message: message.into(),
}
}
}
impl<'src> From<CompileError<'src>> for Error<'src> {
fn from(compile_error: CompileError<'src>) -> Self {
Self::Compile { compile_error }
}
}
impl<'src> From<ConfigError> for Error<'src> {
fn from(config_error: ConfigError) -> Self {
Self::Config { config_error }
}
}
impl<'src> From<dotenv::Error> for Error<'src> {
fn from(dotenv_error: dotenv::Error) -> Error<'src> {
Self::Dotenv { dotenv_error }
}
}
impl<'src> From<SearchError> for Error<'src> {
fn from(search_error: SearchError) -> Self {
Self::Search { search_error }
}
}
impl<'src> ColorDisplay for Error<'src> {
fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result {
use Error::*;
write!(
f,
"{}: {}",
color.error().paint("error"),
color.message().prefix()
)?;
match self {
ArgumentCountMismatch {
recipe,
found,
min,
max,
..
} => {
if min == max {
let expected = min;
write!(
f,
"Recipe `{}` got {} {} but {}takes {}",
recipe,
found,
Count("argument", *found),
if expected < found { "only " } else { "" },
expected
)?;
} else if found < min {
write!(
f,
"Recipe `{}` got {} {} but takes at least {}",
recipe,
found,
Count("argument", *found),
min
)?;
} else if found > max {
write!(
f,
"Recipe `{}` got {} {} but takes at most {}",
recipe,
found,
Count("argument", *found),
max
)?;
}
}
Backtick { output_error, .. } => match output_error {
OutputError::Code(code) => {
write!(f, "Backtick failed with exit code {}", code)?;
}
OutputError::Signal(signal) => {
write!(f, "Backtick was terminated by signal {}", signal)?;
}
OutputError::Unknown => {
write!(f, "Backtick failed for an unknown reason")?;
}
OutputError::Io(io_error) => {
match io_error.kind() {
io::ErrorKind::NotFound => write!(
f,
"Backtick could not be run because just could not find `sh`:\n{}",
io_error
),
io::ErrorKind::PermissionDenied => write!(
f,
"Backtick could not be run because just could not run `sh`:\n{}",
io_error
),
_ => write!(
f,
"Backtick could not be run because of an IO error while launching `sh`:\n{}",
io_error | }
OutputError::Utf8(utf8_error) => {
write!(
f,
"Backtick succeeded but stdout was not utf8: {}",
utf8_error
)?;
}
},
ChooserInvoke {
shell_binary,
shell_arguments,
chooser,
io_error,
} => {
write!(
f,
"Chooser `{} {} {}` invocation failed: {}",
shell_binary,
shell_arguments,
chooser.to_string_lossy(),
io_error,
)?;
}
ChooserRead { chooser, io_error } => {
write!(
f,
"Failed to read output from chooser `{}`: {}",
chooser.to_string_lossy(),
io_error
)?;
}
ChooserStatus { chooser, status } => {
write!(
f,
"Chooser `{}` failed: {}",
chooser.to_string_lossy(),
status
)?;
}
ChooserWrite { chooser, io_error } => {
write!(
f,
"Failed to write to chooser `{}`: {}",
chooser.to_string_lossy(),
io_error
)?;
}
Code {
recipe,
line_number,
code,
} => {
if let Some(n) = line_number {
write!(
f,
"Recipe `{}` failed on line {} with exit code {}",
recipe, n, code
)?;
} else {
write!(f, "Recipe `{}` failed with exit code {}", recipe, code)?;
}
}
CommandInvoke {
binary,
arguments,
io_error,
} => {
write!(
f,
"Failed to invoke {}: {}",
iter::once(binary)
.chain(arguments)
.map(|value| Enclosure::tick(value.to_string_lossy()).to_string())
.collect::<Vec<String>>()
.join(" "),
io_error,
)?;
}
CommandStatus {
binary,
arguments,
status,
} => {
write!(
f,
"Command {} failed: {}",
iter::once(binary)
.chain(arguments)
.map(|value| Enclosure::tick(value.to_string_lossy()).to_string())
.collect::<Vec<String>>()
.join(" "),
status,
)?;
}
Compile { compile_error } => Display::fmt(compile_error, f)?,
Config { config_error } => Display::fmt(config_error, f)?,
Cygpath {
recipe,
output_error,
} => match output_error {
OutputError::Code(code) => {
write!(
f,
"Cygpath failed with exit code {} while translating recipe `{}` shebang interpreter \
path",
code, recipe
)?;
}
OutputError::Signal(signal) => {
write!(
f,
"Cygpath terminated by signal {} while translating recipe `{}` shebang interpreter \
path",
signal, recipe
)?;
}
OutputError::Unknown => {
write!(
f,
"Cygpath experienced an unknown failure while translating recipe `{}` shebang \
interpreter path",
recipe
)?;
}
OutputError::Io(io_error) => {
match io_error.kind() {
io::ErrorKind::NotFound => write!(
f,
"Could not find `cygpath` executable to translate recipe `{}` shebang interpreter \
path:\n{}",
recipe, io_error
),
io::ErrorKind::PermissionDenied => write!(
f,
"Could not run `cygpath` executable to translate recipe `{}` shebang interpreter \
path:\n{}",
recipe, io_error
),
_ => write!(f, "Could not run `cygpath` executable:\n{}", io_error),
}?;
}
OutputError::Utf8(utf8_error) => {
write!(
f,
"Cygpath successfully translated recipe `{}` shebang interpreter path, but output was \
not utf8: {}",
recipe, utf8_error
)?;
}
},
DefaultRecipeRequiresArguments {
recipe,
min_arguments,
} => {
write!(
f,
"Recipe `{}` cannot be used as default recipe since it requires at least {} {}.",
recipe,
min_arguments,
Count("argument", *min_arguments),
)?;
}
Dotenv { dotenv_error } => {
write!(f, "Failed to load environment file: {}", dotenv_error)?;
}
EditorInvoke { editor, io_error } => {
write!(
f,
"Editor `{}` invocation failed: {}",
editor.to_string_lossy(),
io_error
)?;
}
EditorStatus { editor, status } => {
write!(
f,
"Editor `{}` failed: {}",
editor.to_string_lossy(),
status
)?;
}
EvalUnknownVariable {
variable,
suggestion,
} => {
write!(f, "Justfile does not contain variable `{}`.", variable,)?;
if let Some(suggestion) = *suggestion {
write!(f, "\n{}", suggestion)?;
}
}
FunctionCall { function, message } => {
write!(
f,
"Call to function `{}` failed: {}",
function.lexeme(),
message
)?;
}
InitExists { justfile } => {
write!(f, "Justfile `{}` already exists", justfile.display())?;
}
Internal { message } => {
write!(
f,
"Internal runtime error, this may indicate a bug in just: {} \
consider filing an issue: https://github.com/casey/just/issues/new",
message
)?;
}
Io { recipe, io_error } => {
match io_error.kind() {
io::ErrorKind::NotFound => write!(
f,
"Recipe `{}` could not be run because just could not find `sh`: {}",
recipe, io_error
),
io::ErrorKind::PermissionDenied => write!(
f,
"Recipe `{}` could not be run because just could not run `sh`: {}",
recipe, io_error
),
_ => write!(
f,
"Recipe `{}` could not be run because of an IO error while launching `sh`: {}",
recipe, io_error
),
}?;
}
Load { io_error, path } => {
write!(
f,
"Failed to read justfile at `{}`: {}",
path.display(),
io_error
)?;
}
NoChoosableRecipes => {
write!(f, "Justfile contains no choosable recipes.")?;
}
NoRecipes => {
write!(f, "Justfile contains no recipes.")?;
}
RegexCompile { source } => {
write!(f, "{}", source)?;
}
Search { search_error } => Display::fmt(search_error, f)?,
Shebang {
recipe,
command,
argument,
io_error,
} => {
if let Some(argument) = argument {
write!(
f,
"Recipe `{}` with shebang `#!{} {}` execution error: {}",
recipe, command, argument, io_error
)?;
} else {
write!(
f,
"Recipe `{}` with shebang `#!{}` execution error: {}",
recipe, command, io_error
)?;
}
}
Signal {
recipe,
line_number,
signal,
} => {
if let Some(n) = line_number {
write!(
f,
"Recipe `{}` was terminated on line {} by signal {}",
recipe, n, signal
)?;
} else {
write!(f, "Recipe `{}` was terminated by signal {}", recipe, signal)?;
}
}
TmpdirIo { recipe, io_error } => write!(
f,
"Recipe `{}` could not be run because of an IO error while trying to create a temporary \
directory or write a file to that directory`:{}",
recipe, io_error
)?,
Unknown {
recipe,
line_number,
} => {
if let Some(n) = line_number {
write!(
f,
"Recipe `{}` failed on line {} for an unknown reason",
recipe, n
)?;
} else {
write!(f, "Recipe `{}` failed for an unknown reason", recipe)?;
}
}
UnknownOverrides { overrides } => {
write!(
f,
"{} {} overridden on the command line but not present in justfile",
Count("Variable", overrides.len()),
List::and_ticked(overrides),
)?;
}
UnknownRecipes {
recipes,
suggestion,
} => {
write!(
f,
"Justfile does not contain {} {}.",
Count("recipe", recipes.len()),
List::or_ticked(recipes),
)?;
if let Some(suggestion) = *suggestion {
write!(f, "\n{}", suggestion)?;
}
}
Unstable { message } => {
write!(
f,
"{} Invoke `just` with the `--unstable` flag to enable unstable features.",
message
)?;
}
WriteJustfile { justfile, io_error } => {
write!(
f,
"Failed to write justfile to `{}`: {}",
justfile.display(),
io_error
)?;
}
}
write!(f, "{}", color.message().suffix())?;
if let ArgumentCountMismatch {
recipe, parameters, ..
} = self
{
writeln!(f)?;
write!(
f,
"{}:\n just {}",
color.message().paint("usage"),
recipe
)?;
for param in parameters {
write!(f, " {}", param.color_display(color))?;
}
}
if let Some(token) = self.context() {
writeln!(f)?;
write!(f, "{}", token.color_display(color.error()))?;
}
Ok(())
}
} | ),
}?; |
int.rs | //! `int` impl
use crate::avm2::activation::Activation;
use crate::avm2::object::{Object, ScriptObject};
use crate::avm2::value::Value;
use crate::avm2::Error;
use gc_arena::MutationContext;
/// Implements `int`
pub fn constructor<'gc>(
_activation: &mut Activation<'_, 'gc, '_>,
_this: Option<Object<'gc>>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error> {
Err("int constructor is a stub.".into())
}
/// Construct `int.prototype`.
pub fn create_proto<'gc>(
mc: MutationContext<'gc, '_>,
super_proto: Object<'gc>, | } | _fn_proto: Object<'gc>,
) -> Object<'gc> {
ScriptObject::object(mc, super_proto) |
dataframe.rs | use crate::dataframe::PyDataFrame;
use crate::error::PyPolarsEr;
use crate::lazy::{dsl::PyExpr, utils::py_exprs_to_exprs};
use polars::lazy::frame::{LazyFrame, LazyGroupBy};
use pyo3::prelude::*;
#[pyclass]
#[repr(transparent)]
pub struct PyLazyGroupBy {
// option because we cannot get a self by value in pyo3
pub lgb: Option<LazyGroupBy>,
}
#[pymethods]
impl PyLazyGroupBy {
pub fn agg(&mut self, aggs: Vec<PyExpr>) -> PyLazyFrame {
let lgb = self.lgb.take().unwrap();
let aggs = py_exprs_to_exprs(aggs);
lgb.agg(aggs).into()
}
}
#[pyclass]
#[repr(transparent)]
#[derive(Clone)]
pub struct PyLazyFrame {
// option because we cannot get a self by value in pyo3
pub ldf: LazyFrame,
}
impl From<LazyFrame> for PyLazyFrame {
fn from(ldf: LazyFrame) -> Self {
PyLazyFrame { ldf }
}
}
#[pymethods]
impl PyLazyFrame {
#[staticmethod]
pub fn new_from_csv(
path: String,
sep: &str,
has_header: bool,
ignore_errors: bool,
skip_rows: usize,
stop_after_n_rows: Option<usize>,
) -> Self {
let delimiter = sep.as_bytes()[0];
LazyFrame::new_from_csv(
path,
delimiter,
has_header,
ignore_errors,
skip_rows,
stop_after_n_rows,
)
.into()
}
pub fn describe_plan(&self) -> String {
self.ldf.describe_plan()
}
pub fn | (&self) -> PyResult<String> {
let result = self
.ldf
.describe_optimized_plan()
.map_err(PyPolarsEr::from)?;
Ok(result)
}
pub fn optimization_toggle(
&self,
type_coercion: bool,
predicate_pushdown: bool,
projection_pushdown: bool,
simplify_expr: bool,
) -> PyLazyFrame {
let ldf = self.ldf.clone();
let ldf = ldf
.with_type_coercion_optimization(type_coercion)
.with_predicate_pushdown_optimization(predicate_pushdown)
.with_simplify_expr_optimization(simplify_expr)
.with_projection_pushdown_optimization(projection_pushdown);
ldf.into()
}
pub fn sort(&self, by_column: &str, reverse: bool) -> PyLazyFrame {
let ldf = self.ldf.clone();
ldf.sort(by_column, reverse).into()
}
pub fn collect(&self) -> PyResult<PyDataFrame> {
let ldf = self.ldf.clone();
let df = ldf.collect().map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn filter(&mut self, predicate: PyExpr) -> PyLazyFrame {
let ldf = self.ldf.clone();
ldf.filter(predicate.inner).into()
}
pub fn select(&mut self, exprs: Vec<PyExpr>) -> PyLazyFrame {
let ldf = self.ldf.clone();
let exprs = py_exprs_to_exprs(exprs);
ldf.select(exprs).into()
}
pub fn groupby(&mut self, by: Vec<&str>) -> PyLazyGroupBy {
let ldf = self.ldf.clone();
let lazy_gb = ldf.groupby(by);
PyLazyGroupBy { lgb: Some(lazy_gb) }
}
pub fn inner_join(
&mut self,
other: PyLazyFrame,
left_on: PyExpr,
right_on: PyExpr,
) -> PyLazyFrame {
let ldf = self.ldf.clone();
let other = other.ldf;
ldf.inner_join(other, left_on.inner, right_on.inner).into()
}
pub fn outer_join(
&mut self,
other: PyLazyFrame,
left_on: PyExpr,
right_on: PyExpr,
) -> PyLazyFrame {
let ldf = self.ldf.clone();
let other = other.ldf;
ldf.outer_join(other, left_on.inner, right_on.inner).into()
}
pub fn left_join(
&mut self,
other: PyLazyFrame,
left_on: PyExpr,
right_on: PyExpr,
) -> PyLazyFrame {
let ldf = self.ldf.clone();
let other = other.ldf;
ldf.left_join(other, left_on.inner, right_on.inner).into()
}
pub fn with_column(&mut self, expr: PyExpr) -> PyLazyFrame {
let ldf = self.ldf.clone();
ldf.with_column(expr.inner).into()
}
pub fn with_columns(&mut self, exprs: Vec<PyExpr>) -> PyLazyFrame {
let ldf = self.ldf.clone();
ldf.with_columns(py_exprs_to_exprs(exprs)).into()
}
pub fn with_column_renamed(&mut self, existing: &str, new: &str) -> PyLazyFrame {
let ldf = self.ldf.clone();
ldf.with_column_renamed(existing, new).into()
}
pub fn reverse(&self) -> Self {
let ldf = self.ldf.clone();
ldf.reverse().into()
}
pub fn shift(&self, periods: i32) -> Self {
let ldf = self.ldf.clone();
ldf.shift(periods).into()
}
pub fn fill_none(&self, fill_value: PyExpr) -> Self {
let ldf = self.ldf.clone();
ldf.fill_none(fill_value.inner).into()
}
pub fn min(&self) -> Self {
let ldf = self.ldf.clone();
ldf.min().into()
}
pub fn max(&self) -> Self {
let ldf = self.ldf.clone();
ldf.max().into()
}
pub fn sum(&self) -> Self {
let ldf = self.ldf.clone();
ldf.sum().into()
}
pub fn mean(&self) -> Self {
let ldf = self.ldf.clone();
ldf.mean().into()
}
pub fn std(&self) -> Self {
let ldf = self.ldf.clone();
ldf.std().into()
}
pub fn var(&self) -> Self {
let ldf = self.ldf.clone();
ldf.var().into()
}
pub fn median(&self) -> Self {
let ldf = self.ldf.clone();
ldf.median().into()
}
pub fn quantile(&self, quantile: f64) -> Self {
let ldf = self.ldf.clone();
ldf.quantile(quantile).into()
}
pub fn explode(&self, column: &str) -> Self {
let ldf = self.ldf.clone();
ldf.explode(column).into()
}
pub fn drop_duplicates(&self, maintain_order: bool, subset: Option<Vec<String>>) -> Self {
let ldf = self.ldf.clone();
ldf.drop_duplicates(maintain_order, subset).into()
}
pub fn drop_nulls(&self, subset: Option<Vec<String>>) -> Self {
let ldf = self.ldf.clone();
ldf.drop_nulls(subset.as_ref().map(|v| v.as_ref())).into()
}
pub fn clone(&self) -> PyLazyFrame {
self.ldf.clone().into()
}
}
| describe_optimized_plan |
index.js | import React, { PureComponent } from 'react';
import Link from 'umi/link';
import RightContent from '../GlobalHeader/RightContent';
import BaseMenu from '../SiderMenu/BaseMenu';
import { getFlatMenuKeys } from '../SiderMenu/SiderMenuUtils';
import styles from './index.less';
import { title } from '../../defaultSettings';
export default class TopNavHeader extends PureComponent {
state = {
maxWidth: undefined,
};
static getDerivedStateFromProps(props) {
return {
maxWidth: (props.contentWidth === 'Fixed' ? 1200 : window.innerWidth) - 280 - 165 - 40,
};
}
render() {
const { theme, contentWidth, menuData, logo } = this.props;
const { maxWidth } = this.state;
const flatMenuKeys = getFlatMenuKeys(menuData); | this.maim = ref;
}}
className={`${styles.main} ${contentWidth === 'Fixed' ? styles.wide : ''}`}
>
<div className={styles.left}>
<div className={styles.logo} key="logo" id="logo">
<Link to="/home">
<img src={logo} alt="logo" />
<h1>{title}</h1>
</Link>
</div>
<div
style={{
maxWidth,
}}
>
<BaseMenu {...this.props} flatMenuKeys={flatMenuKeys} className={styles.menu} />
</div>
</div>
<RightContent {...this.props} />
</div>
</div>
);
}
} | return (
<div className={`${styles.head} ${theme === 'light' ? styles.light : ''}`}>
<div
ref={ref => { |
basic.go | package strprocess
import (
"errors"
"strconv"
)
// Strtoi is a wrapper of `strconv.Atoi()`.
// If `strconv.Atoi()` returns an error, Strtoi calls panic.
func Strtoi(s string) int | {
if i, err := strconv.Atoi(s); err != nil {
panic(errors.New("[argument error]: Strtoi only accepts integer string"))
} else {
return i
}
} |
|
DynamicPage.js | /* @flow */
import React from "react";
import ReactMarkdown from "react-markdown";
import Helmet from "react-helmet";
import { makeTitle } from "../routes";
import icons from "../icons";
import Query from "../queries/query";
import StaticPage from "./StaticPage";
import pageQuery from "../queries/content/page.js";
import NotFoundStaticPage from "./NotFoundStaticPage";
import routerContext from "../contexts/router-context";
import gfm from "remark-gfm";
import Accordion from "../components/Accordion";
type Props = {
location: any,
}
class DynamicPage extends React.Component<Props, void> {
static contextType = routerContext;
absoluteImageUrl(uri: string): string {
// Strapi returns a relative image url, we need to change
// it to point to our content server.
return window.STRAPI_URL + uri;
}
render() {
const params = {
"path": this.props.location.pathname,
};
const loading = (
<StaticPage
title="Loading"
bannerName="static"
>
<icons.Loading className="big" />
</StaticPage> | )
const error = (
<StaticPage
title="Error"
bannerName="static"
>
<p className="errorMessage">
Error retrieving content. Please try again.
</p>
</StaticPage>
)
return (
<Query
query={pageQuery}
args={params}
loadingComponent={loading}
errorComponent={error}
>
{res => {
if (
res.data.pages !== undefined && res.data.pages.length
) {
const page = res.data.pages[0];
return (
<StaticPage
title={page.Title}
bannerName={page.Banner ? page.Banner.Key : ""}
bannerPrimary={page.BannerTextPrimary}
bannerSecondary={page.BannerTextSecondary}
>
<Helmet>
<title>
{
makeTitle(
page.Title,
this.context.router.match.params
)
}
</title>
</Helmet>
<div className="DynamicPage">
<ReactMarkdown
plugins={[gfm]}
source={page.Body}
transformImageUri={
this.absoluteImageUrl
}
/>
<Accordion
title={page.AccordionTitle}
items={page.Accordion}
/>
</div>
</StaticPage>
)
}
return (<NotFoundStaticPage />)
}}
</Query>
);
}
}
export default DynamicPage; | |
User.js | const { Schema, model } = require('mongoose');
// create the User schema
const userSchema = new Schema(
{
username: {
type: String,
unique: true,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
match: [/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/]
},
thoughts: [
{
type: Schema.Types.ObjectId,
ref: 'Thought'
}
],
friends: [
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
},
{
toJSON: {
virtuals: true,
getters: true
},
id: false
}
);
userSchema.virtual('friendCount').get(function() {
return this.friends.length; |
const User = model('User', userSchema);
module.exports = User; | }); |
list.rs | use inner::logger::Logger;
use inner::json_helper;
use std::path::Path;
use json::JsonValue;
use inner::list_helper::{print_header, print_git_packages, print_str_packages};
pub fn list(is_local: bool, is_remote: bool, is_global: bool, logger: &Logger) {
let lock_content = match json_helper::read(Path::new("rubigo.lock")) {
Ok(content) => content,
Err(e) => {
logger.fatal(format!("unable to read `rubigo.lock`: {}", e));
return
}
};
let is_all = !(is_local || is_remote || is_global);
if is_remote || is_all {
list_remote(&lock_content[json_helper::GIT_KEY]);
}
if is_local || is_all {
list_local(&lock_content[json_helper::LOCAL_KEY]);
}
if is_global || is_all {
list_global(&lock_content[json_helper::GLOBAL_KEY]);
}
}
fn list_global(content: &JsonValue) {
if content.len() == 0 {
return
}
print_header("Global packages", content.len());
print_str_packages(content);
}
fn list_local(content: &JsonValue) |
fn list_remote(content: &JsonValue) {
if content.len() == 0 {
return
}
print_header("Remote packages", content.len());
print_git_packages(content);
}
| {
if content.len() == 0 {
return
}
print_header("Local packages", content.len());
print_str_packages(content);
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.