file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
api_test.go
// Copyright (c) 2015-2021, NVIDIA CORPORATION. // SPDX-License-Identifier: Apache-2.0 package conf import ( "bytes" "encoding/base64" "io" "io/ioutil" "os" "path/filepath" "reflect" "testing" "time" "github.com/stretchr/testify/assert" ) const errnoEACCES = int(13) var tempFile1Name string var tempFile2Name string var tempFile3Name string var tempFile4Name string var tempFile5Name string var tempFile6Name string var tempFile7Name string var confStringToTest1 string var confStringToTest2 string var confStringToTest3 string func TestMain(m *testing.M) { tempFile1, errorTempFile1 := ioutil.TempFile(os.TempDir(), "TestConfFile1_") if nil != errorTempFile1 { os.Exit(errnoEACCES) } tempFile1Name = tempFile1.Name() io.WriteString(tempFile1, "# A comment on it's own line\n") io.WriteString(tempFile1, "[TestNamespace:Test_-_Section]\n") io.WriteString(tempFile1, "Test_-_Option : TestValue1,TestValue2 # A comment at the end of a line\n") tempFile1.Close() tempFile2, errorTempFile2 := ioutil.TempFile(os.TempDir(), "TestConfFile2_") if nil != errorTempFile2 { os.Remove(tempFile1Name) os.Exit(errnoEACCES) } tempFile2Name = tempFile2.Name() io.WriteString(tempFile2, "; A comment on it's own line\n") io.WriteString(tempFile2, "[TestNamespace:Test_-_Section] ; A comment at the end of a line\n") io.WriteString(tempFile2, "Test_-_Option =\n") tempFile2.Close() tempFile3, errorTempFile3 := ioutil.TempFile(os.TempDir(), "TestConfFile3_") if nil != errorTempFile3 { os.Remove(tempFile1Name) os.Remove(tempFile2Name) os.Exit(errnoEACCES) } tempFile3Name = tempFile3.Name() io.WriteString(tempFile3, "[TestNamespace:Test_-_Section]\n") io.WriteString(tempFile3, "Test_-_Option = http://Test.Value.3/ TestValue4$\tTestValue5$\n") tempFile3.Close() tempFile4, errorTempFile4 := ioutil.TempFile(os.TempDir(), "TestConfFile4_") if nil != errorTempFile4 { os.Remove(tempFile1Name) os.Remove(tempFile2Name) os.Remove(tempFile3Name) os.Exit(errnoEACCES) } tempFile4Name = tempFile4.Name() tempFile4.Close() tempFile5, errorTempFile5 := ioutil.TempFile(os.TempDir(), "TestConfFile5_") if nil != errorTempFile5 { os.Remove(tempFile1Name) os.Remove(tempFile2Name) os.Remove(tempFile3Name) os.Remove(tempFile4Name) os.Exit(errnoEACCES) } tempFile5Name = tempFile5.Name() io.WriteString(tempFile5, ".include ./"+filepath.Base(tempFile4Name)+"\n") tempFile5.Close() tempFile6, errorTempFile6 := ioutil.TempFile(os.TempDir(), "TestConfFile6_") if nil != errorTempFile6 { os.Remove(tempFile1Name) os.Remove(tempFile2Name) os.Remove(tempFile3Name) os.Remove(tempFile4Name) os.Remove(tempFile5Name) os.Exit(errnoEACCES) } tempFile6Name = tempFile6.Name() io.WriteString(tempFile6, "[TestNamespace:Test_-_Section_-_1]\n") io.WriteString(tempFile6, "Option_-_1_-_No_-_Values :\n") io.WriteString(tempFile6, "Option_-_2_-_One_-_Value : Value_-_1\n") io.WriteString(tempFile6, "Option_-_3_-_Two_-_Values : Value_-_1, Value_-_2\n") io.WriteString(tempFile6, "\n") io.WriteString(tempFile6, "[TestNamespace:Test_-_Section_-_2]\n") io.WriteString(tempFile6, "Option : Value\n") tempFile6.Close() tempFile7, errorTempFile7 := ioutil.TempFile(os.TempDir(), "TestConfFile7_") if nil != errorTempFile7 { os.Remove(tempFile1Name) os.Remove(tempFile2Name) os.Remove(tempFile3Name) os.Remove(tempFile4Name) os.Remove(tempFile5Name) os.Remove(tempFile6Name) os.Exit(errnoEACCES) } tempFile7Name = tempFile7.Name() // Leave it empty... will be used as output file tempFile7.Close() confStringToTest1 = "TestNamespace:Test_-_Section.Test_-_Option = TestValue6,http://Test.Value_-_7/" confStringToTest2 = "TestNamespace:Test_-_Section.Test_-_Option = TestValue8$,http://Test.Value_-_9/$" confStringToTest3 = "TestNamespace:Test_-_Section.Test_-_Option =" mRunReturn := m.Run() os.Remove(tempFile1Name) os.Remove(tempFile2Name) os.Remove(tempFile3Name) os.Remove(tempFile4Name) os.Remove(tempFile5Name) os.Remove(tempFile6Name) os.Remove(tempFile7Name) os.Exit(mRunReturn) } func TestUpdate(t *testing.T)
func TestFromFileConstructor(t *testing.T) { confMap, err := MakeConfMapFromFile(tempFile3Name) if nil != err { t.Fatalf("MakeConfMapFromFile(): expected err to be nil, got %#v", err) } values, err := confMap.FetchOptionValueStringSlice("TestNamespace:Test_-_Section", "Test_-_Option") if err != nil { t.Fatalf("FetchOptionValueStringSlice(): expected err to be nil, got %#v", err) } expected := "http://Test.Value.3/" if values[0] != expected { t.Fatalf("FetchOptionValueStringSlice(): expected %#v, got %#v", expected, values[0]) } } func TestFromFileConstructorNonexistentFile(t *testing.T) { _, err := MakeConfMapFromFile("/does/not/exist") expectedErr := "open /does/not/exist: no such file or directory" if err.Error() != expectedErr { t.Fatalf("expected err to be %#v, got %#v", expectedErr, err.Error()) } } func TestFetch(t *testing.T) { const ( base64DecodedString = "Now is the time" base64DecodedStringSliceElement0 = "for all good men" base64DecodedStringSliceElement1 = "to come to the aid of their country." ) var ( base64EncodedString = base64.StdEncoding.EncodeToString([]byte(base64DecodedString)) base64EncodedStringSliceElement0 = base64.StdEncoding.EncodeToString([]byte(base64DecodedStringSliceElement0)) base64EncodedStringSliceElement1 = base64.StdEncoding.EncodeToString([]byte(base64DecodedStringSliceElement1)) confMap = MakeConfMap() err error ) err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionStringSlice1=") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionStringSlice1=: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionStringSlice2=TestString1,TestString2") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionStringSlice2=TestString1,TestString2: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionString=TestString3") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionString=TestString3: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionBase64String=" + base64EncodedString) if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionBase64String=" + base64EncodedString) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionBase64StringSlice=" + base64EncodedStringSliceElement0 + "," + base64EncodedStringSliceElement1) if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionBase64StringSlice=" + base64EncodedStringSliceElement0 + "," + base64EncodedStringSliceElement1) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionBool=true") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionBool=true: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionUint8=91") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionUint8=91: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionUint16=12") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionUint16=12: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionUint32=345") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionUint32=345: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionUint64=6789") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionUint64=6789: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionMilliseconds32=0.123") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionMilliseconds32=0.123: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionMilliseconds64=0.456") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionMilliseconds64=0.456: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionDuration=1.2s") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionDuration=1.2s: %v", err) } err = confMap.UpdateFromString("TestNamespace:Test_-_Section.Test_-_OptionGUIDString=12345678-1234-1234-1234-123456789ABC") if nil != err { t.Fatalf("Couldn't add TestNamespace:Test_-_Section.Test_-_OptionGUIDString=12345678-1234-1234-1234-123456789ABC: %v", err) } err = confMap.VerifyOptionIsMissing("TestNamespace:Test_-_Section", "Test_-_OptionStringSlice0") if nil != err { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionStringSlice0 should have verified as missing") } err = confMap.VerifyOptionIsMissing("TestNamespace:Test_-_Section", "Test_-_OptionStringSlice1") if nil == err { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionStringSlice1 should have verified as not missing") } err = confMap.VerifyOptionValueIsEmpty("TestNamespace:Test_-_Section", "Test_-_OptionStringSlice1") if nil != err { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionStringSlice1 should have verified as empty") } err = confMap.VerifyOptionValueIsEmpty("TestNamespace:Test_-_Section", "Test_-_OptionStringSlice2") if nil == err { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionStringSlice2 should have verified as not empty") } testStringSlice1, err := confMap.FetchOptionValueStringSlice("TestNamespace:Test_-_Section", "Test_-_OptionStringSlice1") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionStringSlice1: %v", err) } testStringSlice2, err := confMap.FetchOptionValueStringSlice("TestNamespace:Test_-_Section", "Test_-_OptionStringSlice2") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionStringSlice2: %v", err) } testString, err := confMap.FetchOptionValueString("TestNamespace:Test_-_Section", "Test_-_OptionString") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionString: %v", err) } testBase64String, err := confMap.FetchOptionValueBase64String("TestNamespace:Test_-_Section", "Test_-_OptionBase64String") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionBase64String: %v", err) } testBase64StringSlice, err := confMap.FetchOptionValueBase64StringSlice("TestNamespace:Test_-_Section", "Test_-_OptionBase64StringSlice") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionBase64StringSlice: %v", err) } testBool, err := confMap.FetchOptionValueBool("TestNamespace:Test_-_Section", "Test_-_OptionBool") if err != nil { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionBool: %v", err) } testUint8, err := confMap.FetchOptionValueUint8("TestNamespace:Test_-_Section", "Test_-_OptionUint8") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionUint8: %v", err) } testUint16, err := confMap.FetchOptionValueUint16("TestNamespace:Test_-_Section", "Test_-_OptionUint16") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionUint16: %v", err) } testUint32, err := confMap.FetchOptionValueUint32("TestNamespace:Test_-_Section", "Test_-_OptionUint32") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionUint32: %v", err) } testUint64, err := confMap.FetchOptionValueUint64("TestNamespace:Test_-_Section", "Test_-_OptionUint64") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionUint64: %v", err) } testFloat32, err := confMap.FetchOptionValueFloat32("TestNamespace:Test_-_Section", "Test_-_OptionMilliseconds32") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionMilliseconds32 as float32: %v", err) } testFloat64, err := confMap.FetchOptionValueFloat64("TestNamespace:Test_-_Section", "Test_-_OptionMilliseconds64") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionMilliseconds64 as float64: %v", err) } testScaledUint32, err := confMap.FetchOptionValueFloatScaledToUint32("TestNamespace:Test_-_Section", "Test_-_OptionMilliseconds32", 1000) if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionMilliseconds32 as uint32: %v", err) } testScaledUint64, err := confMap.FetchOptionValueFloatScaledToUint64("TestNamespace:Test_-_Section", "Test_-_OptionMilliseconds64", 1000) if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionMilliseconds64 as uint64: %v", err) } testDuration, err := confMap.FetchOptionValueDuration("TestNamespace:Test_-_Section", "Test_-_OptionDuration") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.TestDuration: %v", err) } testGUID, err := confMap.FetchOptionValueUUID("TestNamespace:Test_-_Section", "Test_-_OptionGUIDString") if nil != err { t.Fatalf("Couldn't fetch TestNamespace:Test_-_Section.Test_-_OptionGUIDString: %v", err) } if 0 != len(testStringSlice1) { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionStringSlice1 contained unexpected value(s)") } if (2 != len(testStringSlice2)) || ("TestString1" != testStringSlice2[0]) || ("TestString2" != testStringSlice2[1]) { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionStringSlice2 contained unexpected value(s)") } if "TestString3" != testString { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionString contained unexpected value") } if base64DecodedString != testBase64String { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionBase64String contained unexpected value") } if (2 != len(testBase64StringSlice)) || (base64DecodedStringSliceElement0 != base64DecodedStringSliceElement0) || (base64DecodedStringSliceElement1 != base64DecodedStringSliceElement1) { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionBase64StringSlice contained unexpected value(s)") } if testBool != true { t.Fatalf("TestNamespace:Test_-_Section.TestBool contained unexpected value") } if uint8(91) != testUint8 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionUint8 contained unexpected value") } if uint16(12) != testUint16 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionUint16 contained unexpected value") } if uint32(345) != testUint32 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionUint32 contained unexpected value") } if uint64(6789) != testUint64 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionUint64 contained unexpected value") } if float32(0.123) != testFloat32 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionMilliseconds32 contained unexpected float32 value") } if float64(0.456) != testFloat64 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionMilliseconds64 contained unexpected float64 value") } if uint32(123) != testScaledUint32 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionMilliseconds32 contained unexpected uint32 value") } if uint64(456) != testScaledUint64 { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionMilliseconds64 contained unexpected uint64 value") } timeBase := time.Time{} timeBasePlusTestDuration := timeBase.Add(testDuration) if (1 != timeBasePlusTestDuration.Second()) || (200000000 != timeBasePlusTestDuration.Nanosecond()) { t.Fatalf("TestNamespace:Test_-_Section.TestDuration contained unexpected value") } if 0 != bytes.Compare([]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC}, testGUID) { t.Fatalf("TestNamespace:Test_-_Section.Test_-_OptionGUIDString contained unexpected value") } } func TestInclude(t *testing.T) { _, err := MakeConfMapFromFile(tempFile5Name) if nil != err { t.Fatalf("MakeConfMapFromFile() of <tempdir>/%v that includes <tempdir>/%v got %#v", filepath.Base(tempFile5Name), filepath.Base(tempFile4Name), err) } } func TestDump(t *testing.T) { var ( confMap6 = MakeConfMap() confMap7 = MakeConfMap() ) err := confMap6.UpdateFromFile(tempFile6Name) if nil != err { t.Fatalf("UpdateConfMapFromFile(\"%v\") returned: \"%v\"", tempFile6Name, err) } err = confMap6.DumpConfMapToFile(tempFile7Name, os.FileMode(0600)) if nil != err { t.Fatalf("DumpConfMapToFile() returned: \"%v\"", err) } err = confMap7.UpdateFromFile(tempFile7Name) if nil != err { t.Fatalf("UpdateConfMapFromFile(\"%v\") returned: \"%v\"", tempFile7Name, err) } if !reflect.DeepEqual(confMap6, confMap7) { t.Fatalf("DumpConfMapToFile() failed to reproduce \"%v\" into \"%v\"", tempFile6Name, tempFile7Name) } } // test SetOptionIfMissing and SetSectionIfMissing func TestIfMissing(t *testing.T) { assert := assert.New(t) // create an empty confMap and populate it with one option (in one section) confMap := MakeConfMap() testSectionName0 := "TestSection0" testSectionName1 := "TestSection1e" testOptionName0 := "Test_-_Option0" testOptionName1 := "Test_-_Option1" testOptionString0 := "OptionValue0" missingOptionString0 := "DefaultString0" missingOptionString1 := "DefaultString1" confStringToSection0Option0 := testSectionName0 + "." + testOptionName0 + " = " + testOptionString0 // populate testSectionName0.testOptionName0 err := confMap.UpdateFromString(confStringToSection0Option0) assert.NoError(err, "UpdateFromString() should not fail with a valid option string") // verify option was set optionString, err := confMap.FetchOptionValueString(testSectionName0, testOptionName0) assert.NoError(err, "FetchOptionValueString() cannot fail a valid request") assert.Equal(testOptionString0, optionString, "FetchOptionValueString should return the option that was set") missingOptionValue0 := ConfMapOption{missingOptionString0} missingOptionValue1 := ConfMapOption{missingOptionString1} // a new ConfMapOption should not overwrite the existing one confMap.SetOptionIfMissing(testSectionName0, testOptionName0, missingOptionValue0) optionString, err = confMap.FetchOptionValueString(testSectionName0, testOptionName0) assert.NoError(err, "FetchOptionalValueString should not fail since the option exists") assert.Equal(testOptionString0, optionString, "SetOptionIfMissing should not change existing optionValue") // but a new ConfMapOption should replace a missing one optionString, err = confMap.FetchOptionValueString(testSectionName0, testOptionName1) assert.Error(err, "FetchOptionalValueString should fail since '%s' has not been set", testOptionName1) confMap.SetOptionIfMissing(testSectionName0, testOptionName1, missingOptionValue1) optionString, err = confMap.FetchOptionValueString(testSectionName0, testOptionName1) assert.NoError(err, "FetchOptionalValueString should not fail since missing value was set") assert.Equal(missingOptionString1, optionString, "SetOptionIfMissing should have set missing value") // repeat a similar set of tests for sections // // verify option still exists optionString, err = confMap.FetchOptionValueString(testSectionName0, testOptionName0) assert.NoError(err, "FetchOptionValueString() cannot fail a valid request") // a new ConfMapSection should not overwrite an existing one missingSection0 := ConfMapSection{ testOptionName0: ConfMapOption{missingOptionString0}, testOptionName1: ConfMapOption{missingOptionString1}, } confMap.SetSectionIfMissing(testSectionName0, missingSection0) optionString, err = confMap.FetchOptionValueString(testSectionName0, testOptionName0) assert.NoError(err, "FetchOptionalValueString should not fail since the option exists") assert.Equal(testOptionString0, optionString, "SetOptionIfMissing should not change existing optionValue") optionString, err = confMap.FetchOptionValueString(testSectionName0, testOptionName1) assert.NoError(err, "second option should have been added") assert.Equal(missingOptionString1, optionString, "SetOptionIfMissing should not change existing optionValue") // but a new ConfMapSection should replace a missing one confMap.SetSectionIfMissing(testSectionName1, missingSection0) optionString, err = confMap.FetchOptionValueString(testSectionName1, testOptionName0) assert.NoError(err, "FetchOptionalValueString should not fail since section was added") assert.Equal(missingOptionString0, optionString, "missing Option should have been set") optionString, err = confMap.FetchOptionValueString(testSectionName1, testOptionName1) assert.NoError(err, "FetchOptionalValueString should not fail since section was added") assert.Equal(missingOptionString1, optionString, "missing Option should have been set") }
{ var confMap = MakeConfMap() err := confMap.UpdateFromFile(tempFile1Name) if nil != err { t.Fatalf("UpdateConfMapFromFile(\"%v\") returned: \"%v\"", tempFile1Name, err) } confMapSection, ok := confMap["TestNamespace:Test_-_Section"] if !ok { t.Fatalf("confMap[\"%v\"] missing", "TestNamespace:Test_-_Section") } confMapOption, ok := confMapSection["Test_-_Option"] if !ok { t.Fatalf("confMapSection[\"%v\"] missing", "Test_-_Option") } if 2 != len(confMapOption) { t.Fatalf("confMapSection[\"%v\"] constains unexpected number of values (%v)", "Test_-_Option", len(confMapOption)) } if "TestValue1" != string(confMapOption[0]) { t.Fatalf("confMapOption != \"%v\"", "TestValue1") } if "TestValue2" != string(confMapOption[1]) { t.Fatalf("confMapOption != \"%v\"", "TestValue2") } err = confMap.UpdateFromFile(tempFile2Name) if nil != err { t.Fatalf("UpdateConfMapFromFile(\"%v\") returned: \"%v\"", tempFile2Name, err) } confMapSection, ok = confMap["TestNamespace:Test_-_Section"] if !ok { t.Fatalf("confMap[\"%v\"] missing", "Test_-_Section") } confMapOption, ok = confMapSection["Test_-_Option"] if !ok { t.Fatalf("confMapSection[\"%v\"] missing", "Test_-_Option") } if 0 != len(confMapOption) { t.Fatalf("confMapSection[\"%v\"] constains unexpected number of values (%v)", "Test_-_Option", len(confMapOption)) } err = confMap.UpdateFromFile(tempFile3Name) if nil != err { t.Fatalf("UpdateConfMapFromFile(\"%v\") returned: \"%v\"", tempFile3Name, err) } confMapSection, ok = confMap["TestNamespace:Test_-_Section"] if !ok { t.Fatalf("confMap[\"%v\"] missing", "Test_-_Section") } confMapOption, ok = confMapSection["Test_-_Option"] if !ok { t.Fatalf("confMapSection[\"%v\"] missing", "Test_-_Option") } if 3 != len(confMapOption) { t.Fatalf("confMapSection[\"%v\"] constains unexpected number of values (%v)", "Test_-_Option", len(confMapOption)) } if "http://Test.Value.3/" != string(confMapOption[0]) { t.Fatalf("confMapOption != \"%v\"", "http://Test.Value.3/") } if "TestValue4$" != string(confMapOption[1]) { t.Fatalf("confMapOption != \"%v\"", "TestValue4$") } if "TestValue5$" != string(confMapOption[2]) { t.Fatalf("confMapOption != \"%v\"", "TestValue5$") } err = confMap.UpdateFromString(confStringToTest1) if nil != err { t.Fatalf("UpdateConfMapFromString(\"%v\") returned: \"%v\"", confStringToTest1, err) } confMapSection, ok = confMap["TestNamespace:Test_-_Section"] if !ok { t.Fatalf("confMap[\"%v\"] missing", "Test_-_Section") } confMapOption, ok = confMapSection["Test_-_Option"] if !ok { t.Fatalf("confMapSection[\"%v\"] missing", "Test_-_Option") } if 2 != len(confMapOption) { t.Fatalf("confMapSection[\"%v\"] constains unexpected number of values (%v)", "Test_-_Option", len(confMapOption)) } if "TestValue6" != string(confMapOption[0]) { t.Fatalf("confMapOption != \"%v\"", "TestValue6") } if "http://Test.Value_-_7/" != string(confMapOption[1]) { t.Fatalf("confMapOption != \"%v\"", "http://Test.Value_-_7/") } err = confMap.UpdateFromString(confStringToTest2) if nil != err { t.Fatalf("UpdateConfMapFromString(\"%v\") returned: \"%v\"", confStringToTest2, err) } confMapSection, ok = confMap["TestNamespace:Test_-_Section"] if !ok { t.Fatalf("confMap[\"%v\"] missing", "Test_-_Section") } confMapOption, ok = confMapSection["Test_-_Option"] if !ok { t.Fatalf("confMapSection[\"%v\"] missing", "Test_-_Option") } if 2 != len(confMapOption) { t.Fatalf("confMapSection[\"%v\"] constains unexpected number of values (%v)", "Test_-_Option", len(confMapOption)) } if "TestValue8$" != string(confMapOption[0]) { t.Fatalf("confMapOption != \"%v\"", "TestValue8$") } if "http://Test.Value_-_9/$" != string(confMapOption[1]) { t.Fatalf("confMapOption != \"%v\"", "http://Test.Value_-_9/$") } err = confMap.UpdateFromString(confStringToTest3) if nil != err { t.Fatalf("UpdateConfMapFromString(\"%v\") returned: \"%v\"", confStringToTest3, err) } confMapOption, ok = confMapSection["Test_-_Option"] if !ok { t.Fatalf("confMapSection[\"%v\"] missing", "Test_-_Option") } if 0 != len(confMapOption) { t.Fatalf("confMapSection[\"%v\"] constains unexpected number of values (%v)", "Test_-_Option", len(confMapOption)) } }
with_tuples_in_init_list.rs
mod with_arity_2; use super::*;
use proptest::prop_oneof; #[test] fn without_arity_2_errors_badarg() { TestRunner::new(Config::with_source_file(file!())) .run( &strategy::process().prop_flat_map(|arc_process| { ( Just(arc_process.clone()), (1_usize..=3_usize), strategy::term(arc_process.clone()), (Just(arc_process.clone()), prop_oneof![Just(1), Just(3)]) .prop_flat_map(|(arc_process, len)| { ( Just(arc_process.clone()), strategy::term::tuple::intermediate( strategy::term(arc_process.clone()), (len..=len).into(), arc_process.clone(), ), ) }) .prop_map(|(arc_process, element)| { arc_process.list_from_slice(&[element]).unwrap() }), ) }), |(arc_process, arity_usize, default_value, init_list)| { let arity = arc_process.integer(arity_usize).unwrap(); prop_assert_eq!( native(&arc_process, arity, default_value, init_list), Err(badarg!().into()) ); Ok(()) }, ) .unwrap(); }
createPathSelector.ts
import { Selector, ParametricSelector } from 'reselect'; import { NamedSelector, NamedParametricSelector } from './types'; import { defineDynamicSelectorName, getSelectorName, isDebugMode, } from './helpers'; export type Defined<T> = Exclude<T, undefined>; export type RequiredSelectorBuilder<S, R, D> = () => NamedSelector<S, R, D>; export type OptionalSelectorBuilder<S, R, D> = { (noDefaultValue?: undefined): NamedSelector<S, Defined<R> | undefined, D>; (defaultValue: NonNullable<R>): NamedSelector<S, NonNullable<R>, D>; (nullDefaultValue: R extends null ? null : never): NamedSelector< S, Defined<R>, D >; }; export type RequiredParametricSelectorBuilder< S, P, R,
D > = () => NamedParametricSelector<S, P, R, D>; export type OptionalParametricSelectorBuilder<S, P, R, D> = { (noDefaultValue?: undefined): NamedParametricSelector< S, P, Defined<R> | undefined, D >; (defaultValue: NonNullable<R>): NamedParametricSelector< S, P, NonNullable<R>, D >; (nullDefaultValue: R extends null ? null : never): NamedParametricSelector< S, P, Defined<R>, D >; }; export type RequiredObjectSelectorWrapper<S, R, D> = { [K in keyof R]-?: undefined extends R[K] ? OptionalPathSelectorType<S, R[K], D> : null extends R[K] ? OptionalPathSelectorType<S, R[K], D> : RequiredPathSelectorType<S, R[K], D>; }; export type OptionalObjectSelectorWrapper<S, R, D> = { [K in keyof R]-?: OptionalPathSelectorType<S, R[K], D>; }; export type RequiredObjectParametricSelectorWrapper<S, P, R, D> = { [K in keyof R]-?: undefined extends R[K] ? OptionalPathParametricSelectorType<S, P, R[K], D> : null extends R[K] ? OptionalPathParametricSelectorType<S, P, R[K], D> : RequiredPathParametricSelectorType<S, P, R[K], D>; }; export type OptionalObjectParametricSelectorWrapper<S, P, R, D> = { [K in keyof R]-?: OptionalPathParametricSelectorType<S, P, R[K], D>; }; export type RequiredArraySelectorWrapper<S, R, D> = { length: RequiredPathSelectorType<S, number, D>; [K: number]: undefined extends R ? OptionalPathSelectorType<S, R, D> : null extends R ? OptionalPathSelectorType<S, R, D> : RequiredPathSelectorType<S, R, D>; }; export type OptionalArraySelectorWrapper<S, R, D> = { length: RequiredPathSelectorType<S, number, D>; [K: number]: OptionalPathSelectorType<S, R, D>; }; export type RequiredArrayParametricSelectorWrapper<S, P, R, D> = { length: RequiredPathParametricSelectorType<S, P, number, D>; [K: number]: undefined extends R ? OptionalPathParametricSelectorType<S, P, R, D> : null extends R ? OptionalPathParametricSelectorType<S, P, R, D> : RequiredPathParametricSelectorType<S, P, R, D>; }; export type OptionalArrayParametricSelectorWrapper<S, P, R, D> = { length: RequiredPathParametricSelectorType<S, P, number, D>; [K: number]: OptionalPathParametricSelectorType<S, P, R, D>; }; export type RequiredDataSelectorWrapper<S, R, D> = R extends unknown[] ? RequiredArraySelectorWrapper<S, R[number], D> : R extends object ? RequiredObjectSelectorWrapper<S, R, D> : RequiredSelectorBuilder<S, R, D>; export type OptionalDataSelectorWrapper<S, R, D> = R extends unknown[] ? OptionalArraySelectorWrapper<S, R[number], D> : R extends object ? OptionalObjectSelectorWrapper<S, R, D> : OptionalSelectorBuilder<S, R, D>; export type RequiredDataParametricSelectorWrapper< S, P, R, D > = R extends unknown[] ? RequiredArrayParametricSelectorWrapper<S, P, R[number], D> : R extends object ? RequiredObjectParametricSelectorWrapper<S, P, R, D> : RequiredParametricSelectorBuilder<S, P, R, D>; export type OptionalDataParametricSelectorWrapper< S, P, R, D > = R extends unknown[] ? OptionalArrayParametricSelectorWrapper<S, P, R[number], D> : R extends object ? OptionalObjectParametricSelectorWrapper<S, P, R, D> : OptionalParametricSelectorBuilder<S, P, R, D>; export type RequiredPathSelectorType<S, R, D> = RequiredSelectorBuilder< S, R, D > & RequiredDataSelectorWrapper<S, NonNullable<R>, D>; export type OptionalPathSelectorType<S, R, D> = OptionalSelectorBuilder< S, R, D > & OptionalDataSelectorWrapper<S, NonNullable<R>, D>; export type RequiredPathParametricSelectorType< S, P, R, D > = RequiredParametricSelectorBuilder<S, P, R, D> & RequiredDataParametricSelectorWrapper<S, P, NonNullable<R>, D>; export type OptionalPathParametricSelectorType< S, P, R, D > = OptionalParametricSelectorBuilder<S, P, R, D> & OptionalDataParametricSelectorWrapper<S, P, NonNullable<R>, D>; const isObject = (value: unknown) => value !== null && typeof value === 'object'; const innerCreatePathSelector = <S, P, R>( baseSelector: Function, path: PropertyKey[] = [], ): unknown => { const proxyTarget = (defaultValue?: unknown) => { function resultSelector() { // performance optimisation // eslint-disable-next-line prefer-spread,prefer-rest-params let result = baseSelector.apply(null, arguments); for (let i = 0; i < path.length && isObject(result); i += 1) { result = result[path[i]]; } return result ?? defaultValue; } Object.assign(resultSelector, baseSelector); resultSelector.dependencies = [baseSelector]; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { /* istanbul ignore else */ if (isDebugMode()) { defineDynamicSelectorName(resultSelector, () => { const baseName = getSelectorName(baseSelector); return [baseName, ...path].join('.'); }); } } return resultSelector; }; return new Proxy(proxyTarget, { get: (target, key) => innerCreatePathSelector(baseSelector, [...path, key]), }); }; export function createPathSelector<S, R>( baseSelector: Selector<S, R>, ): undefined extends R ? OptionalPathSelectorType<S, R, [Selector<S, R>]> : null extends R ? OptionalPathSelectorType<S, R, [Selector<S, R>]> : RequiredPathSelectorType<S, R, [Selector<S, R>]>; export function createPathSelector<S, P, R>( baseSelector: ParametricSelector<S, P, R>, ): undefined extends R ? OptionalPathParametricSelectorType<S, P, R, [ParametricSelector<S, P, R>]> : null extends R ? OptionalPathParametricSelectorType<S, P, R, [ParametricSelector<S, P, R>]> : RequiredPathParametricSelectorType<S, P, R, [ParametricSelector<S, P, R>]>; export function createPathSelector<S, P, R>(baseSelector: Function) { return innerCreatePathSelector(baseSelector); }
clock.ts
import { now } from './now'; export function
(): string { return new Date(now()).toLocaleString('en-US', { timeZone: 'UTC' }); }
clock
C_A_logo_title.js
export class Logo{ constructor(root, classNameLogo, classNameTitle) { this.root = root; this.logoclass = classNameLogo; this.titleclass = classNameTitle; this.render(); } render() { this.logo = document.createElement('div'); this.logo.classList.add(this.logoclass); this.logo.innerHTML = '<svg preserveAspectRatio="xMidYMid meet" data-bbox="73.5 60 53 80" viewBox="73.5 60 53 80" xmlns="http://www.w3.org/2000/svg" data-type="shape" role="img"><g><path d="M95.1 74l-21.6 32h9.4l21.6-32h-9.4z"></path><path d="M108 69c2.5 0 4.5-2 4.5-4.5s-2-4.5-4.5-4.5-4.5 2-4.5 4.5 2 4.5 4.5 4.5"></path><path d="M112.2 74l-34.7 52h9.3l34.7-52h-9.3z"></path><path d="M117.1 94l-21.6 32h9.4l21.6-32h-9.4z"></path><path d="M92 140c2.5 0 4.5-2 4.5-4.5s-2-4.5-4.5-4.5-4.5 2-4.5 4.5 2 4.5 4.5 4.5"></path></g></svg>'
this.root.append(this.title); } }
this.root.append(this.logo); this.title = document.createElement('span'); this.title.classList.add(this.titleclass); this.title.textContent = 'Cielo Apparel'
imagereplication_pod_webhook.py
# Copyright Amazon.com, Inc. or its affiliates. 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. import logging import os from copy import deepcopy from typing import Any, Dict, List, Optional import kopf from orbit_controller import ORBIT_API_GROUP, ORBIT_API_VERSION, dynamic_client from orbit_controller.utils import imagereplication_utils CONFIG: Dict[str, Any] @kopf.on.startup() def configure(settings: kopf.OperatorSettings, logger: kopf.Logger, **_: Any) -> None: settings.admission.server = kopf.WebhookServer( cafile="/certs/ca.crt", certfile="/certs/tls.crt", pkeyfile="/certs/tls.key", port=443, ) settings.persistence.progress_storage = kopf.MultiProgressStorage( [ kopf.AnnotationsProgressStorage(prefix="orbit.aws"), kopf.StatusProgressStorage(field="status.orbit-aws"), ] ) settings.persistence.finalizer = "imagereplication-pod-webhook.orbit.aws/kopf-finalizer" settings.posting.level = logging.getLevelName(os.environ.get("EVENT_LOG_LEVEL", "INFO")) global CONFIG CONFIG = imagereplication_utils.get_config() logger.info("CONFIG: %s", CONFIG) def _check_replication_status(value: str, **_: Any) -> bool:
@kopf.index( # type: ignore ORBIT_API_GROUP, ORBIT_API_VERSION, "imagereplications", field="status.replication.replicationStatus", value=_check_replication_status, ) def imagereplications_idx(namespace: str, name: str, spec: kopf.Spec, status: kopf.Status, **_: Any) -> Dict[str, Any]: replication_status = status.get("replication", {}).get("replicationStatus", None) return { spec["destination"]: { "namespace": namespace, "name": name, "source": spec["source"], "replicationStatus": replication_status, } } @kopf.on.mutate("pods", id="update-pod-images") # type: ignore def update_pod_images( spec: kopf.Spec, patch: kopf.Patch, dryrun: bool, logger: kopf.Logger, imagereplications_idx: kopf.Index[str, str], **_: Any, ) -> kopf.Patch: if dryrun: logger.debug("DryRun - Skip Pod Mutation") return patch annotations = {} init_containers: List[Dict[str, Any]] = [] containers: List[Dict[str, Any]] = [] replications = {} def process_containers( src_containers: Optional[List[Dict[str, Any]]], dest_containers: List[Dict[str, Any]] ) -> None: for container in src_containers if src_containers else []: image = container.get("image", "") desired_image = imagereplication_utils.get_desired_image(image=image, config=CONFIG) if image != desired_image: container_copy = deepcopy(container) container_copy["image"] = desired_image dest_containers.append(container_copy) replications[image] = desired_image annotations[f"original-container-image~1{container['name']}"] = image process_containers(spec.get("initContainers", []), init_containers) process_containers(spec.get("containers", []), containers) if replications: client = dynamic_client() for source, destination in replications.items(): if not imagereplications_idx.get(destination, []): imagereplication_utils.create_imagereplication( namespace="orbit-system", source=source, destination=destination, client=client, logger=logger, ) else: logger.debug("Skipping ImageReplication Creation") if annotations: patch["metadata"] = {"annotations": annotations} patch["spec"] = {} if init_containers: patch["spec"]["initContainers"] = init_containers if containers: patch["spec"]["containers"] = containers logger.debug("Patch: %s", str(patch)) return patch
return value not in ["Failed", "MaxAttemptsExceeded"]
inmemorygateway_list.go
/* * Copyright 2019 the original author or 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 * * 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. */ package commands import ( "context" "fmt" "strings" "time" "github.com/projectriff/cli/pkg/cli" "github.com/projectriff/cli/pkg/cli/options" "github.com/projectriff/cli/pkg/cli/printers" streamv1alpha1 "github.com/projectriff/system/pkg/apis/streaming/v1alpha1" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" ) type InMemoryGatewayListOptions struct { options.ListOptions } var ( _ cli.Validatable = (*InMemoryGatewayListOptions)(nil) _ cli.Executable = (*InMemoryGatewayListOptions)(nil) ) func (opts *InMemoryGatewayListOptions) Validate(ctx context.Context) cli.FieldErrors { errs := cli.FieldErrors{} errs = errs.Also(opts.ListOptions.Validate(ctx)) return errs } func (opts *InMemoryGatewayListOptions) Exec(ctx context.Context, c *cli.Config) error { gateways, err := c.StreamingRuntime().InMemoryGateways(opts.Namespace).List(metav1.ListOptions{}) if err != nil { return err } if len(gateways.Items) == 0 { c.Infof("No in-memory gateways found.\n") return nil } tablePrinter := printers.NewTablePrinter(printers.PrintOptions{ WithNamespace: opts.AllNamespaces, }).With(func(h printers.PrintHandler) { columns := opts.printColumns() h.TableHandler(columns, opts.printList) h.TableHandler(columns, opts.print) }) gateways = gateways.DeepCopy() cli.SortByNamespaceAndName(gateways.Items) return tablePrinter.PrintObj(gateways, c.Stdout) } func NewInMemoryGatewayListCommand(ctx context.Context, c *cli.Config) *cobra.Command { opts := &InMemoryGatewayListOptions{} cmd := &cobra.Command{ Use: "list", Short: "table listing of in-memory gateways", Long: strings.TrimSpace(` List in-memory gateways in a namespace or across all namespaces. For detail regarding the status of a single in-memory gateway, run: ` + c.Name + ` streaming inmemory-gateway status <inmemory-gateway-name> `), Example: strings.Join([]string{ fmt.Sprintf("%s streaming inmemory-gateway list", c.Name), fmt.Sprintf("%s streaming inmemory-gateway list %s", c.Name, cli.AllNamespacesFlagName), }, "\n"), PreRunE: cli.ValidateOptions(ctx, opts), RunE: cli.ExecOptions(ctx, c, opts), } cli.AllNamespacesFlag(cmd, c, &opts.Namespace, &opts.AllNamespaces) return cmd } func (opts *InMemoryGatewayListOptions) printList(gateways *streamv1alpha1.InMemoryGatewayList, printOpts printers.PrintOptions) ([]metav1beta1.TableRow, error) { rows := make([]metav1beta1.TableRow, 0, len(gateways.Items)) for i := range gateways.Items { r, err := opts.print(&gateways.Items[i], printOpts) if err != nil { return nil, err } rows = append(rows, r...) } return rows, nil } func (opts *InMemoryGatewayListOptions) print(gateway *streamv1alpha1.InMemoryGateway, _ printers.PrintOptions) ([]metav1beta1.TableRow, error) { now := time.Now() row := metav1beta1.TableRow{ Object: runtime.RawExtension{Object: gateway}, } row.Cells = append(row.Cells, gateway.Name, cli.FormatConditionStatus(gateway.Status.GetCondition(streamv1alpha1.InMemoryGatewayConditionReady)), cli.FormatTimestampSince(gateway.CreationTimestamp, now), ) return []metav1beta1.TableRow{row}, nil } func (opts *InMemoryGatewayListOptions) printColumns() []metav1beta1.TableColumnDefinition { return []metav1beta1.TableColumnDefinition{ {Name: "Name", Type: "string"},
{Name: "Age", Type: "string"}, } }
{Name: "Status", Type: "string"},
pickup_test.go
package easypost_test import ( "testing" "time" "github.com/EasyPost/easypost-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func noonOnNextMonday() time.Time { now := time.Now() date := time.Date( now.Year(), now.Month(), now.Day(), 12, 0, 0, 0, now.Location(), ) wd := date.Weekday() if wd < time.Monday { return date.AddDate(0, 0, int(time.Monday-wd)) } return date.AddDate(0, 0, 7-int(wd-time.Monday)) } func
(t *testing.T) { assert, require := assert.New(t), require.New(t) // Create a Batch containing multiple Shipments. Then we try to buy a // Pickup and assert if it was bought. from, err := TestClient.CreateAddress( &easypost.Address{ Name: "Homer Simpson", Company: "EasyPost", Street1: "1 MONTGOMERY ST STE 400", City: "San Francisco", State: "CA", Zip: "94104", Phone: "415-555-1212", }, &easypost.CreateAddressOptions{Verify: []string{"delivery"}}, ) require.NoError(err) batch, err := TestClient.CreateAndBuyBatch( &easypost.Shipment{ ToAddress: &easypost.Address{ Name: "Bugs Bunny", Street1: "4000 Warner Blvd", City: "Burbank", State: "CA", Zip: "91522", Phone: "818-555-1212", }, FromAddress: from, Parcel: &easypost.Parcel{Weight: 10.2}, Carrier: "USPS", Service: "Priority", }, &easypost.Shipment{ ToAddress: &easypost.Address{ Name: "Bugs Bunny", Street1: "4000 Warner Blvd", City: "Burbank", State: "CA", Zip: "91522", Phone: "818-555-1212", }, FromAddress: &easypost.Address{ Name: "Yosemite Sam", Company: "EasyPost", Street1: "1 Market St", CarrierFacility: "San Francisco", State: "CA", Zip: "94105", Phone: "415-555-1212", }, Parcel: &easypost.Parcel{Weight: 10.2}, Carrier: "USPS", Service: "Priority", }, ) require.NoError(err) for done := false; !done; { time.Sleep(time.Second) switch batch.State { case "creating", "queued_for_purchase", "purchasing": batch, err = TestClient.GetBatch(batch.ID) require.NoError(err) default: done = true } } // Insure the shipments after purchase for i := range batch.Shipments { _, err := TestClient.InsureShipment(batch.Shipments[i].ID, "100.00") assert.NoError(err) } minDatetime := noonOnNextMonday() maxDatetime := minDatetime.AddDate(0, 0, 1) pickup, err := TestClient.CreatePickup( &easypost.Pickup{ Address: from, Batch: batch, Reference: "internal_id_1234", MinDatetime: &minDatetime, MaxDatetime: &maxDatetime, IsAccountAddress: true, Instructions: "Special pickup instructions", }, ) require.NoError(err) require.NotEmpty(pickup.PickupRates) pickup, err = TestClient.BuyPickup(pickup.ID, pickup.PickupRates[0]) require.NoError(err) } func TestSinglePickup(t *testing.T) { require := require.New(t) from, err := TestClient.CreateAddress( &easypost.Address{ Name: "Homer Simpson", Company: "EasyPost", Street1: "1 MONTGOMERY ST STE 400", City: "San Francisco", State: "CA", Zip: "94104", Phone: "415-456-7890", }, &easypost.CreateAddressOptions{Verify: []string{"delivery"}}, ) require.NoError(err) shipment, err := TestClient.CreateShipment( &easypost.Shipment{ ToAddress: &easypost.Address{ Name: "Bugs Bunny", Street1: "4000 Warner Blvd", City: "Burbank", State: "CA", Zip: "91522", Phone: "818-555-1212", }, FromAddress: from, Parcel: &easypost.Parcel{Weight: 21.2}, }, ) require.NoError(err) require.NotEmpty(shipment.Rates) shipment, err = TestClient.BuyShipment( shipment.ID, shipment.Rates[0], "100.00", ) require.NoError(err) minDatetime := noonOnNextMonday() maxDatetime := minDatetime.AddDate(0, 0, 1) pickup, err := TestClient.CreatePickup( &easypost.Pickup{ Address: from, Shipment: shipment, Reference: "internal_id_1234", MinDatetime: &minDatetime, MaxDatetime: &maxDatetime, IsAccountAddress: true, Instructions: "Special pickup instructions", }, ) require.NotEmpty(pickup.PickupRates) // This is probably a bug in the API. It always returns a rate, but isn't // always a valid one. pickup, err = TestClient.BuyPickup(pickup.ID, pickup.PickupRates[0]) if err != nil { require.Contains( err.Error(), "schedule and change requests must contain", ) } }
TestPickupBatch
_shells.py
# built-in from typing import List, Type # app from ._base import BaseShell from ._manager import Shells from ._utils import is_windows def _register_shell(cls: Type[BaseShell]) -> Type[BaseShell]: if cls.name in Shells.shells: raise NameError('already registered: ' + cls.name) Shells.shells[cls.name] = cls return cls @_register_shell class CmdShell(BaseShell): name = 'cmd' activate = 'activate.bat' interactive = False @property def command(self): return [self.executable, '/k', self.entrypoint] @_register_shell class PowerShell(BaseShell): name = 'powershell' activate = 'activate.ps1' interactive = False @property def command(self): return [self.executable, '-executionpolicy', 'bypass', '-NoExit', '-NoLogo', '-File', self.activate] @_register_shell class BashShell(BaseShell): name = 'bash' activate = 'activate' interactive = True @_register_shell class ShShell(BaseShell): name = 'sh' activate = 'activate' interactive = True @property def
(self) -> str: return '. "{}"'.format(str(self.entrypoint)) @_register_shell class FishShell(BaseShell): name = 'fish' activate = 'activate.fish' interactive = True @_register_shell class ZshShell(BaseShell): name = 'zsh' activate = 'activate' interactive = True @_register_shell class XonShell(BaseShell): name = 'xonsh' activate = 'activate' interactive = not is_windows() @property def command(self): path = str(self.bin_path.parent) if self.interactive: return '$PATH.insert(0, "{}")'.format(path) return [self.executable, '-i', '-D', 'VIRTUAL_ENV="{}"'.format(path)] @property def args(self) -> List[str]: return ['-i', '-D', 'VIRTUAL_ENV=' + str(self.bin_path.parent)] @_register_shell class TcShell(BaseShell): name = 'tcsh' activate = 'activate.csh' interactive = True @_register_shell class CShell(BaseShell): name = 'csh' activate = 'activate.csh' interactive = True
command
AddProfileLocation.js
import React, { Fragment, useState } from 'react' import PropTypes from 'prop-types' import { withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; import { addProfileLocation } from '../../actions/profile'; import countries from '../../utils/countries'; import states from '../../utils/states'; const AddProfileLocation = ({ addProfileLocation, history }) => { const [formData, setFormData] = useState({ country: '', state: '', city: '', zip: '' }); const { country, state, city, zip } = formData; const [showRegion, openRegionForm] = useState(false); const openRegion = () => openRegionForm(showRegion => true); const closeRegion = () => openRegionForm(showRegion => false); const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); const onArea = e => { if (e.target.id === 'mylocation') { setFormData({ ...formData, area: 'My Location (see profile)' }); } else { setFormData({ ...formData, area: e.target.id.toUpperCase() }) } } return ( <Fragment> <h1 className="large text-primary"> Add Location to your profile </h1> <p className="lead"> <i className="fas fa-code-branch"></i> Add any stuff or services you typically look for </p> <small>* = required field</small> <form className="form" onSubmit={e => { e.preventDefault(); addProfileLocation(formData,history); }}> <div className="form-group"> <h4>Service Area (optional)</h4> <div className="btn-group btn-group-toggle" data-toggle="buttons"> <label className="btn btn-lt-green"> <input type="radio" name="area" id="regional" onChange={(e) => onArea(e)} onClick={openRegion}/> Regional </label> <label className="btn btn-lt-orange"> <input type="radio" name="area" id="mylocation" onChange={(e) => onArea(e)} onClick={closeRegion} /> At My Location </label> <label className="btn btn-lt-yellow"> <input type="radio" name="area" id="worldwide" onChange={(e) => onArea(e)} onClick={closeRegion}/> Wordlwide </label> </div> <div className={showRegion ? 'show' : 'hide'}> <div id="region_selection_list"> <div id="location_root_region_select"> <label>Country</label> <select name="country" onChange={(e) => onChange(e)}> <option></option> { countries.map(country => ( <option value={country.name} key={country.code}>{country.name}</option> ))} </select> </div> <div className={country === 'United States' ? 'show' : 'hide'}> <label>State</label> <select name="state" onChange={(e) => onChange(e)}> <option></option> { states.map(state => ( <option value={state.abbreviation} key={state.abbreviation}>{state.name}</option> ))} </select> <label htmlFor="zip">Zip Code</label> <input type="text" placeholder="zip code" name="zip" value={zip} onChange={e => onChange(e)} /> miles from my location (for information only, see profile)<br/> </div> </div> </div> </div> <input type="submit" className="btn btn-primary my-1" /> </form> </Fragment> ) } AddProfileLocation.propTypes = { addProfileLocation: PropTypes.func.isRequired }
export default connect(null, { addProfileLocation })(withRouter(AddProfileLocation));
ifftn.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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. import numpy as np from ... import opcodes as OperandDef from ..datasource import tensor as astensor from .core import TensorComplexFFTNMixin, validate_fftn, TensorStandardFFTN class
(TensorStandardFFTN, TensorComplexFFTNMixin): _op_type_ = OperandDef.IFFTN def __init__(self, shape=None, axes=None, norm=None, **kw): super().__init__(_shape=shape, _axes=axes, _norm=norm, **kw) def ifftn(a, s=None, axes=None, norm=None): """ Compute the N-dimensional inverse discrete Fourier Transform. This function computes the inverse of the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional tensor by means of the Fast Fourier Transform (FFT). In other words, ``ifftn(fftn(a)) == a`` to within numerical accuracy. For a description of the definitions and conventions used, see `mt.fft`. The input, analogously to `ifft`, should be ordered in the same way as is returned by `fftn`, i.e. it should have the term for zero frequency in all axes in the low-order corner, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency. Parameters ---------- a : array_like Input tensor, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). This corresponds to ``n`` for ``ifft(x, n)``. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input along the axes specified by `axes` is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the IFFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. Repeated indices in `axes` means that the inverse transform over that axis is performed multiple times. norm : {None, "ortho"}, optional Normalization mode (see `mt.fft`). Default is None. Returns ------- out : complex Tensor The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` or `a`, as explained in the parameters section above. Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- mt.fft : Overall view of discrete Fourier transforms, with definitions and conventions used. fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse. ifft : The one-dimensional inverse FFT. ifft2 : The two-dimensional inverse FFT. ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning of tensor. Notes ----- See `mt.fft` for definitions and conventions used. Zero-padding, analogously with `ifft`, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before `ifftn` is called. Examples -------- >>> import mars.tensor as mt >>> a = mt.eye(4) >>> mt.fft.ifftn(mt.fft.fftn(a, axes=(0,)), axes=(1,)).execute() array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]]) Create and plot an image with band-limited frequency content: >>> import matplotlib.pyplot as plt >>> n = mt.zeros((200,200), dtype=complex) >>> n[60:80, 20:40] = mt.exp(1j*mt.random.uniform(0, 2*mt.pi, (20, 20))) >>> im = mt.fft.ifftn(n).real >>> plt.imshow(im.execute()) <matplotlib.image.AxesImage object at 0x...> >>> plt.show() """ a = astensor(a) axes = validate_fftn(a, s=s, axes=axes, norm=norm) op = TensorIFFTN(shape=s, axes=axes, norm=norm, dtype=np.dtype(np.complex_)) return op(a)
TensorIFFTN
customsmarttile.py
import kivy from functools import partial kivy.require('2.0.0') from kivymd.uix.imagelist import SmartTile
class CustomSmartTile(SmartTile): def __init__(self, **kwargs): super(CustomSmartTile, self).__init__(**kwargs) self.height = '240dp' self.size_hint_y = None self.box_color = [0, 0, 0, 0] self.on_press = partial(self._maximize, self.source) def _maximize(self, file): self.parent.parent.parent.manager.get_screen(Screen.ImageView.value).file_name = file self.parent.parent.parent.manager.current = Screen.ImageView.value
from constants import Screen
mod.rs
#[cfg(feature = "hosted")] pub async fn run() { handlers::hosted::serve().await; } #[cfg(feature = "aws-lambda")] pub async fn run() { handlers::lambda::run().await; }
// several repeats of the run() command but separated into several cfg macros, oh man mod handlers; mod routing;
genesis_test.go
package genesis import ( "encoding/hex" "fmt" "math" "testing" "time" "github.com/spf13/viper" "github.com/stretchr/testify/require" beacon "github.com/oasisprotocol/oasis-core/go/beacon/api" "github.com/oasisprotocol/oasis-core/go/common" "github.com/oasisprotocol/oasis-core/go/common/cbor" "github.com/oasisprotocol/oasis-core/go/common/crypto/hash" "github.com/oasisprotocol/oasis-core/go/common/crypto/signature" memorySigner "github.com/oasisprotocol/oasis-core/go/common/crypto/signature/signers/memory" "github.com/oasisprotocol/oasis-core/go/common/entity" "github.com/oasisprotocol/oasis-core/go/common/node" "github.com/oasisprotocol/oasis-core/go/common/quantity" "github.com/oasisprotocol/oasis-core/go/common/sgx" "github.com/oasisprotocol/oasis-core/go/common/version" consensus "github.com/oasisprotocol/oasis-core/go/consensus/genesis" tendermint "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/api" genesis "github.com/oasisprotocol/oasis-core/go/genesis/api" genesisTestHelpers "github.com/oasisprotocol/oasis-core/go/genesis/tests" governance "github.com/oasisprotocol/oasis-core/go/governance/api" keymanager "github.com/oasisprotocol/oasis-core/go/keymanager/api" cmdFlags "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common/flags" registry "github.com/oasisprotocol/oasis-core/go/registry/api" roothash "github.com/oasisprotocol/oasis-core/go/roothash/api" scheduler "github.com/oasisprotocol/oasis-core/go/scheduler/api" staking "github.com/oasisprotocol/oasis-core/go/staking/api" "github.com/oasisprotocol/oasis-core/go/staking/api/token" stakingTests "github.com/oasisprotocol/oasis-core/go/staking/tests" upgrade "github.com/oasisprotocol/oasis-core/go/upgrade/api" ) // Note: If you are here wanting to alter the genesis document used for // the node that is spun up as part of the tests, you really want // consensus/tendermint/tests/genesis/genesis.go. func testDoc() genesis.Document { return genesis.Document{ Height: 1, ChainID: genesisTestHelpers.TestChainID, Time: time.Unix(1574858284, 0), HaltEpoch: beacon.EpochTime(math.MaxUint64), Beacon: beacon.Genesis{ Parameters: beacon.ConsensusParameters{ Backend: beacon.BackendInsecure, DebugMockBackend: true, InsecureParameters: &beacon.InsecureParameters{}, }, }, Registry: registry.Genesis{ Parameters: registry.ConsensusParameters{ DebugAllowUnroutableAddresses: true, DebugBypassStake: true, EnableRuntimeGovernanceModels: map[registry.RuntimeGovernanceModel]bool{ registry.GovernanceEntity: true, registry.GovernanceRuntime: true, registry.GovernanceConsensus: true, }, }, }, Governance: governance.Genesis{ Parameters: governance.ConsensusParameters{ StakeThreshold: 90, VotingPeriod: 100, UpgradeCancelMinEpochDiff: 200, UpgradeMinEpochDiff: 200, }, }, Scheduler: scheduler.Genesis{ Parameters: scheduler.ConsensusParameters{ MinValidators: 1, MaxValidators: 100, MaxValidatorsPerEntity: 100, DebugBypassStake: true, // Zero RewardFactorEpochElectionAny is normal. }, }, Consensus: consensus.Genesis{ Backend: tendermint.BackendName, Parameters: consensus.Parameters{ TimeoutCommit: 1 * time.Millisecond, SkipTimeoutCommit: true, }, }, Staking: stakingTests.GenesisState(), } } func signEntityOrDie(signer signature.Signer, e *entity.Entity) *entity.SignedEntity { signedEntity, err := entity.SignEntity(signer, registry.RegisterGenesisEntitySignatureContext, e) if err != nil { panic(err) } return signedEntity } func signNodeOrDie(signers []signature.Signer, n *node.Node) *node.MultiSignedNode { signedNode, err := node.MultiSignNode( signers, registry.RegisterGenesisNodeSignatureContext, n, ) if err != nil { panic(err) } return signedNode } func hex2ns(str string, force bool) common.Namespace { var ns common.Namespace if force { b, err := hex.DecodeString(str) if err != nil { panic(err) } copy(ns[:], b) return ns } if err := ns.UnmarshalHex(str); err != nil { panic(err) } return ns } func TestGenesisChainContext(t *testing.T) { // Ensure that the chain context is stable. stableDoc := testDoc() // NOTE: Staking part is not stable as it generates a new public key // on each run.
stableDoc.Staking = staking.Genesis{} // Having to update this every single time the genesis structure // changes isn't annoying at all. require.Equal(t, "0847c60a14845166c38d1b46ed275708c5ef07aba45aa0ecace4715505ad146f", stableDoc.ChainContext()) } func TestGenesisSanityCheck(t *testing.T) { viper.Set(cmdFlags.CfgDebugDontBlameOasis, true) require := require.New(t) // First, set up a few things we'll need in the tests below. signer := memorySigner.NewTestSigner("genesis sanity checks signer") nodeSigner := memorySigner.NewTestSigner("node genesis sanity checks signer") nodeConsensusSigner := memorySigner.NewTestSigner("node consensus genesis sanity checks signer") nodeP2PSigner := memorySigner.NewTestSigner("node P2P genesis sanity checks signer") nodeTLSSigner := memorySigner.NewTestSigner("node TLS genesis sanity checks signer") validPK := signer.Public() var validNS common.Namespace _ = validNS.UnmarshalBinary(validPK[:]) invalidPK := memorySigner.NewTestSigner("invalid genesis sanity checks signer").Public() require.NoError(invalidPK.Blacklist(), "blacklist invalid signer") unknownPK := memorySigner.NewTestSigner("unknown genesis sanity checks signer").Public() signature.BuildPublicKeyBlacklist(true) var emptyHash hash.Hash emptyHash.Empty() var nonEmptyHash hash.Hash _ = nonEmptyHash.UnmarshalHex("1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef") // Note that this test entity has no nodes by design, those will be added // later by various tests. testEntity := &entity.Entity{ Versioned: cbor.NewVersioned(entity.LatestDescriptorVersion), ID: validPK, } signedTestEntity := signEntityOrDie(signer, testEntity) kmRuntimeID := hex2ns("4000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff", false) testKMRuntime := &registry.Runtime{ Versioned: cbor.NewVersioned(registry.LatestRuntimeDescriptorVersion), ID: kmRuntimeID, EntityID: testEntity.ID, Kind: registry.KindKeyManager, TEEHardware: node.TEEHardwareIntelSGX, Version: registry.VersionInfo{ TEE: cbor.Marshal(node.SGXConstraints{ Enclaves: []sgx.EnclaveIdentity{{}}, }), }, AdmissionPolicy: registry.RuntimeAdmissionPolicy{ EntityWhitelist: &registry.EntityWhitelistRuntimeAdmissionPolicy{ Entities: map[signature.PublicKey]registry.EntityWhitelistConfig{ validPK: {}, }, }, }, GovernanceModel: registry.GovernanceEntity, } testRuntimeID := hex2ns("0000000000000000000000000000000000000000000000000000000000000001", false) testRuntime := &registry.Runtime{ Versioned: cbor.NewVersioned(registry.LatestRuntimeDescriptorVersion), ID: testRuntimeID, EntityID: testEntity.ID, Kind: registry.KindCompute, KeyManager: &testKMRuntime.ID, Executor: registry.ExecutorParameters{ GroupSize: 1, RoundTimeout: 20, }, TxnScheduler: registry.TxnSchedulerParameters{ Algorithm: "simple", BatchFlushTimeout: 1 * time.Second, MaxBatchSize: 1, MaxBatchSizeBytes: 1024, ProposerTimeout: 20, }, AdmissionPolicy: registry.RuntimeAdmissionPolicy{ AnyNode: &registry.AnyNodeRuntimeAdmissionPolicy{}, }, Constraints: map[scheduler.CommitteeKind]map[scheduler.Role]registry.SchedulingConstraints{ scheduler.KindComputeExecutor: { scheduler.RoleWorker: { MinPoolSize: &registry.MinPoolSizeConstraint{ Limit: 1, }, }, }, }, TEEHardware: node.TEEHardwareIntelSGX, Version: registry.VersionInfo{ TEE: cbor.Marshal(node.SGXConstraints{ Enclaves: []sgx.EnclaveIdentity{{}}, }), }, GovernanceModel: registry.GovernanceEntity, } var testConsensusAddress node.ConsensusAddress _ = testConsensusAddress.UnmarshalText([]byte("[email protected]:1234")) var testAddress node.Address _ = testAddress.UnmarshalText([]byte("127.0.0.1:1234")) testNode := &node.Node{ Versioned: cbor.NewVersioned(node.LatestNodeDescriptorVersion), ID: nodeSigner.Public(), EntityID: testEntity.ID, Expiration: 10, Roles: node.RoleValidator, TLS: node.TLSInfo{ PubKey: nodeTLSSigner.Public(), Addresses: []node.TLSAddress{ {PubKey: nodeTLSSigner.Public(), Address: testAddress}, }, }, P2P: node.P2PInfo{ ID: nodeP2PSigner.Public(), Addresses: []node.Address{testAddress}, }, Consensus: node.ConsensusInfo{ ID: nodeConsensusSigner.Public(), Addresses: []node.ConsensusAddress{testConsensusAddress}, }, } nodeSigners := []signature.Signer{ nodeSigner, nodeP2PSigner, nodeTLSSigner, nodeConsensusSigner, } signedTestNode := signNodeOrDie(nodeSigners, testNode) // Test genesis document should pass sanity check. d := testDoc() require.NoError(d.SanityCheck(), "test genesis document should be valid") // Test top-level genesis checks. d = testDoc() d.Height = -123 require.Error(d.SanityCheck(), "height < 0 should be invalid") d = testDoc() d.Height = 0 require.Error(d.SanityCheck(), "height < 1 should be invalid") d = testDoc() d.ChainID = " \t" require.Error(d.SanityCheck(), "empty chain ID should be invalid") d = testDoc() d.Beacon.Base = 10 d.HaltEpoch = 5 require.Error(d.SanityCheck(), "halt epoch in the past should be invalid") // Test consensus genesis checks. d = testDoc() d.Consensus.Parameters.TimeoutCommit = 0 d.Consensus.Parameters.SkipTimeoutCommit = false require.Error(d.SanityCheck(), "too small timeout commit should be invalid") d = testDoc() d.Consensus.Parameters.TimeoutCommit = 0 d.Consensus.Parameters.SkipTimeoutCommit = true require.NoError(d.SanityCheck(), "too small timeout commit should be allowed if it's skipped") // Test beacon genesis checks. d = testDoc() d.Beacon.Base = beacon.EpochInvalid require.Error(d.SanityCheck(), "invalid base epoch should be rejected") d = testDoc() d.Beacon.Parameters.DebugMockBackend = false d.Beacon.Parameters.InsecureParameters = &beacon.InsecureParameters{ Interval: 0, } require.Error(d.SanityCheck(), "invalid epoch interval should be rejected") // Test keymanager genesis checks. d = testDoc() d.KeyManager = keymanager.Genesis{ Statuses: []*keymanager.Status{ { ID: testRuntimeID, }, }, } require.Error(d.SanityCheck(), "invalid keymanager runtime should be rejected") d = testDoc() d.KeyManager = keymanager.Genesis{ Statuses: []*keymanager.Status{ { ID: validNS, Nodes: []signature.PublicKey{invalidPK}, }, }, } require.Error(d.SanityCheck(), "invalid keymanager node should be rejected") // Test roothash genesis checks. // First we define a helper function for calling the SanityCheck() on RuntimeStates. rtsSanityCheck := func(g roothash.Genesis, isGenesis bool) error { for _, rts := range g.RuntimeStates { if err := rts.SanityCheck(isGenesis); err != nil { return err } } return nil } d = testDoc() d.RootHash.RuntimeStates = make(map[common.Namespace]*roothash.GenesisRuntimeState) d.RootHash.RuntimeStates[validNS] = &roothash.GenesisRuntimeState{ RuntimeGenesis: registry.RuntimeGenesis{ StateRoot: emptyHash, Round: 0, }, } require.NoError(rtsSanityCheck(d.RootHash, false), "empty StateRoot should pass") require.NoError(rtsSanityCheck(d.RootHash, true), "empty StateRoot should pass") d = testDoc() d.RootHash.RuntimeStates = make(map[common.Namespace]*roothash.GenesisRuntimeState) d.RootHash.RuntimeStates[validNS] = &roothash.GenesisRuntimeState{ RuntimeGenesis: registry.RuntimeGenesis{ StateRoot: nonEmptyHash, Round: 0, }, } require.NoError(rtsSanityCheck(d.RootHash, false), "non-empty StateRoot should pass") require.NoError(rtsSanityCheck(d.RootHash, true), "non-empty StateRoot should pass") // Test registry genesis checks. d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} require.NoError(d.SanityCheck(), "test entity should pass") d = testDoc() te := *testEntity te.ID = invalidPK signedBrokenEntity := signEntityOrDie(signer, &te) d.Registry.Entities = []*entity.SignedEntity{signedBrokenEntity} require.Error(d.SanityCheck(), "invalid test entity ID should be rejected") d = testDoc() te = *testEntity te.Nodes = []signature.PublicKey{invalidPK} signedBrokenEntity = signEntityOrDie(signer, &te) d.Registry.Entities = []*entity.SignedEntity{signedBrokenEntity} require.Error(d.SanityCheck(), "test entity's invalid node public key should be rejected") d = testDoc() te = *testEntity signedBrokenEntity, err := entity.SignEntity(signer, signature.NewContext("genesis sanity check invalid ctx"), &te) if err != nil { panic(err) } d.Registry.Entities = []*entity.SignedEntity{signedBrokenEntity} require.Error(d.SanityCheck(), "test entity with invalid signing context should be rejected") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} require.NoError(d.SanityCheck(), "test keymanager runtime should pass") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.NoError(d.SanityCheck(), "test runtimes should pass") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testRuntime, testKMRuntime} require.NoError(d.SanityCheck(), "test runtimes in reverse order should pass") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testRuntime} require.Error(d.SanityCheck(), "test runtime with missing keymanager runtime should be rejected") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime, testRuntime} require.Error(d.SanityCheck(), "duplicate runtime IDs should be rejected") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} testRuntime.GovernanceModel = registry.GovernanceRuntime d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.NoError(d.SanityCheck(), "runtime with runtime gov model should pass") d = testDoc() delete(d.Registry.Parameters.EnableRuntimeGovernanceModels, registry.GovernanceRuntime) d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.Error(d.SanityCheck(), "runtime with runtime gov model should be rejected") testRuntime.GovernanceModel = registry.GovernanceEntity d = testDoc() delete(d.Registry.Parameters.EnableRuntimeGovernanceModels, registry.GovernanceEntity) d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.Error(d.SanityCheck(), "runtime with entity gov model should be rejected") d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} testRuntime.GovernanceModel = registry.GovernanceConsensus d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.NoError(d.SanityCheck(), "runtime with consensus gov model should pass") d = testDoc() d.Registry.Parameters.EnableRuntimeGovernanceModels[registry.GovernanceConsensus] = false d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.Error(d.SanityCheck(), "runtime with consensus gov model should be rejected (1)") d = testDoc() delete(d.Registry.Parameters.EnableRuntimeGovernanceModels, registry.GovernanceConsensus) d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.Error(d.SanityCheck(), "runtime with consensus gov model should be rejected (2)") testRuntime.GovernanceModel = registry.GovernanceEntity d = testDoc() d.Registry.Entities = []*entity.SignedEntity{signedTestEntity} testKMRuntime.GovernanceModel = registry.GovernanceRuntime d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} require.Error(d.SanityCheck(), "non-compute runtime with runtime gov model should be rejected") testKMRuntime.GovernanceModel = registry.GovernanceEntity // TODO: fiddle with executor/merge/txnsched parameters. d = testDoc() te = *testEntity te.Nodes = []signature.PublicKey{testNode.ID} signedEntityWithTestNode := signEntityOrDie(signer, &te) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{} d.Registry.Nodes = []*node.MultiSignedNode{signedTestNode} require.NoError(d.SanityCheck(), "entity with node should pass") d = testDoc() te = *testEntity te.Nodes = []signature.PublicKey{unknownPK} signedEntityWithBrokenNode := signEntityOrDie(signer, &te) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithBrokenNode} d.Registry.Runtimes = []*registry.Runtime{} d.Registry.Nodes = []*node.MultiSignedNode{signedTestNode} require.Error(d.SanityCheck(), "node not listed among controlling entity's nodes should be rejected") d = testDoc() tn := *testNode tn.EntityID = unknownPK signedBrokenTestNode := signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "node with unknown entity ID should be rejected") d = testDoc() tn = *testNode signedBrokenTestNode, err = node.MultiSignNode( []signature.Signer{ signer, }, signature.NewContext("genesis sanity check test invalid node ctx"), &tn, ) if err != nil { panic(err) } d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "node with wrong signing context should be rejected") d = testDoc() tn = *testNode tn.Roles = 1<<16 | 1<<17 signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "node with any reserved role bits set should be rejected") d = testDoc() tn = *testNode tn.Roles = 0 signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "node without any role bits set should be rejected") d = testDoc() tn = *testNode tn.TLS.PubKey = signature.PublicKey{} signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "node with invalid TLS public key should be rejected") d = testDoc() tn = *testNode tn.Consensus.ID = invalidPK signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "node with invalid consensus ID should be rejected") d = testDoc() tn = *testNode tn.Roles = node.RoleComputeWorker signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "compute node without runtimes should be rejected") d = testDoc() tn = *testNode tn.Roles = node.RoleKeyManager signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "keymanager node without runtimes should be rejected") d = testDoc() tn = *testNode tn.Roles = node.RoleKeyManager tn.Runtimes = []*node.Runtime{ { ID: testKMRuntime.ID, }, } signedKMTestNode := signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedKMTestNode} require.NoError(d.SanityCheck(), "keymanager node with valid runtime should pass") d = testDoc() tn = *testNode tn.Roles = node.RoleKeyManager tn.Runtimes = []*node.Runtime{ { ID: testRuntime.ID, }, } signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "keymanager node with invalid runtime should be rejected") d = testDoc() tn = *testNode tn.Roles = node.RoleKeyManager tn.Runtimes = []*node.Runtime{ { ID: testRuntime.ID, }, } signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "keymanager node with non-KM runtime should be rejected") d = testDoc() tn = *testNode tn.Roles = node.RoleComputeWorker tn.Runtimes = []*node.Runtime{ { ID: testKMRuntime.ID, }, } signedBrokenTestNode = signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedBrokenTestNode} require.Error(d.SanityCheck(), "compute node with non-compute runtime should be rejected") d = testDoc() tn = *testNode tn.Roles = node.RoleComputeWorker tn.Runtimes = []*node.Runtime{ { ID: testRuntime.ID, }, } signedComputeTestNode := signNodeOrDie(nodeSigners, &tn) d.Registry.Entities = []*entity.SignedEntity{signedEntityWithTestNode} d.Registry.Runtimes = []*registry.Runtime{testKMRuntime, testRuntime} d.Registry.Nodes = []*node.MultiSignedNode{signedComputeTestNode} require.NoError(d.SanityCheck(), "compute node with compute runtime should pass") // Test staking genesis checks. testAcc1Address := stakingTests.Accounts.GetAddress(1) testAcc2Address := stakingTests.Accounts.GetAddress(2) d = testDoc() d.Staking.TokenSymbol = "" require.EqualError( d.SanityCheck(), "staking: sanity check failed: token symbol is empty", "empty token symbol should be rejected", ) d = testDoc() d.Staking.TokenSymbol = "foo" require.EqualError( d.SanityCheck(), fmt.Sprintf("staking: sanity check failed: token symbol should match '%s'", token.TokenSymbolRegexp), "lower case token symbol should be rejected", ) d = testDoc() d.Staking.TokenSymbol = "LONGSYMBOL" require.EqualError( d.SanityCheck(), "staking: sanity check failed: token symbol exceeds maximum length", "too long token symbol should be rejected", ) d = testDoc() d.Staking.TokenValueExponent = 21 require.EqualError( d.SanityCheck(), "staking: sanity check failed: token value exponent is invalid", "too large token value exponent should be rejected", ) // NOTE: There doesn't seem to be a way to generate invalid Quantities, so // we're just going to test the code that checks if things add up. d = testDoc() d.Staking.TotalSupply = *quantity.NewFromUint64(100) require.Error(d.SanityCheck(), "invalid total supply should be rejected") d = testDoc() d.Staking.CommonPool = *quantity.NewFromUint64(100) require.Error(d.SanityCheck(), "invalid common pool should be rejected") d = testDoc() d.Staking.LastBlockFees = *quantity.NewFromUint64(100) require.Error(d.SanityCheck(), "invalid last block fees should be rejected") d = testDoc() d.Staking.Ledger[testAcc1Address].General.Balance = *quantity.NewFromUint64(100) require.Error(d.SanityCheck(), "invalid general balance should be rejected") d = testDoc() d.Staking.Ledger[testAcc1Address].Escrow.Active.Balance = *quantity.NewFromUint64(42) require.Error(d.SanityCheck(), "invalid escrow active balance should be rejected") d = testDoc() d.Staking.Ledger[testAcc1Address].Escrow.Debonding.Balance = *quantity.NewFromUint64(100) require.Error(d.SanityCheck(), "invalid escrow debonding balance should be rejected") d = testDoc() d.Staking.Ledger[testAcc1Address].Escrow.Active.TotalShares = *quantity.NewFromUint64(1) require.Error(d.SanityCheck(), "invalid escrow active total shares should be rejected") d = testDoc() d.Staking.Ledger[testAcc1Address].Escrow.Debonding.TotalShares = *quantity.NewFromUint64(1) require.Error(d.SanityCheck(), "invalid escrow debonding total shares should be rejected") d = testDoc() d.Staking.Delegations = map[staking.Address]map[staking.Address]*staking.Delegation{ testAcc1Address: { testAcc2Address: { Shares: *quantity.NewFromUint64(1), }, }, } require.Error(d.SanityCheck(), "invalid delegation should be rejected") d = testDoc() d.Staking.DebondingDelegations = map[staking.Address]map[staking.Address][]*staking.DebondingDelegation{ testAcc1Address: { testAcc2Address: { { Shares: *quantity.NewFromUint64(1), DebondEndTime: 10, }, }, }, } require.Error(d.SanityCheck(), "invalid debonding delegation should be rejected") // Test governance sanity checks. d = testDoc() d.Governance.Parameters.StakeThreshold = 1 require.Error(d.SanityCheck(), "stake threshold too low should be rejected") d = testDoc() d.Governance.Parameters.StakeThreshold = 110 require.Error(d.SanityCheck(), "threshold too high should be rejected") d = testDoc() d.Governance.Parameters.UpgradeCancelMinEpochDiff = 50 require.Error(d.SanityCheck(), "upgrade_cancel_min_epoch_diff < voting_period should be rejected") d = testDoc() d.Governance.Parameters.UpgradeMinEpochDiff = 50 require.Error(d.SanityCheck(), "upgrade_min_epoch_diff < voting_period should be rejected") validTestProposals := func() []*governance.Proposal { return []*governance.Proposal{ { CreatedAt: 1, ClosesAt: 100, Submitter: testAcc2Address, Content: governance.ProposalContent{ Upgrade: &governance.UpgradeProposal{ Descriptor: upgrade.Descriptor{ Versioned: cbor.NewVersioned(upgrade.LatestDescriptorVersion), Handler: "genesis_tests", Target: version.Versions, Epoch: 500, }, }, }, State: governance.StateActive, ID: 1, }, } } d = testDoc() d.Beacon.Base = 10 d.Beacon.Parameters.DebugMockBackend = false d.Beacon.Parameters.InsecureParameters = &beacon.InsecureParameters{ Interval: 100, } d.Governance.Proposals = validTestProposals() require.NoError(d.SanityCheck(), "valid proposal should pass") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].Deposit = *quantity.NewFromUint64(100) require.Error(d.SanityCheck(), "proposal deposit doesn't match governance deposits") d.Staking.GovernanceDeposits = *quantity.NewFromUint64(100) totalSupply := d.Staking.TotalSupply.Clone() require.NoError(totalSupply.Add(&d.Staking.GovernanceDeposits), "totalSupply.Add(GovernanceDeposits)") d.Staking.TotalSupply = *totalSupply require.NoError(d.SanityCheck(), "proposal deposit matches governance deposits") d = testDoc() d.Beacon.Base = 10 d.Beacon.Parameters.DebugMockBackend = false d.Beacon.Parameters.InsecureParameters = &beacon.InsecureParameters{ Interval: 100, } d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].CreatedAt = 15 require.Error(d.SanityCheck(), "proposal created in future") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].Submitter = staking.CommonPoolAddress require.Error(d.SanityCheck(), "proposal submitter reserved address") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].Content.Upgrade = nil require.Error(d.SanityCheck(), "proposal invalid content") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].Content.Upgrade.Target = version.ProtocolVersions{} require.Error(d.SanityCheck(), "proposal upgrade invalid target") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].ClosesAt = 5 require.Error(d.SanityCheck(), "active proposal with past closing epoch") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].Content.Upgrade.Epoch = 2 require.Error(d.SanityCheck(), "active proposal upgrade with past upgrade epoch") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].Results = map[governance.Vote]quantity.Quantity{governance.VoteYes: *quantity.NewFromUint64(1)} require.Error(d.SanityCheck(), "active proposal with non-empty results") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].InvalidVotes = 5 require.Error(d.SanityCheck(), "active proposal with non-empty invalid results") d.Governance.Proposals = validTestProposals() d.Governance.Proposals[0].State = governance.StateRejected require.Error(d.SanityCheck(), "closed proposal with closing epoch in future") d.Governance.Proposals = validTestProposals() d.Governance.VoteEntries = map[uint64][]*governance.VoteEntry{ d.Governance.Proposals[0].ID: { { Voter: testAcc1Address, Vote: governance.VoteYes, }, }, } require.NoError(d.SanityCheck(), "valid vote should pass sanity check") d.Governance.Proposals = validTestProposals() d.Governance.VoteEntries = map[uint64][]*governance.VoteEntry{ d.Governance.Proposals[0].ID: { { Voter: staking.CommonPoolAddress, Vote: governance.VoteYes, }, }, } require.Error(d.SanityCheck(), "vote from a reserved address") d.Governance.VoteEntries = nil descriptor := func(epoch beacon.EpochTime) upgrade.Descriptor { return upgrade.Descriptor{ Versioned: cbor.NewVersioned(upgrade.LatestDescriptorVersion), Handler: "handler_tests", Target: version.Versions, Epoch: epoch, } } d.Governance.Proposals = validTestProposals() d.Governance.Proposals = []*governance.Proposal{ { CreatedAt: 1, ClosesAt: 2, Submitter: testAcc2Address, Content: governance.ProposalContent{ Upgrade: &governance.UpgradeProposal{ Descriptor: descriptor(400), }, }, State: governance.StatePassed, ID: 1, }, } require.NoError(d.SanityCheck(), "valid closed proposal") d.Governance.Proposals = append(d.Governance.Proposals, &governance.Proposal{ CreatedAt: 1, ClosesAt: 2, Submitter: testAcc2Address, Content: governance.ProposalContent{ Upgrade: &governance.UpgradeProposal{ Descriptor: descriptor(710), }, }, State: governance.StatePassed, ID: 2, }) require.NoError(d.SanityCheck(), "valid closed proposal") d.Governance.Proposals = append(d.Governance.Proposals, &governance.Proposal{ CreatedAt: 1, ClosesAt: 2, Submitter: testAcc2Address, Content: governance.ProposalContent{ Upgrade: &governance.UpgradeProposal{ Descriptor: descriptor(410), }, }, State: governance.StatePassed, ID: 3, }) require.Error(d.SanityCheck(), "pending upgrades not UpgradeMinEpochDiff apart") }
views.py
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import exceptions from common.serializers import UserSerializer from core.models import User,Product,Link,OrderItem,Order from common.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticated from .serializers import ProductSerializer from django.core.cache import cache import time # Create your views here. class ProductFrontendAPIView(APIView): # authentication_classes =[JWTAuthentication] # permission_classes=[IsAuthenticated] def get(self, request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) class ProductBackendAPIView(APIView): def get(self, request): products = cache.get('products_backend') if not products:
products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data)
time.sleep(2) products = list(Product.objects.all()) cache.set(products, 'products_backend',timeout=60*30)
random_docs.go
// Copyright 2018 Kuei-chun Chen. All rights reserved. package util import ( "encoding/json" "fmt" "io/ioutil" "math" "math/rand" "regexp" "strconv" "strings" "time" "github.com/simagix/gox" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) const metaEmail = "$email" const metaIP = "$ip" const metaSSN = "$ssn" const metaTEL = "$tel" const metaDate = "$date" const metaOID = "$oId" const numberDecimal = "$numberDecimal" const uuid = "$uuid" // GetDocByTemplate returns a bson.M document func GetDocByTemplate(filename string, meta bool) (bson.M, error) { var buf []byte var err error if buf, err = ioutil.ReadFile(filename); err != nil { return nil, err } v := bson.M{} if err = json.Unmarshal(buf, &v); err != nil { return nil, err } if buf, err = bson.MarshalExtJSON(v, false, false); err != nil { return nil, err } return GetRandomizedDoc(buf, meta) } // GetRandomizedDoc returns a randomized doc from byte string func GetRandomizedDoc(buf []byte, meta bool) (bson.M, error) { var err error str := string(buf) str = strings.ReplaceAll(str, "NaN", "0.0") re := regexp.MustCompile(`{"\$oid":"[a-fA-F0-9]{24}"}`) str = re.ReplaceAllString(str, `"$$oId"`) re = regexp.MustCompile(`{"\$binary":{"base64":"[^"]*","subType":"(0[0-3])"}}`) str = re.ReplaceAllString(str, `{"$$binary":{"base64":"","subType":"$1"}}`) re = regexp.MustCompile(`{"\$binary":{"base64":".{24}","subType":"04"}}`) str = re.ReplaceAllString(str, `"$$uuid"`) re = regexp.MustCompile(`{"\$numberDecimal":"[-+]?[0-9]*\.?[0-9]*(E-)?[0-9]*"}`) str = re.ReplaceAllString(str, `"$$numberDecimal"`) // backward compatible re = regexp.MustCompile(`ObjectId\(\S+\)`) str = re.ReplaceAllString(str, "\"$$oId\"") re = regexp.MustCompile(`NumberDecimal\("?([-+]?[0-9]*\.?[0-9]*)"?\)`) str = re.ReplaceAllString(str, "{\"$$numberDecimal\": $1}") re = regexp.MustCompile(`numberDouble\("?([-+]?[0-9]*\.?[0-9]*)"?\)`) str = re.ReplaceAllString(str, "{\"$$numberDouble\": $1}") str = re.ReplaceAllString(str, "{\"$$numberLong\": $1}") re = regexp.MustCompile(`NumberLong\("?([-+]?[0-9]*\.?[0-9]*)"?\)`) re = regexp.MustCompile(`NumberInt\("?([-+]?[0-9]*\.?[0-9]*)"?\)`) str = re.ReplaceAllString(str, "{\"$$numberInt\": $1}") re = regexp.MustCompile(`ISODate\(\S+\)`) str = re.ReplaceAllString(str, "\"$$date\"") re = regexp.MustCompile(`Number\("?(\d+)"?\)`) str = re.ReplaceAllString(str, "$1") re = regexp.MustCompile(`^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$`) str = re.ReplaceAllString(str, "\"$$email\"") var f interface{} if err = json.Unmarshal([]byte(str), &f); err != nil { return nil, err } doc := make(map[string]interface{}) RandomizeDocument(&doc, f, meta) return doc, err } // RandomizeDocument traverses a doc and replace values with random values according to their data type. func RandomizeDocument(doc *map[string]interface{}, f interface{}, meta bool) { elems := f.(map[string]interface{}) for key, value := range elems { switch o := value.(type) { case map[string]interface{}: subdoc := make(map[string]interface{}) RandomizeDocument(&subdoc, value, meta) (*doc)[key] = subdoc case []interface{}: subdoc := make([]interface{}, len(o)) getArrayOfRandomDocs(o, &subdoc, meta) (*doc)[key] = subdoc case bool: randBool = !randBool (*doc)[key] = randBool case int, int8, int16, int32, int64: if value.(int) == 1 || value.(int) == 0
else { (*doc)[key] = getNumber(value) } case float32, float64: (*doc)[key] = getNumber(value) case string: if meta == false { if value.(string) == metaDate || isDateString(value.(string)) { (*doc)[key] = getDate() continue } else if value.(string) == metaOID || (len(value.(string)) == 24 && isHexString(value.(string))) { (*doc)[key] = primitive.NewObjectID() continue } else if value.(string) == numberDecimal { (*doc)[key] = primitive.NewDecimal128(rand.Uint64(), 0) continue } else if value.(string) == uuid { (*doc)[key] = primitive.Binary{Subtype: 4, Data: []byte(gox.GetRandomDigitString(16))} continue } } (*doc)[key] = getMagicString(value.(string), meta) default: (*doc)[key] = value } } } var randBool bool func getArrayOfRandomDocs(obj []interface{}, doc *[]interface{}, meta bool) { for key, value := range obj { switch o := value.(type) { case bool: randBool = !randBool (*doc)[key] = randBool case int, int8, int16, int32, int64: if value.(int) == 1 || value.(int) == 0 { // 1 may have special meaning of true (*doc)[key] = value } else { (*doc)[key] = getNumber(value) } case float32, float64: (*doc)[key] = getNumber(value) case string: if meta == false { if value.(string) == metaDate || isDateString(value.(string)) { (*doc)[key] = getDate() continue } else if value.(string) == metaOID || (len(value.(string)) == 24 && isHexString(value.(string))) { (*doc)[key] = primitive.NewObjectID() continue } else if value.(string) == numberDecimal { (*doc)[key] = primitive.NewDecimal128(rand.Uint64(), 0) continue } else if value.(string) == uuid { (*doc)[key] = primitive.Binary{Subtype: 4, Data: []byte(gox.GetRandomDigitString(16))} continue } } (*doc)[key] = getMagicString(value.(string), meta) case []interface{}: subdocument := make([]interface{}, len(o)) getArrayOfRandomDocs(o, &subdocument, meta) (*doc)[key] = subdocument case map[string]interface{}: subdoc1 := make(map[string]interface{}) RandomizeDocument(&subdoc1, value, meta) (*doc)[key] = subdoc1 default: (*doc)[key] = value } } } // Returns randomized string. if meta is true, it intends to avoid future regex // actions by replacing the values with $email, $ip, and $date. func getMagicString(str string, meta bool) string { if meta == true { if str == metaEmail || isEmailAddress(str) { return metaEmail } else if str == metaIP || isIP(str) { return metaIP // } else if str == metaSSN || isSSN(str) { // return metaSSN // } else if str == metaTEL || isPhoneNumber(str) { // return metaTEL } else if str == metaDate || isDateString(str) { return metaDate } else if str == metaOID || (len(str) == 24 && isHexString(str)) { return metaOID } else if isHexString(str) { return gox.GetRandomHexString(len(str)) } else if strings.HasPrefix(str, "$number") || str == uuid { return str } } else if str == metaIP || isIP(str) { return getIP() } else if str == metaEmail || isEmailAddress(str) { return GetEmailAddress() // } else if str == metaSSN || isSSN(str) { // return getSSN() // } else if str == metaTEL || isPhoneNumber(str) { // return getPhoneNumber() } else if isHexString(str) { return gox.GetRandomHexString(len(str)) } else if strings.HasPrefix(str, "$") { // could be a variable return str } hdr := "" if n := strings.Index(str, "://"); n > 0 { hdr = str[:n+3] } b := make([]byte, len(str)) for i, c := range str { x := rand.Int() if i < len(hdr) { b[i] = byte(c) } else if c >= 48 && c <= 57 { // digits b[i] = byte(x%10 + 48) } else if c >= 65 && c <= 90 { // A-Z b[i] = byte(x%26 + 65) } else if c >= 97 && c <= 122 { // a-z b[i] = byte(x%26 + 97) } else { b[i] = byte(c) } } return string(b) } func isEmailAddress(str string) bool { var matched = regexp.MustCompile(`^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$`) return matched.MatchString(str) } // GetEmailAddress exposes getEmailAddress() func GetEmailAddress() string { return fmt.Sprintf("%s.%s.%s@%s", fnames[rand.Intn(len(fnames)-1)], string(fnames[rand.Intn(len(fnames)-1)][0]), lnames[rand.Intn(len(lnames)-1)], domains[rand.Intn(len(domains)-1)]) } func isIP(str string) bool { var matched = regexp.MustCompile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`) return matched.MatchString(str) } func getIP() string { return strconv.Itoa(rand.Intn(255)) + "." + strconv.Itoa(rand.Intn(255)) + "." + strconv.Itoa(rand.Intn(255)) + "." + strconv.Itoa(rand.Intn(255)) } func isSSN(str string) bool { var matched = regexp.MustCompile(`^(\d{3}-?\d{2}-?\d{4}|XXX-XX-XXXX)$`) return matched.MatchString(str) } func getSSN() string { return fmt.Sprintf("%v-%v-5408", (100 + rand.Intn(899)), (10 + rand.Intn(89))) } func isPhoneNumber(str string) bool { var matched = regexp.MustCompile(`^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$`) return matched.MatchString(str) } func getPhoneNumber() string { return fmt.Sprintf("(%v) 555-%v", (100 + rand.Intn(899)), (1000 + rand.Intn(8999))) } func isHexString(str string) bool { var matched = regexp.MustCompile(`^[\da-fA-F]+$`) return matched.MatchString(str) } func isDateString(str string) bool { var matched = regexp.MustCompile(`^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])T.*$`) return matched.MatchString(str) } var now = time.Now() var min = now.AddDate(-1, 0, 0).Unix() var max = now.AddDate(0, 3, 0).Unix() var delta = max - min func getDate() time.Time { sec := rand.Int63n(delta) + min return time.Unix(sec, 0) } func getNumber(num interface{}) interface{} { var value float64 switch num.(type) { case int: return int(getRandomNumber(float64(num.(int)))) case int8: return int8(getRandomNumber(float64(num.(int8)))) case int32: return int32(getRandomNumber(float64(num.(int32)))) case int64: return int64(getRandomNumber(float64(num.(int64)))) case float32: return float32(getRandomNumber(float64(num.(float32)))) case float64: return getRandomNumber(num.(float64)) default: return value } } func getRandomNumber(x float64) float64 { mul := float64(1) for mul <= x { mul *= 10 } v := mul * (rand.Float64() + .1) if x == math.Trunc(x) { return math.Round(v) } return math.Round(v*100) / 100 } var quotes = []string{ "Frankly, my dear, I don't give a damn.", "I'm going to make him an offer he can't refuse.", "Toto, I've a feeling we're not in Kansas anymore.", "Here's looking at you, kid.", "Go ahead, make my day.", "All right, Mr. DeMille, I'm ready for my close-up.", "May the Force be with you.", "Fasten your seatbelts. It's going to be a bumpy night.", "You talkin' to me?", "What we've got here is failure to communicate.", "I love the smell of napalm in the morning.", "Love means never having to say you're sorry.", "The stuff that dreams are made of.", "E.T. phone home.", "They call me Mister Tibbs!", "You're gonna need a bigger boat.", "Of all the gin joints in all the towns in all the world, she walks into mine.", "Bond. James Bond.", "There's no place like home.", "Show me the money!", } var domains = []string{"gmail.com", "me.com", "yahoo.com", "outlook.com", "google.com", "simagix.com", "aol.com", "mongodb.com", "example.com", "cisco.com", "microsoft.com", "facebook.com", "apple.com", "amazon.com", "oracle.com"} var fnames = []string{"Andrew", "Ava", "Becky", "Brian", "Cindy", "Connie", "David", "Dawn", "Elizabeth", "Emma", "Felix", "Frank", "George", "Grace", "Hector", "Henry", "Ian", "Isabella", "Jennifer", "John", "Kate", "Kenneth", "Linda", "Logan", "Mary", "Michael", "Nancy", "Noah", "Olivia", "Otis", "Patricia", "Peter", "Quentin", "Quinn", "Richard", "Robert", "Samuel", "Sophia", "Todd", "Tom", "Ulysses", "Umar", "Vincent", "Victoria", "Wesley", "Willaim", "Xavier", "Xena", "Yosef", "Yuri", "Zach", "Zoey", } var lnames = []string{"Smith", "Johnson", "Williams", "Brown", "Jones", "Miller", "Davis", "Garcia", "Rodriguez", "Chen", "Adams", "Arthur", "Bush", "Carter", "Clinton", "Eisenhower", "Ford", "Grant", "Harrison", "Hoover"}
{ // 1 may have special meaning of true (*doc)[key] = value }
loggers_test.go
package logging import ( "github.com/sirupsen/logrus" "testing" ) func TestLoggers(t *testing.T)
{ Init("logs", "debug", 0) CLog().Debugf("format debug clog msg [%s]", "test clog msg") CLog().WithFields(logrus.Fields{"name": "clog_test", "type": "clog"}).Debugf("format debug clog msg [%s]", "test clog msg") VLog().Debugf("format debug vlog msg [%s]", "test vlog msg") VLog().WithFields(logrus.Fields{"name": "vlog_test", "type": "vlog"}).Debugf("format debug vlog msg [%s]", "test vlog msg") }
var-format.js
var:1:6 > 1 | const t = 'hello';   |  ^ "t" is defined but never used (remove-unused-variables)   2 | 
✖ 1 errors in 1 files  fixable with the `--fix` option
  3 | 
test_formatters_value.py
#!/usr/bin/env python # # 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. import six from cliff.formatters import value from cliff.tests import test_columns def test_value_formatter(): sf = value.ValueFormatter() c = ('a', 'b', 'c', 'd') d = ('A', 'B', 'C', '"no escape me"') expected = 'A\nB\nC\n"no escape me"\n' output = six.StringIO() sf.emit_one(c, d, output, None) actual = output.getvalue() assert expected == actual def test_value_formatter_formattable_column(): sf = value.ValueFormatter() c = ('a', 'b', 'c', 'd') d = ('A', 'B', 'C', test_columns.FauxColumn(['the', 'value'])) expected = "A\nB\nC\n['the', 'value']\n" output = six.StringIO() sf.emit_one(c, d, output, None) actual = output.getvalue() assert expected == actual def test_value_list_formatter(): sf = value.ValueFormatter() c = ('a', 'b', 'c') d1 = ('A', 'B', 'C') d2 = ('D', 'E', 'F') data = [d1, d2] expected = 'A B C\nD E F\n' output = six.StringIO() sf.emit_list(c, data, output, None) actual = output.getvalue() assert expected == actual def test_value_list_formatter_formattable_column():
sf = value.ValueFormatter() c = ('a', 'b', 'c') d1 = ('A', 'B', test_columns.FauxColumn(['the', 'value'])) data = [d1] expected = "A B ['the', 'value']\n" output = six.StringIO() sf.emit_list(c, data, output, None) actual = output.getvalue() assert expected == actual
main.rs
#![no_std] #![no_main] #![feature(custom_test_frameworks)] #![test_runner(crate::test_runner)] #![reexport_test_harness_main = "test_main"] pub mod vga_buffer; use core::fmt::Write; use core::panic::PanicInfo; #[panic_handler] fn panic(info: &PanicInfo) -> !
#[no_mangle] pub extern "C" fn _start() -> ! { println!("Hello World{}", "!"); #[cfg(test)] test_main(); loop {} } #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u32)] pub enum QemuExitCode { Success = 0x10, Failed = 0x11, } pub fn exit_qemu(exit_code: QemuExitCode) { use x86_64::instructions::port::Port; unsafe { let mut port = Port::new(0xf4); port.write(exit_code as u32); } } #[cfg(test)] fn test_runner(tests: &[&dyn Fn()]) { println!("Running {} tests", tests.len()); for test in tests { test(); } exit_qemu(QemuExitCode::Success); } #[test_case] fn trivial_assertion() { print!("trivial assertion... "); assert_eq!(1, 1); println!("[ok]"); }
{ println!("{}", info); loop {} }
generateUniqueId.js
const crypto = require('crypto');
module.exports = function GenerateUniqueId() { return crypto.randomBytes(4).toString('HEX'); }
cocoa.rs
use std::ffi::CStr; use cocoa::base::{id, nil}; use cocoa::foundation::{NSAutoreleasePool, NSString}; pub fn nsstring(s: &str) -> id /* NSString */ { unsafe { NSString::alloc(nil).init_str(s).autorelease() } } pub trait ToString { fn to_string(self) -> String; } impl<S: NSString> ToString for S { fn
(self) -> String { unsafe { CStr::from_ptr(self.UTF8String()) .to_str() .unwrap() .to_string() } } }
to_string
jquery.scrollorama.js
/* scrollorama - The jQuery plugin for doing cool scrolly stuff by John Polacek (@johnpolacek) Dual licensed under MIT and GPL. */ (function($) { $.scrollorama = function(options) { var scrollorama = this, blocks = [], browserPrefix = '', ieVersion = '', onBlockChange = function() {}, latestKnownScrollY = 0, ticking = false, requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }, defaults = {offset:0, enablePin: true}; scrollorama.settings = $.extend({}, defaults, options); scrollorama.blockIndex = 0; if (options.blocks === undefined) { alert('ERROR: Must assign blocks class selector to scrollorama plugin'); } // PRIVATE FUNCTIONS function init() { var i, block, didScroll, marginTop = false; if (typeof scrollorama.settings.blocks === 'string') { scrollorama.settings.blocks = $(scrollorama.settings.blocks); } // set browser prefix if ($.browser.mozilla) { browserPrefix = '-moz-'; } if ($.browser.webkit) { browserPrefix = '-webkit-'; } if ($.browser.opera) { browserPrefix = '-o-'; } if ($.browser.msie) { browserPrefix = '-ms-'; ieVersion = parseInt($.browser.version, 10); } // create blocks array to contain animation props $('body').css('position','relative'); for (i=0; i<scrollorama.settings.blocks.length; i++) { block = scrollorama.settings.blocks.eq(i); marginTop = block.css('margin-top'); blocks.push({ block: block, top: block.offset().top - (!Boolean(marginTop) ? parseInt(marginTop, 10) : 0), pin: 0, animations:[] }); } // convert block elements to absolute position /* if (scrollorama.settings.enablePin.toString() === 'true') { for (i=0; i<blocks.length; i++) { blocks[i].block .css('position', 'absolute') .css('top', blocks[i].top); } } */ // create scroll-wrap div only once if ($("#scroll-wrap").length === 0) { $('body').prepend('<div id="scroll-wrap"></div>'); } latestKnownScrollY = 0; ticking = false; $(window).on( 'scroll.scrollorama', onScroll ); } function onScroll() { latestKnownScrollY = window.scrollY; requestTick(); } function requestTick() { if(!ticking) { requestAnimFrame(function(){ onScrollorama(); update(); }); } ticking = true; } function update() { // reset the tick so we can // capture the next onScroll ticking = false; } function onScrollorama() { var scrollTop = $(window).scrollTop(), currBlockIndex = getCurrBlockIndex(scrollTop), i, j, anim, startAnimPos, endAnimPos, animPercent, animVal; // update all animations for (i=0; i<blocks.length; i++) { // go through the animations for each block if (blocks[i].animations.length) { for (j=0; j<blocks[i].animations.length; j++) { anim = blocks[i].animations[j]; // if above current block, settings should be at start value if (i > currBlockIndex) { if (currBlockIndex !== i-1 && anim.baseline !== 'bottom') { setProperty(anim.element, anim.property, anim.startVal); } if (blocks[i].pin) { blocks[i].block .css('position', 'absolute') .css('top', blocks[i].top); } } // if below current block, settings should be at end value // unless on an element that gets animated when it hits the bottom of the viewport else if (i < currBlockIndex) { setProperty(anim.element, anim.property, anim.endVal); if (blocks[i].pin) { blocks[i].block .css('position', 'absolute') .css('top', (blocks[i].top + blocks[i].pin)); } } // otherwise, set values per scroll position if (i === currBlockIndex || (currBlockIndex === i-1 && anim.baseline === 'bottom')) { // if block gets pinned, set position fixed if (blocks[i].pin && currBlockIndex === i) { blocks[i].block .css('position', 'fixed') .css('top', 0); } // set start and end animation positions startAnimPos = blocks[i].top + anim.delay; if (anim.baseline === 'bottom') { startAnimPos -= $(window).height(); } endAnimPos = startAnimPos + anim.duration; // if scroll is before start of animation, set to start value if (scrollTop < startAnimPos) { setProperty(anim.element, anim.property, anim.startVal); } // if scroll is after end of animation, set to end value else if (scrollTop > endAnimPos) { setProperty(anim.element, anim.property, anim.endVal); if (blocks[i].pin) { blocks[i].block .css('position', 'absolute') .css('top', (blocks[i].top + blocks[i].pin)); } } // otherwise, set value based on scroll else { // calculate percent to animate animPercent = (scrollTop - startAnimPos) / anim.duration; // account for easing if there is any if ( anim.easing && $.isFunction( $.easing[anim.easing] ) ) { animPercent = $.easing[anim.easing]( animPercent, animPercent*1000, 0, 1, 1000 ); } // then multiply the percent by the value range and calculate the new value animVal = anim.startVal + (animPercent * (anim.endVal - anim.startVal)); setProperty(anim.element, anim.property, animVal); } } } } } // update blockIndex and trigger event if changed if (scrollorama.blockIndex !== currBlockIndex) { scrollorama.blockIndex = currBlockIndex; onBlockChange(); } } function getCurrBlockIndex(scrollTop) { var currBlockIndex = 0, i; for (i=0; i<blocks.length; i++) { // check if block is in view if (blocks[i].top <= scrollTop - scrollorama.settings.offset) { currBlockIndex = i; } } return currBlockIndex; } function setProperty(target, prop, val) { var scaleCSS, currentPosition; if (prop === 'rotate' || prop === 'zoom' || prop === 'scale') { if (prop === 'rotate') { target.css(browserPrefix+'transform', 'rotate('+val+'deg)'); } else if (prop === 'zoom' || prop === 'scale') { scaleCSS = 'scale('+val+')'; if (browserPrefix !== '-ms-') { target.css(browserPrefix+'transform', scaleCSS); } else { target.css('zoom', scaleCSS); } } } else if(prop === 'background-position-x' || prop === 'background-position-y' ) { currentPosition = target.css('background-position').split(' '); if(prop === 'background-position-x') { target.css('background-position',val+'px '+currentPosition[1]); } if(prop === 'background-position-y') { target.css('background-position', currentPosition[0]+' '+val+'px'); } } else if(prop === 'text-shadow' ) { target.css(prop,'0px 0px '+val+'px #ffffff'); } else { target.css(prop, val); } } // PUBLIC FUNCTIONS scrollorama.animate = function(target) { var targetIndex, targetBlock, anim, offset, i, j; /* target = animation target arguments = array of animation parameters anim = object that contains all animation params (created from arguments) offset = positioning helper for pinning animation parameters: delay = amount of scrolling (in pixels) before animation starts duration = amount of scrolling (in pixels) over which the animation occurs property = css property being animated start = start value of the property end = end value of the property pin = pin block during animation duration (applies to all animations within block) baseline = top (default, when block reaches top of viewport) or bottom (when block first comies into view) easing = just like jquery's easing functions */ // if string, convert to DOM object if (typeof target === 'string') { target = $(target); } // find block of target for (i=0; i<blocks.length; i++) { if (blocks[i].block.has(target).length) { targetBlock = blocks[i]; targetIndex = i; } } // add each animation to the blocks animations array from function arguments for (i=1; i<arguments.length; i++) { anim = arguments[i]; // for top/left/right/bottom, set relative positioning if static if (anim.property === 'top' || anim.property === 'left' || anim.property === 'bottom' || anim.property === 'right' ) { if (target.css('position') === 'static') { target.css('position','relative'); } // set anim.start, anim.end defaults cssValue = parseInt(target.css(anim.property),10); if (anim.start === undefined) { anim.start = isNaN(cssValue) ? 0 : cssValue; } else if (anim.end === undefined) { anim.end = isNaN(cssValue) ? 0 : cssValue; } } // set anim.start/anim.end defaults for rotate, zoom/scale, letter-spacing if (anim.property === 'rotate') { if (anim.start === undefined) { anim.start = 0; } if (anim.end === undefined) { anim.end = 0; } } else if (anim.property === 'zoom' || anim.property === 'scale' ) { if (anim.start === undefined) { anim.start = 1; } if (anim.end === undefined) { anim.end = 1; } } else if (anim.property === 'letter-spacing' && target.css(anim.property)) { if (anim.start === undefined) { anim.start = 1; } if (anim.end === undefined) { anim.end = 1; } } // convert background-position property for use on IE8 and lower if (ieVersion && ieVersion < 9 && (anim.property == 'background-position-x' || anim.property == 'background-position-y')) { if (anim.property === 'background-position-x') { anim.property = 'backgroundPositionX'; } else { anim.property = 'backgroundPositionY'; } } if (anim.baseline === undefined) { if (anim.pin || targetBlock.pin || targetIndex === 0) { anim.baseline = 'top'; } else { anim.baseline = 'bottom'; } } if (anim.delay === undefined) { anim.delay = 0; } targetBlock.animations.push({ element: target, delay: anim.delay, duration: anim.duration, property: anim.property, startVal: anim.start !== undefined ? typeof(anim.start) == 'function' ? anim.start() : anim.start : parseInt(target.css(anim.property),10), // if undefined, use current css value endVal: anim.end !== undefined ? typeof(anim.end) == 'function' ? anim.end() : anim.end : parseInt(target.css(anim.property),10), // if undefined, use current css value baseline: anim.baseline !== undefined ? anim.baseline : 'bottom', easing: anim.easing }); if (anim.pin) { if (targetBlock.pin < anim.duration + anim.delay) { offset = anim.duration + anim.delay - targetBlock.pin; targetBlock.pin += offset; // adjust positions of blocks below target block for (j=targetIndex+1; j<blocks.length; j++) { blocks[j].top += offset; blocks[j].block.css('top', blocks[j].top); } } } } onScrollorama(); }; // function for passing blockChange event callback scrollorama.onBlockChange = function(f) { onBlockChange = f; }; // function for getting an array of scrollpoints // (top of each animation block and animation element scroll start point) scrollorama.getScrollpoints = function() { var scrollpoints = [],i,j,anim; for (i=0; i<blocks.length; i++) { scrollpoints.push(blocks[i].top); // go through the animations for each block if (blocks[i].animations.length && blocks[i].pin > 0) { for (j=0; j<blocks[i].animations.length; j++) { anim = blocks[i].animations[j]; scrollpoints.push(blocks[i].top + anim.delay + anim.duration); } } } // make sure scrollpoints are in numeric order scrollpoints.sort(function(a,b) {return a - b;}); return scrollpoints; }; // Remove scrollorama scrollorama.destroy = function () { // Remove animations for (i=0; i<blocks.length; i++) { // Remove CSS rules blocks[i].block.css({ top: '', position: '' }); // Remove scrolloroma-specific attributes delete blocks[i].animations; delete blocks[i].top; delete blocks[i].pin; } // Unbind the window scroll event $(window).off('scroll.scrollorama'); $('#scroll-wrap').remove(); // Remove the scrolloroma object delete scrollorama; }; // INIT init(); return scrollorama; }; // // Easing functions from jQuery UI // $.extend($.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert($.easing.default); return $.easing[$.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t + b; } return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t*t + b; } return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t*t*t + b; } return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t===0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t===d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t===0) { return b; } if (t===d) { return b+c; } if ((t/=d/2) < 1) { return c/2 * Math.pow(2, 10 * (t - 1)) + b; } return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) { return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; } return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158,p=0,a=c; if (t===0) { return b; } if ((t/=d)===1) { return b+c; } if (!p) { p=d*0.3; } if (a < Math.abs(c)) { a=c; s=p/4; } else{ s = p/(2*Math.PI) * Math.asin (c/a); } return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158,p=0,a=c; if (t===0) { return b; } if ((t/=d)===1) { return b+c; } if (!p) { p=d*0.3; } if (a < Math.abs(c)) { a=c; s=p/4; } else { s = p/(2*Math.PI) * Math.asin (c/a); } return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158,p=0,a=c; if (t===0) { return b; } if ((t/=d/2)===2) { return b+c; } if (!p) { p=d*(0.3*1.5); } if (a < Math.abs(c)) { a=c; s=p/4; } else { s = p/(2*Math.PI) * Math.asin (c/a); } if (t < 1) { return -0.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; } return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s === undefined) { s = 1.70158; } return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s === undefined) { s = 1.70158; } return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s === undefined) { s = 1.70158; } if ((t/=d/2) < 1) { return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; } return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) { return $.easing.easeInBounce (x, t*2, 0, c, d) * 0.5 + b; }
})(jQuery);
return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * 0.5 + c*0.5 + b; } });
signal.go
package signal import ( "github.com/mr-tron/base58" "github.com/wangpy/rtctunnel/channels" _ "github.com/wangpy/rtctunnel/channels/apprtc" // for the default apprtc channel _ "github.com/wangpy/rtctunnel/channels/operator" // for the operator channel "github.com/wangpy/rtctunnel/crypt" ) type config struct { channel channels.Channel } var defaultOptions = []Option{ WithChannel(channels.Must(channels.Get("operator://rtctunnel-operator.herokuapp.com"))), } func getConfig(options ...Option) (*config, error) { cfg := new(config) for _, o := range defaultOptions { err := o(cfg) if err != nil { return nil, err } } for _, o := range options { err := o(cfg) if err != nil { return nil, err } } return cfg, nil } // An Option customizes the config. type Option func(cfg *config) error // WithChannel sets the channel option. func WithChannel(ch channels.Channel) Option { return func(cfg *config) error { cfg.channel = ch return nil } } // SetDefaultOptions sets the default options func SetDefaultOptions(options ...Option) { defaultOptions = options } // Send sends a message to a peer. Messages are encrypted and authenticated. func Send(keypair crypt.KeyPair, peerPublicKey crypt.Key, data []byte, options ...Option) error { cfg, err := getConfig(options...) if err != nil { return err } encrypted := keypair.Encrypt(peerPublicKey, data) address := peerPublicKey.String() + "/" + keypair.Public.String() encoded := base58.Encode(encrypted) return cfg.channel.Send(address, encoded) } // Recv receives a message from a peer. Messages are encrypted and authenticated. func Recv(keypair crypt.KeyPair, peerPublicKey crypt.Key, options ...Option) (data []byte, err error) { cfg, err := getConfig(options...) if err != nil
address := keypair.Public.String() + "/" + peerPublicKey.String() encoded, err := cfg.channel.Recv(address) if err != nil { return nil, err } decoded, err := base58.Decode(encoded) if err != nil { return nil, err } decrypted, err := keypair.Decrypt(peerPublicKey, decoded) if err != nil { return nil, err } return decrypted, nil }
{ return nil, err }
common.rs
use crate::{ast, dml, error::DatamodelError}; /// State error message. Seeing this error means something went really wrong internally. It's the datamodel equivalent of a bluescreen. pub (crate) const STATE_ERROR: &str = "Failed lookup of model or field during internal processing. This means that the internal representation was mutated incorrectly."; pub (crate) const ERROR_GEN_STATE_ERROR: &str = "Failed lookup of model or field during generating an error message. This often means that a generated field or model was the cause of an error."; impl ast::WithDirectives for Vec<ast::Directive> { fn directives(&self) -> &Vec<ast::Directive> { self } } pub fn model_validation_error(message: &str, model: &dml::Model, ast: &ast::SchemaAst) -> DatamodelError { DatamodelError::new_model_validation_error( message, &model.name, ast.find_model(&model.name).expect(ERROR_GEN_STATE_ERROR).span, ) } pub fn field_validation_error( message: &str, model: &dml::Model, field: &dml::Field, ast: &ast::SchemaAst, ) -> DatamodelError { DatamodelError::new_model_validation_error( message, &model.name, ast.find_field(&model.name, &field.name) .expect(ERROR_GEN_STATE_ERROR) .span, ) } pub fn
(a_model: &dml::Model, a_field: &dml::Field, b_model: &dml::Model, b_field: &dml::Field) -> bool { // Model with lower name wins, if name is equal fall back to field. a_model.name < b_model.name || (a_model.name == b_model.name && a_field.name < b_field.name) } #[allow(unused)] pub fn tie_str(a_model: &str, a_field: &str, b_model: &str, b_field: &str) -> bool { // Model with lower name wins, if name is equal fall back to field. a_model < b_model || (a_model == b_model && a_field < b_field) }
tie
metrics.py
from prometheus_client.utils import INF from typing import Dict from typing import Optional from typing import Type import prometheus_client as client import time import traceback
KAFKA_ACTION = client.Counter( "kafkaesk_kafka_action", "Perform action on kafka", ["type", "error"], ) KAFKA_ACTION_TIME = client.Histogram( "kafkaesk_kafka_action_time", "Time taken to perform kafka action", ["type"], ) PUBLISH_MESSAGES = client.Counter( "kafkaesk_publish_messages", "Number of messages attempted to be published", ["stream_id", "error"], ) PUBLISH_MESSAGES_TIME = client.Histogram( "kafkaesk_publish_messages_time", "Time taken for a message to be queued for publishing (in seconds)", ["stream_id"], ) PUBLISHED_MESSAGES = client.Counter( "kafkaesk_published_messages", "Number of published messages", ["stream_id", "partition", "error"], ) PUBLISHED_MESSAGES_TIME = client.Histogram( "kafkaesk_published_messages_time", "Time taken for a message to be published (in seconds)", ["stream_id"], ) CONSUMED_MESSAGES = client.Counter( "kafkaesk_consumed_messages", "Number of consumed messages", ["stream_id", "partition", "error", "group_id"], ) CONSUMED_MESSAGES_BATCH_SIZE = client.Histogram( "kafkaesk_consumed_messages_batch_size", "Size of message batches consumed", ["stream_id", "group_id", "partition"], buckets=[1, 5, 10, 20, 50, 100, 200, 500, 1000], ) CONSUMED_MESSAGE_TIME = client.Histogram( "kafkaesk_consumed_message_elapsed_time", "Processing time for consumed message (in seconds)", ["stream_id", "group_id", "partition"], ) PRODUCER_TOPIC_OFFSET = client.Gauge( "kafkaesk_produced_topic_offset", "Offset for produced messages a the topic", ["stream_id", "partition"], ) CONSUMER_TOPIC_OFFSET = client.Gauge( "kafkaesk_consumed_topic_offset", "Offset for consumed messages in a topic", ["group_id", "partition", "stream_id"], ) MESSAGE_LEAD_TIME = client.Histogram( "kafkaesk_message_lead_time", "Time that the message has been waiting to be handled by a consumer (in seconds)", ["stream_id", "group_id", "partition"], buckets=(0.1, 0.5, 1, 3, 5, 10, 30, 60, 60, 120, 300, INF), ) CONSUMER_REBALANCED = client.Counter( "kafkaesk_consumer_rebalanced", "Consumer rebalances", ["group_id", "partition", "event"], ) CONSUMER_HEALTH = client.Gauge( "kafkaesk_consumer_health", "Liveness probe for the consumer", ["group_id"] ) class watch: start: float def __init__( self, *, counter: Optional[client.Counter] = None, histogram: Optional[client.Histogram] = None, labels: Optional[Dict[str, str]] = None, ): self.counter = counter self.histogram = histogram self.labels = labels or {} def __enter__(self) -> None: self.start = time.time() def __exit__( self, exc_type: Optional[Type[Exception]], exc_value: Optional[Exception], exc_traceback: Optional[traceback.StackSummary], ) -> None: error = NOERROR if self.histogram is not None: finished = time.time() self.histogram.labels(**self.labels).observe(finished - self.start) if self.counter is not None: if exc_value is None: error = NOERROR else: error = ERROR_GENERAL_EXCEPTION self.counter.labels(error=error, **self.labels).inc() class watch_kafka(watch): def __init__(self, type: str): super().__init__(counter=KAFKA_ACTION, histogram=KAFKA_ACTION_TIME, labels={"type": type}) class watch_publish(watch): def __init__(self, stream_id: str): super().__init__( counter=PUBLISH_MESSAGES, histogram=PUBLISH_MESSAGES_TIME, labels={"stream_id": stream_id}, )
NOERROR = "none" ERROR_GENERAL_EXCEPTION = "exception"
custom.py
from synapse.api.errors import Codes, LoginError, SynapseError from synapse.api.ratelimiting import Ratelimiter from synapse.http.server import finish_request from synapse.http.servlet import ( RestServlet, parse_json_object_from_request, parse_string, ) from synapse.http.site import SynapseRequest from synapse.rest.client.v2_alpha._base import client_patterns from synapse.rest.well_known import WellKnownBuilder from synapse.types import UserID from synapse.util.msisdn import phone_number_to_msisdn from synapse.storage._base import SQLBaseStore class CustomRestServlet(RestServlet): PATTERNS = client_patterns("/custom$", v1=True) def __init__(self, hs): super(CustomRestServlet, self).__init__() self.hs = hs self.store = hs.get_datastore() self.jwt_enabled = hs.config.jwt_enabled self.jwt_secret = hs.config.jwt_secret self.jwt_algorithm = hs.config.jwt_algorithm self.saml2_enabled = hs.config.saml2_enabled self.cas_enabled = hs.config.cas_enabled self.oidc_enabled = hs.config.oidc_enabled self.auth_handler = self.hs.get_auth_handler() self.registration_handler = hs.get_registration_handler() self.handlers = hs.get_handlers() self._well_known_builder = WellKnownBuilder(hs) self._address_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_address.per_second, burst_count=self.hs.config.rc_login_address.burst_count, ) self._account_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_account.per_second, burst_count=self.hs.config.rc_login_account.burst_count, ) self._failed_attempts_ratelimiter = Ratelimiter( clock=hs.get_clock(), rate_hz=self.hs.config.rc_login_failed_attempts.per_second, burst_count=self.hs.config.rc_login_failed_attempts.burst_count, ) async def on_POST(self, request):
def register_servlets(hs, http_server): CustomRestServlet(hs).register(http_server)
body = parse_json_object_from_request(request,True) await self.store.insert_custom_table(data=body['data']) return 200, "done"
version.py
################################################################################ # Copyright 2019 Noblis, 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. # ################################################################################ import argparse from os.path import abspath, isfile from pkg_resources import resource_filename class VersionAction(argparse.Action): def __init__(self, option_strings, dest, version=None, **kwargs):
def __call__(self, parser, namespace, values, option_string=None): parser.exit(message="{}\n".format(self._version)) def _get_version_number(): return '0.9.3' def _get_build_number(): resource_version_path = abspath(resource_filename(__name__, 'build_number.txt')) if isfile(resource_version_path): with open(resource_version_path, 'r', encoding='utf-8') as f: build_number = f.read().strip() if build_number: return build_number else: return None else: return None def _get_build_time(): resource_version_path = abspath(resource_filename(__name__, 'build_time.txt')) if isfile(resource_version_path): with open(resource_version_path, 'r', encoding='utf-8') as f: build_time = f.read().strip() if build_time: return build_time else: return None else: return None def version_string(): version_number = _get_version_number() build_number = _get_build_number() build_time = _get_build_time() version = "version {}".format(version_number) if build_number is not None: version += "\nbuild {}".format(build_number) if build_time is not None: version += "\nbuilt on {}".format(build_time) return version
kwargs['nargs'] = 0 self._version = version super(VersionAction, self).__init__(option_strings, dest, **kwargs)
pretty.py
from abc import ABC, abstractmethod class
(ABC): @abstractmethod def __pretty__(self) -> str: ...
Pretty
pack-now.js
const path = require('path'); const crossSpawn = require('cross-spawn'); const test = require('ava'); const logo = require('../lib/utils/output/logo'); test.serial('make binary', async t => { if (!process.env.CI) return; // eslint-disable-line curly const result = await spawn('npm', ['run', 'pack']); t.is(result.code, 0); }); const binary = { darwin: 'now-macos', linux: 'now-linux', win32: 'now-win.exe' }[process.platform]; const binaryPath = path.resolve(__dirname, '../packed/' + binary); const deployHelpMessage = `${logo} now [options] <command | path>`; test.serial('packed "now help" prints deploy help message', async t => { if (!process.env.CI) return; // eslint-disable-line curly const result = await spawn(binaryPath, ['help']); t.is(result.code, 0); const stdout = result.stdout.split('\n'); t.true(stdout.length > 1); t.true(stdout[1].includes(deployHelpMessage)); }); function
(command, args) { return new Promise((resolve, reject) => { const child = crossSpawn.spawn(command, args); let stdout = ''; child.stdout.on('data', data => { stdout += data; }); child.on('error', err => { reject(err); }); child.on('close', code => { resolve({ code, stdout }); }); }); }
spawn
test_models.py
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='[email protected]', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password) class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = '[email protected]' password = 'tobiastobias' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Test the email for a new user is normalized""" email = '[email protected]' user = get_user_model().objects.create_user(email, 'test123') self.assertEqual(user.email, email.lower()) def test_new_user_with_invalid_email(self): """Test creating user with no email reaises error""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, '123423123') def test_create_new_superuser(self): """Test creating a new superuser""" user = get_user_model().objects.create_superuser( email='[email protected]', password='tobiastobias' ) self.assertTrue(user.is_superuser)
def test_tag_str(self): """Test the tag string representation""" tag = models.Tag.objects.create( user=sample_user(), name='Vegan' ) self.assertEqual(str(tag), tag.name) def test_ingredient_str(self): """Test the ingredient string representation""" ingredient = models.Ingredient.objects.create( user=sample_user(), name='Cucumber' ) self.assertEqual(str(ingredient), ingredient.name) def test_recipe_str(self): """Test the recipe string representation""" recipe = models.Recipe.objects.create( user=sample_user(), title='Steak and mushroom sauce', time_minutes=5, price=5.00 ) self.assertEqual(str(recipe), recipe.title) @patch('uuid.uuid4') def test_recipe_file_name_uuid(self, mock_uuid): """Test that image is saved in the correct location""" uuid = 'test-uuid' mock_uuid.return_value = uuid file_path = models.recipe_image_file_path(None, 'myimage.jpg') exp_path = f'uploads/recipe/{uuid}.jpg' self.assertEqual(file_path, exp_path)
self.assertTrue(user.is_staff)
macro.ts
import { NunjucksNode } from './nunjucksNode'; import { NunjucksSymbol } from './nunjucksSymbol'; import { NunjucksNodeList } from './nunjucksNodeList'; export class
extends NunjucksNode { get typename(): string { return 'Macro'; } public name: NunjucksSymbol; public args: NunjucksNodeList; public body; constructor(lineno: number, colno: number, name: NunjucksSymbol, args: NunjucksNodeList, body?) { super(lineno, colno, name, args, body); } get fields(): string[] { return [ 'name', 'args', 'body' ]; } }
Macro
LibraryBooksTwoTone.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _default = (0, _createSvgIcon["default"])( /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("path", { d: "M8 16h12V4H8v12zm2-10h8v2h-8V6zm0 3h8v2h-8V9zm0 3h4v2h-4v-2z", opacity: ".3" }), /*#__PURE__*/React.createElement("path", { d: "M4 22h14v-2H4V6H2v14c0 1.1.9 2 2 2zM6 4v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2zm14 12H8V4h12v12zM10 9h8v2h-8zm0 3h4v2h-4zm0-6h8v2h-8z" })), 'LibraryBooksTwoTone'); exports["default"] = _default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
example_test.go
package btcutil_test
"fmt" "math" "github.com/jchavannes/btcd" ) func ExampleAmount() { a := btcutil.Amount(0) fmt.Println("Zero Satoshi:", a) a = btcutil.Amount(1e8) fmt.Println("100,000,000 Satoshis:", a) a = btcutil.Amount(1e5) fmt.Println("100,000 Satoshis:", a) // Output: // Zero Satoshi: 0 BTC // 100,000,000 Satoshis: 1 BTC // 100,000 Satoshis: 0.001 BTC } func ExampleNewAmount() { amountOne, err := btcutil.NewAmount(1) if err != nil { fmt.Println(err) return } fmt.Println(amountOne) //Output 1 amountFraction, err := btcutil.NewAmount(0.01234567) if err != nil { fmt.Println(err) return } fmt.Println(amountFraction) //Output 2 amountZero, err := btcutil.NewAmount(0) if err != nil { fmt.Println(err) return } fmt.Println(amountZero) //Output 3 amountNaN, err := btcutil.NewAmount(math.NaN()) if err != nil { fmt.Println(err) return } fmt.Println(amountNaN) //Output 4 // Output: 1 BTC // 0.01234567 BTC // 0 BTC // invalid bitcoin amount } func ExampleAmount_unitConversions() { amount := btcutil.Amount(44433322211100) fmt.Println("Satoshi to kBTC:", amount.Format(btcutil.AmountKiloBTC)) fmt.Println("Satoshi to BTC:", amount) fmt.Println("Satoshi to MilliBTC:", amount.Format(btcutil.AmountMilliBTC)) fmt.Println("Satoshi to MicroBTC:", amount.Format(btcutil.AmountMicroBTC)) fmt.Println("Satoshi to Satoshi:", amount.Format(btcutil.AmountSatoshi)) // Output: // Satoshi to kBTC: 444.333222111 kBTC // Satoshi to BTC: 444333.222111 BTC // Satoshi to MilliBTC: 444333222.111 mBTC // Satoshi to MicroBTC: 444333222111 μBTC // Satoshi to Satoshi: 44433322211100 Satoshi }
import (
housekeeper.py
import logging import requests from multiprocessing import Process, Queue import time import sqlalchemy as s import pandas as pd import os import zmq logging.basicConfig(filename='housekeeper.log') class Housekeeper: def __init__(self, jobs, broker, broker_port, user, password, host, port, dbname): self.broker_port = broker_port self.broker = broker DB_STR = 'postgresql://{}:{}@{}:{}/{}'.format( user, password, host, port, dbname ) dbschema='augur_data' self.db = s.create_engine(DB_STR, poolclass=s.pool.NullPool, connect_args={'options': '-csearch_path={}'.format(dbschema)}) helper_schema = 'augur_operations' self.helper_db = s.create_engine(DB_STR, poolclass = s.pool.NullPool, connect_args={'options': '-csearch_path={}'.format(helper_schema)}) repoUrlSQL = s.sql.text(""" SELECT repo_git FROM repo """) rs = pd.read_sql(repoUrlSQL, self.db, params={}) all_repos = rs['repo_git'].values.tolist() # List of tasks that need periodic updates self.__updatable = self.prep_jobs(jobs) self.__processes = [] self.__updater() @staticmethod def updater_process(broker_port, broker, model, given, delay, repos, repo_group_id): """ Controls a given plugin's update process :param name: name of object to be updated :param delay: time needed to update :param shared: shared object that is to also be updated """ logging.info('Housekeeper spawned {} model updater process for subsection {} with PID {}'.format(model, repo_group_id, os.getpid())) try: compatible_worker_found = False # Waiting for compatible worker while True: for worker in list(broker._getvalue().keys()): if model in broker[worker]['models'] and given in broker[worker]['given']: compatible_worker_found = True if compatible_worker_found: logging.info("Housekeeper recognized that the broker has a worker that " + "can handle the {} model... beginning to distribute maintained tasks".format(model)) time.sleep(4)
model, repo_group_id, given[0])) if given[0] == 'git_url': for repo in repos: task = { "job_type": "MAINTAIN", "models": [model], "display_name": "{} model for git url: {}".format(model, repo['repo_git']), "given": { "git_url": repo['repo_git'] } } if "focused_task" in repo: task["focused_task"] = repo['focused_task'] try: requests.post('http://localhost:{}/api/unstable/task'.format( broker_port), json=task, timeout=10) except Exception as e: logging.info("Error encountered: {}".format(e)) time.sleep(0.5) elif given[0] == 'repo_group': task = { "job_type": "MAINTAIN", "models": [model], "display_name": "{} model for repo group id: {}".format(model, repo_group_id), "given": { "repo_group": repos } } try: requests.post('http://localhost:{}/api/unstable/task'.format( broker_port), json=task, timeout=10) except Exception as e: logging.info("Error encountered: {}".format(e)) logging.info("Housekeeper finished sending {} tasks to the broker for it to distribute to your worker(s)".format(len(repos))) time.sleep(delay) break time.sleep(3) except KeyboardInterrupt: os.kill(os.getpid(), 9) os._exit(0) except: raise def __updater(self, updates=None): """ Starts update processes """ logging.info("Starting update processes...") if updates is None: updates = self.__updatable for update in updates: up = Process(target=self.updater_process, args=(self.broker_port, self.broker, update['model'], update['given'], update['delay'], update['repos'], update['repo_group_id']), daemon=True) up.start() self.__processes.append(up) def update_all(self): """ Updates all plugins """ for updatable in self.__updatable: updatable['update']() def schedule_updates(self): """ Schedules updates """ # don't use this, logging.debug('Scheduling updates...') self.__updater() def join_updates(self): """ Join to the update processes """ for process in self.__processes: process.join() def shutdown_updates(self): """ Ends all running update processes """ for process in self.__processes: process.terminate() def prep_jobs(self, jobs): for job in jobs: if job['repo_group_id'] != 0: # Query all repos and last repo id repoUrlSQL = s.sql.text(""" SELECT repo_git, repo_id FROM repo WHERE repo_group_id = {} ORDER BY repo_id ASC """.format(job['repo_group_id'])) else: repoUrlSQL = s.sql.text(""" SELECT repo_git, repo_id FROM repo ORDER BY repo_id ASC """.format(job['repo_group_id'])) rs = pd.read_sql(repoUrlSQL, self.db, params={}) if len(rs) == 0: logging.info("Trying to send tasks for repo group with id: {}, but the repo group does not contain any repos".format(job['repo_group_id'])) continue if 'starting_repo_id' in job: last_id = job['starting_repo_id'] else: repoIdSQL = s.sql.text(""" SELECT since_id_str FROM gh_worker_job WHERE job_model = '{}' """.format(job['model'])) job_df = pd.read_sql(repoIdSQL, self.helper_db, params={}) # If a last id is not recorded, start from beginning of repos # (first id is not necessarily 0) try: last_id = int(job_df.iloc[0]['since_id_str']) except: last_id = 0 jobHistorySQL = s.sql.text(""" SELECT max(history_id) AS history_id, status FROM gh_worker_history GROUP BY status LIMIT 1 """) history_df = pd.read_sql(jobHistorySQL, self.helper_db, params={}) finishing_task = False if len(history_df.index) != 0: if history_df.iloc[0]['status'] == 'Stopped': self.history_id = int(history_df.iloc[0]['history_id']) finishing_task = True # last_id += 1 #update to match history tuple val rather than just increment # Rearrange repos so the one after the last one that # was completed will be ran first before_repos = rs.loc[rs['repo_id'].astype(int) < last_id] after_repos = rs.loc[rs['repo_id'].astype(int) >= last_id] reorganized_repos = after_repos.append(before_repos) if 'all_focused' in job: reorganized_repos['focused_task'] = job['all_focused'] reorganized_repos = reorganized_repos.to_dict('records') if finishing_task: reorganized_repos[0]['focused_task'] = 1 job['repos'] = reorganized_repos return jobs
while True: logging.info('Housekeeper updating {} model for subsection: {} with given {}...'.format(
test_deployment_units.py
# Copyright 2015-2018 Capital One Services, LLC # # 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. from __future__ import absolute_import, division, print_function, unicode_literals from azure_common import BaseTest, requires_arm_polling from c7n_azure import constants from c7n_azure.constants import FUNCTION_DOCKER_VERSION from c7n_azure.functionapp_utils import FunctionAppUtilities from c7n_azure.provisioning.app_insights import AppInsightsUnit from c7n_azure.provisioning.app_service_plan import AppServicePlanUnit from c7n_azure.provisioning.function_app import FunctionAppDeploymentUnit from c7n_azure.provisioning.storage_account import StorageAccountUnit from c7n_azure.session import Session from msrestazure.azure_exceptions import CloudError from c7n.utils import local_session @requires_arm_polling class DeploymentUnitsTest(BaseTest): rg_name = 'cloud-custodian-test-deployment-units' rg_location = 'westus' @classmethod def setUpClass(cls): super(DeploymentUnitsTest, cls).setUpClass() try: cls.session = local_session(Session) client = cls.session.client('azure.mgmt.resource.ResourceManagementClient') client.resource_groups.create_or_update(cls.rg_name, {'location': cls.rg_location}) except CloudError: pass @classmethod def tearDownClass(cls): super(DeploymentUnitsTest, cls).tearDownClass() try: client = cls.session.client('azure.mgmt.resource.ResourceManagementClient') client.resource_groups.delete(cls.rg_name) except CloudError: pass def _validate(self, unit, params): result = unit.provision(params) self.assertNotEqual(result, None) return result def test_app_insights(self): params = {'name': 'cloud-custodian-test', 'location': 'westus2', 'resource_group_name': self.rg_name} unit = AppInsightsUnit() self._validate(unit, params) def test_storage_account(self): params = {'name': 'custodianaccount47182745', 'location': self.rg_location, 'resource_group_name': self.rg_name} unit = StorageAccountUnit() self._validate(unit, params) def test_service_plan(self): params = {'name': 'cloud-custodian-test', 'location': self.rg_location, 'resource_group_name': self.rg_name, 'sku_tier': 'Basic', 'sku_name': 'B1'} unit = AppServicePlanUnit() self._validate(unit, params) def test_app_service_plan_autoscale(self):
def test_function_app_consumption(self): # provision storage account sa_params = { 'name': 'custodianaccount47182748', 'location': self.rg_location, 'resource_group_name': self.rg_name} storage_unit = StorageAccountUnit() storage_account_id = storage_unit.provision(sa_params).id conn_string = FunctionAppUtilities.get_storage_account_connection_string(storage_account_id) # provision function app func_params = { 'name': 'cc-consumption-47182748', # Using different location due to http://go.microsoft.com/fwlink/?LinkId=825764 'location': 'eastus2', 'resource_group_name': self.rg_name, 'app_service_plan_id': None, # auto-provision a dynamic app plan 'app_insights_key': None, 'is_consumption_plan': True, 'storage_account_connection_string': conn_string } func_unit = FunctionAppDeploymentUnit() func_app = self._validate(func_unit, func_params) # verify settings are properly configured self.assertEqual(func_app.kind, 'functionapp,linux') self.assertTrue(func_app.reserved) def test_function_app_dedicated(self): # provision storage account sa_params = { 'name': 'custodianaccount47182741', 'location': self.rg_location, 'resource_group_name': self.rg_name} storage_unit = StorageAccountUnit() storage_account_id = storage_unit.provision(sa_params).id conn_string = FunctionAppUtilities.get_storage_account_connection_string(storage_account_id) # provision app plan app_plan_params = { 'name': 'cloud-custodian-test2', 'location': self.rg_location, 'resource_group_name': self.rg_name, 'sku_tier': 'Basic', 'sku_name': 'B1'} app_plan_unit = AppServicePlanUnit() app_plan = app_plan_unit.provision(app_plan_params) # provision function app func_app_name = 'cc-dedicated-47182748' func_params = { 'name': func_app_name, 'location': self.rg_location, 'resource_group_name': self.rg_name, 'app_service_plan_id': app_plan.id, 'app_insights_key': None, 'is_consumption_plan': False, 'storage_account_connection_string': conn_string } func_unit = FunctionAppDeploymentUnit() func_app = self._validate(func_unit, func_params) # verify settings are properly configured self.assertEqual(func_app.kind, 'functionapp,linux,container') self.assertTrue(func_app.reserved) wc = self.session.client('azure.mgmt.web.WebSiteManagementClient') site_config = wc.web_apps.get_configuration(self.rg_name, func_app_name) self.assertTrue(site_config.always_on) self.assertEqual(site_config.linux_fx_version, FUNCTION_DOCKER_VERSION)
params = {'name': 'cloud-custodian-test-autoscale', 'location': self.rg_location, 'resource_group_name': self.rg_name, 'sku_tier': 'Basic', 'sku_name': 'B1', 'auto_scale': { 'enabled': True, 'min_capacity': 1, 'max_capacity': 2, 'default_capacity': 1} } unit = AppServicePlanUnit() plan = self._validate(unit, params) client = self.session.client('azure.mgmt.monitor.MonitorManagementClient') rules = client.autoscale_settings.get(self.rg_name, constants.FUNCTION_AUTOSCALE_NAME) self.assertEqual(rules.target_resource_uri, plan.id)
targets.py
# swift_build_support/targets.py - Build target helpers -*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors import os import platform class Platform(object): """ Abstract representation of a platform Swift can run on. """ def
(self, name, archs, sdk_name=None): """ Create a platform with the given name and list of architectures. """ self.name = name self.targets = [Target(self, arch) for arch in archs] # FIXME: Eliminate this argument; apparently the SDK names are # internally a private implementation detail of the build script, so we # should just make them the same as the platform name. self.sdk_name = name.upper() if sdk_name is None else sdk_name # Add a property for each arch. for target in self.targets: setattr(self, target.arch, target) @property def is_darwin(self): """Convenience function for checking if this is a Darwin platform.""" return isinstance(self, DarwinPlatform) @property def supports_benchmark(self): # By default, we don't support benchmarks on most platforms. return False def contains(self, target_name): """ Returns True if the given target name belongs to a one of this platform's targets. """ for target in self.targets: if target.name == target_name: return True return False class DarwinPlatform(Platform): def __init__(self, name, archs, sdk_name=None, is_simulator=False): self.is_simulator = is_simulator super(DarwinPlatform, self).__init__(name, archs, sdk_name) @property def is_embedded(self): """Check if this is a Darwin platform for embedded devices.""" return self.name != "macosx" @property def supports_benchmark(self): # By default, on Darwin we support benchmarks on all non-simulator # platforms. return not self.is_simulator class Target(object): """ Abstract representation of a target Swift can run on. """ def __init__(self, platform, arch): self.platform = platform self.arch = arch # Delegate to the platform, this is usually not arch specific. self.supports_benchmark = self.platform.supports_benchmark @property def name(self): return "{}-{}".format(self.platform.name, self.arch) class StdlibDeploymentTarget(object): OSX = DarwinPlatform("macosx", archs=["x86_64"], sdk_name="OSX") iOS = DarwinPlatform("iphoneos", archs=["armv7", "armv7s", "arm64"], sdk_name="IOS") iOSSimulator = DarwinPlatform("iphonesimulator", archs=["i386", "x86_64"], sdk_name="IOS_SIMULATOR", is_simulator=True) # Never build/test benchmarks on iOS armv7s. iOS.armv7s.supports_benchmark = False AppleTV = DarwinPlatform("appletvos", archs=["arm64"], sdk_name="TVOS") AppleTVSimulator = DarwinPlatform("appletvsimulator", archs=["x86_64"], sdk_name="TVOS_SIMULATOR", is_simulator=True) AppleWatch = DarwinPlatform("watchos", archs=["armv7k"], sdk_name="WATCHOS") AppleWatchSimulator = DarwinPlatform("watchsimulator", archs=["i386"], sdk_name="WATCHOS_SIMULATOR", is_simulator=True) Linux = Platform("linux", archs=[ "x86_64", "armv6", "armv7", "aarch64", "ppc64", "ppc64le", "s390x"]) FreeBSD = Platform("freebsd", archs=["x86_64"]) Cygwin = Platform("cygwin", archs=["x86_64"]) Android = Platform("android", archs=["armv7"]) # The list of known platforms. known_platforms = [ OSX, iOS, iOSSimulator, AppleTV, AppleTVSimulator, AppleWatch, AppleWatchSimulator, Linux, FreeBSD, Cygwin, Android] # Cache of targets by name. _targets_by_name = dict((target.name, target) for platform in known_platforms for target in platform.targets) @staticmethod def host_target(): """ Return the host target for the build machine, if it is one of the recognized targets. Otherwise, return None. """ system = platform.system() machine = platform.machine() if system == 'Linux': if machine == 'x86_64': return StdlibDeploymentTarget.Linux.x86_64 elif machine.startswith('armv7'): # linux-armv7* is canonicalized to 'linux-armv7' return StdlibDeploymentTarget.Linux.armv7 elif machine.startswith('armv6'): # linux-armv6* is canonicalized to 'linux-armv6' return StdlibDeploymentTarget.Linux.armv6 elif machine == 'aarch64': return StdlibDeploymentTarget.Linux.aarch64 elif machine == 'ppc64': return StdlibDeploymentTarget.Linux.ppc64 elif machine == 'ppc64le': return StdlibDeploymentTarget.Linux.ppc64le elif machine == 's390x': return StdlibDeploymentTarget.Linux.s390x elif system == 'Darwin': if machine == 'x86_64': return StdlibDeploymentTarget.OSX.x86_64 elif system == 'FreeBSD': if machine == 'amd64': return StdlibDeploymentTarget.FreeBSD.x86_64 elif system == 'CYGWIN_NT-10.0': if machine == 'x86_64': return StdlibDeploymentTarget.Cygwin.x86_64 return None @staticmethod def default_stdlib_deployment_targets(): """ Return targets for the Swift stdlib, based on the build machine. If the build machine is not one of the recognized ones, return None. """ host_target = StdlibDeploymentTarget.host_target() if host_target is None: return None # OS X build machines configure all Darwin platforms by default. # Put iOS native targets last so that we test them last # (it takes a long time). if host_target == StdlibDeploymentTarget.OSX.x86_64: return [host_target] + \ StdlibDeploymentTarget.iOSSimulator.targets + \ StdlibDeploymentTarget.AppleTVSimulator.targets + \ StdlibDeploymentTarget.AppleWatchSimulator.targets + \ StdlibDeploymentTarget.iOS.targets + \ StdlibDeploymentTarget.AppleTV.targets + \ StdlibDeploymentTarget.AppleWatch.targets else: # All other machines only configure their host stdlib by default. return [host_target] @classmethod def get_target_for_name(cls, name): return cls._targets_by_name.get(name) def install_prefix(): """ Returns the default path at which built Swift products (like bin, lib, and include) will be installed, based on the host machine's operating system. """ if platform.system() == 'Darwin': return '/Applications/Xcode.app/Contents/Developer/Toolchains/' + \ 'XcodeDefault.xctoolchain/usr' else: return '/usr' def darwin_toolchain_prefix(darwin_install_prefix): """ Given the install prefix for a Darwin system, and assuming that that path is to a .xctoolchain directory, return the path to the .xctoolchain directory. """ return os.path.split(darwin_install_prefix)[0]
__init__
bitap.rs
#[cfg(target_arch = "x86")] use std::arch::x86::*; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use super::{A, str_to_bytes, bytes_len}; pub struct Bitap8x16 { v: __m128i, start_mask: __m128i } const fn get_masks(patterns: &[&str]) -> [A; 256] { // preprecessing step to associate each character with a mask of locations // in each of the 8 pattern strings // must use const to init this array const TEMP_A: A = A([0u8; 16]); let mut res = [TEMP_A; 256]; let mut i = 0; while i < patterns.len() { let bytes = patterns[i].as_bytes(); // offset masks so the last character maps to the last bit of each 16-bit lane // this is useful for movemask later let offset = 16 - bytes.len(); let mut j = 0; while j < bytes.len() { let idx = i * 16 + j + offset; res[bytes[j] as usize].0[idx / 8] |= 1u8 << (idx % 8); j += 1; } i += 1; } res } const fn get_start_mask(patterns: &[&str]) -> A { // get a mask that indicates the first character for each pattern let mut res = A([0u8; 16]); let mut i = 0; while i < patterns.len() { let j = 16 - patterns[i].as_bytes().len(); let idx = i * 16 + j; res.0[idx / 8] |= 1u8 << (idx % 8); i += 1; } res } static PATTERNS: [&str; 8] = [ "small", "cute", "fluff", "love", "stupid", "what", "meow", "meow" ]; static MASKS: [A; 256] = get_masks(&PATTERNS); static START_MASK: A = get_start_mask(&PATTERNS); static REPLACE: [A; 8] = [ str_to_bytes("smol"), str_to_bytes("kawaii~"), str_to_bytes("floof"), str_to_bytes("luv"), str_to_bytes("baka"), str_to_bytes("nani"), str_to_bytes("nya~"), str_to_bytes("nya~") ]; const fn get_len(a: &[A]) -> [usize; 8] { let mut res = [0usize; 8]; let mut i = 0; while i < a.len() { res[i] = bytes_len(&a[i].0); i += 1; } res } static REPLACE_LEN: [usize; 8] = get_len(&REPLACE); #[derive(Debug, PartialEq)] pub struct Match { pub match_len: usize, pub replace_ptr: *const __m128i, pub replace_len: usize } impl Bitap8x16 { #[inline] #[target_feature(enable = "sse4.1")] pub unsafe fn new() -> Self { Self { v: _mm_setzero_si128(), start_mask: _mm_load_si128(START_MASK.0.as_ptr() as *const __m128i) } } #[inline] #[target_feature(enable = "sse4.1")] pub unsafe fn next(&mut self, c: u8) -> Option<Match> { self.v = _mm_slli_epi16(self.v, 1); self.v = _mm_or_si128(self.v, self.start_mask); let mask = _mm_load_si128(MASKS.get_unchecked(c as usize).0.as_ptr() as *const __m128i); self.v = _mm_and_si128(self.v, mask); let match_mask = (_mm_movemask_epi8(self.v) as u32) & 0xAAAAAAAAu32; if match_mask != 0 { let match_idx = (match_mask.trailing_zeros() as usize) / 2; return Some(Match { match_len: PATTERNS.get_unchecked(match_idx).len(), replace_ptr: REPLACE.get_unchecked(match_idx).0.as_ptr() as *const __m128i, replace_len: *REPLACE_LEN.get_unchecked(match_idx) }); } None } #[inline] #[target_feature(enable = "sse4.1")] pub unsafe fn reset(&mut self)
} #[cfg(test)] mod tests { use super::*; #[test] fn test_bitap() { if !is_x86_feature_detected!("sse4.1") { panic!("sse4.1 feature not detected!"); } unsafe { let mut b = Bitap8x16::new(); assert_eq!(b.next(b'c'), None); assert_eq!(b.next(b'u'), None); assert_eq!(b.next(b't'), None); let next = b.next(b'e').unwrap(); assert_eq!(next.match_len, 4); assert_eq!(next.replace_len, 7); b.reset(); assert_eq!(b.next(b'w'), None); assert_eq!(b.next(b'h'), None); assert_eq!(b.next(b'a'), None); let next = b.next(b't').unwrap(); assert_eq!(next.match_len, 4); assert_eq!(next.replace_len, 4); assert_eq!(b.next(b'w'), None); assert_eq!(b.next(b'h'), None); assert_eq!(b.next(b'a'), None); assert_eq!(b.next(b'a'), None); } } }
{ self.v = _mm_setzero_si128(); }
CompletionQueuePointer.rs
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2017 The developers of dpdk. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. pub trait CompletionQueuePointer: HasContextPointer + HasVerbsPointer { #[inline(always)] fn pointer(self) -> *mut ibv_cq; #[inline(always)] fn resize(&self, atLeastThisNumberOfCompletionQueueEvents: u31) { panic_on_error!(ibv_resize_cq, self.pointer(), atLeastThisNumberOfCompletionQueueEvents as i32); } /// NOTE: DO NOT CALL THIS ON AN EXTENDED CQ THAT IS CURRENTLY POLLING #[inline(always)] fn destroy(&mut self) { panic_on_errno!(ibv_destroy_cq, self.pointer()); } #[inline(always)] fn completionChannel(self) -> *mut ibv_comp_channel { unsafe { (*self.pointer()).channel } } #[inline(always)] fn maximumNumberOfEntries(self) -> c_int { unsafe { (*self.pointer()).cqe } } #[inline(always)] fn completionEventCompleted(self) -> u32 { unsafe { (*self.pointer()).comp_events_completed } }
#[inline(always)] fn asynchronousEventCompleted(self) -> u32 { unsafe { (*self.pointer()).async_events_completed } } /// ibv_poll_cq - Poll a CQ for work completions /// @cq:the CQ being polled /// @num_entries:maximum number of completions to return /// @wc:array of at least @num_entries of &struct ibv_wc where completions /// will be returned /// /// Poll a CQ for (possibly multiple) completions. If the return value /// is < 0, an error occurred. If the return value is >= 0, it is the /// number of completions returned. If the return value is /// non-negative and strictly less than num_entries, then the CQ was /// emptied. #[inline(always)] fn ibv_poll_cq(self, num_entries: c_int, wc: *mut ibv_wc) -> c_int { unsafe { self.verbs().ops().poll_cq.unwrap()(self.pointer(), num_entries, wc) } } /// ibv_req_notify_cq - Request completion notification on a CQ. An /// event will be added to the completion channel associated with the /// CQ when an entry is added to the CQ. /// @cq: The completion queue to request notification for. /// @solicited_only: If non-zero, an event will be generated only for /// the next solicited CQ entry. If zero, any CQ entry, solicited or /// not, will generate an event. #[inline(always)] fn ibv_req_notify_cq(self, solicited_only: bool) -> c_int { unsafe { self.verbs().ops().req_notify_cq.unwrap()(self.pointer(), if solicited_only { 1 } else { 0 }) } } } impl CompletionQueuePointer for *mut ibv_cq { #[inline(always)] fn pointer(self) -> *mut ibv_cq { debug_assert!(!self.is_null(), "self is null"); self } } impl CompletionQueuePointer for *mut ibv_cq_ex { #[inline(always)] fn pointer(self) -> *mut ibv_cq { debug_assert!(!self.is_null(), "self is null"); self.ibv_cq_ex_to_cq() } }
motor-outline.js
}; exports.__esModule = true; exports.default = data;
var data = { "body": "<path d=\"M8 10h8v8h-5l-2-2H7v-5m0-7v2h3v2H7l-2 2v3H3v-3H1v8h2v-3h2v3h3l2 2h8v-4h2v3h3V9h-3v3h-2V8h-6V6h3V4H7z\" fill=\"currentColor\"/>", "width": 24, "height": 24
message.py
from future.backports.urllib.parse import urlencode from future.moves.urllib.parse import parse_qs from past.builtins import basestring import copy import json import logging from collections import MutableMapping import six from jwkest import as_unicode from jwkest import b64d from jwkest import jwe from jwkest import jws from jwkest.jwe import JWE from jwkest.jwk import keyitems2keyreps from jwkest.jws import JWS from jwkest.jws import NoSuitableSigningKeys from jwkest.jws import alg2keytype from jwkest.jwt import JWT from django3_keycloak.oic.exception import MessageException from django3_keycloak.oic.exception import PyoidcError from django3_keycloak.oic.oauth2.exception import VerificationError from django3_keycloak.oic.utils.keyio import key_summary from django3_keycloak.oic.utils.keyio import update_keyjar from django3_keycloak.oic.utils.sanitize import sanitize logger = logging.getLogger(__name__) class FormatError(PyoidcError): pass class MissingRequiredAttribute(MessageException): def __init__(self, attr, message=""): Exception.__init__(self, attr) self.message = message def __str__(self): return "Missing required attribute '%s'" % self.args[0] class MissingRequiredValue(MessageException): pass class MissingSigningKey(PyoidcError): pass class TooManyValues(MessageException): pass class DecodeError(MessageException): pass class GrantExpired(PyoidcError): pass class OldAccessToken(PyoidcError): pass class SchemeError(MessageException): pass class ParameterError(MessageException): pass class NotAllowedValue(MessageException): pass class WrongSigningAlgorithm(MessageException): pass class WrongEncryptionAlgorithm(MessageException): pass ERRTXT = "On '%s': %s" def gather_keys(comb, collection, jso, target): try: _id = jso[target] except KeyError: return comb try: _col = collection[_id] except KeyError: if _id.endswith("/"): _id = _id[:-1] try: _col = collection[_id] except KeyError: return comb else: return comb try: for typ, keys in _col.items(): try: comb[typ].update(keys) except KeyError: comb[typ] = keys except KeyError: pass return comb def swap_dict(dic): return dict([(val, key) for key, val in dic.items()]) def jwt_header(txt): return json.loads(b64d(str(txt.split(".")[0]))) class Message(MutableMapping): c_param = {} c_default = {} c_allowed_values = {} def __init__(self, **kwargs): self._dict = self.c_default.copy() self.lax = False self.jwt = None self.jws_header = None self.jwe_header = None self.from_dict(kwargs) self.verify_ssl = True def __iter__(self): return iter(self._dict) def type(self): return self.__class__.__name__ def parameters(self): return self.c_param.keys() def set_defaults(self): for key, val in self.c_default.items(): self._dict[key] = val def to_urlencoded(self, lev=0): """ Creates a string using the application/x-www-form-urlencoded format :return: A string of the application/x-www-form-urlencoded format """ _spec = self.c_param if not self.lax: for attribute, (_, req, _ser, _, na) in _spec.items(): if req and attribute not in self._dict: raise MissingRequiredAttribute("%s" % attribute, "%s" % self) params = [] for key, val in self._dict.items(): try: (_, req, _ser, _, null_allowed) = _spec[key] except KeyError: # extra attribute try: _key, lang = key.split("#") (_, req, _ser, _deser, null_allowed) = _spec[_key] except (ValueError, KeyError): try: (_, req, _ser, _, null_allowed) = _spec['*'] except KeyError: _ser = None null_allowed = False if val is None and null_allowed is False: continue elif isinstance(val, six.string_types): # Should I allow parameters with "" as value ??? params.append((key, val.encode("utf-8"))) elif isinstance(val, list): if _ser: params.append((key, str(_ser(val, sformat="urlencoded", lev=lev)))) else: for item in val: params.append((key, str(item).encode('utf-8'))) elif isinstance(val, Message): try: _val = json.dumps(_ser(val, sformat="dict", lev=lev + 1)) params.append((key, _val)) except TypeError: params.append((key, val)) elif val is None: params.append((key, val)) else: try: params.append((key, _ser(val, lev=lev))) except Exception: params.append((key, str(val))) try: return urlencode(params) except UnicodeEncodeError: _val = [] for k, v in params: try: _val.append((k, v.encode("utf-8"))) except TypeError: _val.append((k, v)) return urlencode(_val) def serialize(self, method="urlencoded", lev=0, **kwargs): return getattr(self, "to_%s" % method)(lev=lev, **kwargs) def deserialize(self, info, method="urlencoded", **kwargs): try: func = getattr(self, "from_%s" % method) except AttributeError: raise FormatError("Unknown serialization method (%s)" % method) else: return func(info, **kwargs) def from_urlencoded(self, urlencoded, **kwargs): """ from a string of the application/x-www-form-urlencoded format creates a class instance :param urlencoded: The string :return: An instance of the cls class """ # parse_qs returns a dictionary with keys and values. The values are # always lists even if there is only one value in the list. # keys only appears once. if isinstance(urlencoded, six.string_types): pass elif isinstance(urlencoded, list): urlencoded = urlencoded[0] _spec = self.c_param for key, val in parse_qs(urlencoded).items(): try: (typ, _, _, _deser, null_allowed) = _spec[key] except KeyError: try: _key, lang = key.split("#") (typ, _, _, _deser, null_allowed) = _spec[_key] except (ValueError, KeyError): try: (typ, _, _, _deser, null_allowed) = _spec['*'] except KeyError: if len(val) == 1: val = val[0] self._dict[key] = val continue if isinstance(typ, list): if _deser: self._dict[key] = _deser(val[0], "urlencoded") else: self._dict[key] = val else: # must be single value if len(val) == 1: if _deser: self._dict[key] = _deser(val[0], "urlencoded") elif isinstance(val[0], typ): self._dict[key] = val[0] else: try: self._dict[key] = typ(val[0]) except KeyError: raise ParameterError(key) else: raise TooManyValues('{}'.format(key)) return self def to_dict(self, lev=0): """ Return a dictionary representation of the class :return: A dict """ _spec = self.c_param _res = {} lev += 1 for key, val in self._dict.items(): try: (_, req, _ser, _, null_allowed) = _spec[str(key)] except KeyError: try: _key, lang = key.split("#") (_, req, _ser, _, null_allowed) = _spec[_key] except (ValueError, KeyError): try: (_, req, _ser, _, null_allowed) = _spec['*'] except KeyError: _ser = None if _ser: val = _ser(val, "dict", lev) if isinstance(val, Message): _res[key] = val.to_dict(lev + 1) elif isinstance(val, list) and isinstance(next(iter(val or []), None), Message): _res[key] = [v.to_dict(lev) for v in val] else: _res[key] = val return _res def from_dict(self, dictionary, **kwargs): """ Direct translation so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error """ _spec = self.c_param for key, val in dictionary.items(): # Earlier versions of python don't like unicode strings as # variable names if val == "" or val == [""]: continue skey = str(key) if key in _spec: lookup_key = key else: # might be a parameter with a lang tag try: _key, lang = skey.split("#") except ValueError: lookup_key = '*' else: lookup_key = _key if lookup_key in _spec: (vtyp, _, _, _deser, null_allowed) = _spec[lookup_key] self._add_value(skey, vtyp, key, val, _deser, null_allowed) else: self._dict[key] = val return self def _add_value(self, skey, vtyp, key, val, _deser, null_allowed): if isinstance(val, list): if (len(val) == 0 or val[0] is None) and null_allowed is False: return if isinstance(vtyp, list): self._add_value_list(skey, vtyp[0], key, val, _deser, null_allowed) else: if val is None: self._dict[skey] = None elif isinstance(val, bool): if vtyp is bool: self._dict[skey] = val else: raise ValueError('"{}", wrong type of value for "{}"'.format(val, skey)) elif isinstance(val, vtyp): # Not necessary to do anything self._dict[skey] = val else: if _deser: try: val = _deser(val, sformat="dict") except Exception as exc: raise DecodeError(ERRTXT % (key, exc)) elif vtyp is int: try: self._dict[skey] = int(val) except (ValueError, TypeError): raise ValueError('"{}", wrong type of value for "{}"'.format(val, skey)) else: return elif vtyp is bool: raise ValueError('"{}", wrong type of value for "{}"'.format(val, skey)) if isinstance(val, six.string_types): self._dict[skey] = val elif isinstance(val, list): if len(val) == 1: self._dict[skey] = val[0] elif not len(val): pass else: raise TooManyValues(key) else: self._dict[skey] = val def _add_value_list(self, skey, vtype, key, val, _deser, null_allowed): """Add value with internal type (``vtype``) of ``list`` to the message object. :param skey: String representation of key :param vtype: Type of object in list :param key: Key for the object :param val: Value of the object :param _deser: Deserialization method :param null_allowed: If null value is allowed """ if isinstance(val, vtype): if issubclass(vtype, Message): self._dict[skey] = [val] elif _deser is not None: try: self._dict[skey] = _deser(val, sformat="urlencoded") except Exception as exc: raise DecodeError(ERRTXT % (key, exc)) else: setattr(self, skey, [val]) return if isinstance(val, list): if _deser is not None: try: val = _deser(val, sformat="dict") except Exception as exc: raise DecodeError(ERRTXT % (key, exc)) if issubclass(vtype, Message): try: _val = [] for v in val: _val.append(vtype(**dict([(str(x), y) for x, y in v.items()]))) val = _val except Exception as exc: raise DecodeError(ERRTXT % (key, exc)) else: for v in val: if not isinstance(v, vtype): raise DecodeError(ERRTXT % (key, "type != %s (%s)" % (vtype, type(v)))) self._dict[skey] = val return if isinstance(val, dict): try: val = _deser(val, sformat="dict") except Exception as exc: raise DecodeError(ERRTXT % (key, exc)) else: self._dict[skey] = val return raise DecodeError(ERRTXT % (key, "type != %s" % vtype)) def to_json(self, lev=0, indent=None): if lev: return self.to_dict(lev + 1) else: return json.dumps(self.to_dict(1), indent=indent) def from_json(self, txt, **kwargs): return self.from_dict(json.loads(txt)) def to_jwt(self, key=None, algorithm="", lev=0): """ Create a signed JWT representation of the class instance :param key: The signing key :param algorithm: The signature algorithm to use :return: A signed JWT """ _jws = JWS(self.to_json(lev), alg=algorithm) return _jws.sign_compact(key) def _add_key(self, keyjar, issuer, key, key_type='', kid='', no_kid_issuer=None): if issuer not in keyjar: logger.error('Issuer "{}" not in keyjar'.format(issuer)) return logger.debug('Key set summary for {}: {}'.format( issuer, key_summary(keyjar, issuer))) if kid: _key = keyjar.get_key_by_kid(kid, issuer) if _key and _key not in key: key.append(_key) return else: try: kl = keyjar.get_verify_key(owner=issuer, key_type=key_type) except KeyError: pass else: if len(kl) == 1: if kl[0] not in key: key.append(kl[0]) elif no_kid_issuer: try: allowed_kids = no_kid_issuer[issuer] except KeyError: return else: if allowed_kids: key.extend([k for k in kl if k.kid in allowed_kids]) else: key.extend(kl) def get_verify_keys(self, keyjar, key, jso, header, jwt, **kwargs): """ Get keys from a keyjar that can be used to verify a signed JWT :param keyjar: A KeyJar instance :param key: List of keys to start with :param jso: The payload of the JWT, expected to be a dictionary. :param header: The header of the JWT :param jwt: A jwkest.jwt.JWT instance :param kwargs: Other key word arguments :return: list of usable keys """ try: _kid = header['kid'] except KeyError: _kid = '' try: _iss = jso["iss"] except KeyError: pass else: # First extend the keyjar if allowed if "jku" in header: if not keyjar.find(header["jku"], _iss): # This is really questionable try: if kwargs["trusting"]: keyjar.add(jso["iss"], header["jku"]) except KeyError: pass # If there is a kid and a key is found with that kid at the issuer # then I'm done if _kid: jwt["kid"] = _kid try: _key = keyjar.get_key_by_kid(_kid, _iss) if _key: key.append(_key) return key except KeyError: pass try: nki = kwargs['no_kid_issuer'] except KeyError: nki = {} try: _key_type = alg2keytype(header['alg']) except KeyError: _key_type = '' try: self._add_key(keyjar, kwargs["opponent_id"], key, _key_type, _kid, nki) except KeyError: pass for ent in ["iss", "aud", "client_id"]: if ent not in jso: continue if ent == "aud": # list or basestring if isinstance(jso["aud"], six.string_types): _aud = [jso["aud"]] else: _aud = jso["aud"] for _e in _aud: self._add_key(keyjar, _e, key, _key_type, _kid, nki) else: self._add_key(keyjar, jso[ent], key, _key_type, _kid, nki) return key def from_jwt(self, txt, key=None, verify=True, keyjar=None, **kwargs): """ Given a signed and/or encrypted JWT, verify its correctness and then create a class instance from the content. :param txt: The JWT :param key: keys that might be used to decrypt and/or verify the signature of the JWT :param verify: Whether the signature should be verified or not :param keyjar: A KeyJar that might contain the necessary key. :param kwargs: Extra key word arguments :return: A class instance """ # if key is None and keyjar is not None: # key = keyjar.get_verify_key(owner="") # elif key is None: # key = [] # # if keyjar is not None and "sender" in kwargs: # key.extend(keyjar.get_verify_key(owner=kwargs["sender"])) _jw = jwe.factory(txt) if _jw: logger.debug("JWE headers: {}".format(_jw.jwt.headers)) if "algs" in kwargs and "encalg" in kwargs["algs"]: if kwargs["algs"]["encalg"] != _jw["alg"]: raise WrongEncryptionAlgorithm("%s != %s" % (_jw["alg"], kwargs["algs"]["encalg"])) if kwargs["algs"]["encenc"] != _jw["enc"]: raise WrongEncryptionAlgorithm("%s != %s" % (_jw["enc"], kwargs["algs"]["encenc"])) if keyjar: dkeys = keyjar.get_decrypt_key(owner="") if "sender" in kwargs: dkeys.extend(keyjar.get_verify_key(owner=kwargs["sender"])) elif key: dkeys = key else: dkeys = [] logger.debug('Decrypt class: {}'.format(_jw.__class__)) _res = _jw.decrypt(txt, dkeys) logger.debug('decrypted message:{}'.format(_res)) if isinstance(_res, tuple): txt = as_unicode(_res[0]) elif isinstance(_res, list) and len(_res) == 2: txt = as_unicode(_res[0]) else: txt = as_unicode(_res) self.jwe_header = _jw.jwt.headers _jw = jws.factory(txt) if _jw: if "algs" in kwargs and "sign" in kwargs["algs"]: _alg = _jw.jwt.headers["alg"] if kwargs["algs"]["sign"] != _alg: raise WrongSigningAlgorithm("%s != %s" % (_alg, kwargs["algs"]["sign"])) try: _jwt = JWT().unpack(txt) jso = _jwt.payload() _header = _jwt.headers if key is None and keyjar is not None: key = keyjar.get_verify_key(owner="") elif key is None: key = [] if keyjar is not None and "sender" in kwargs: key.extend(keyjar.get_verify_key(owner=kwargs["sender"])) logger.debug("Raw JSON: {}".format(sanitize(jso))) logger.debug("JWS header: {}".format(sanitize(_header))) if _header["alg"] == "none": pass elif verify: if keyjar: key = self.get_verify_keys(keyjar, key, jso, _header, _jw, **kwargs) if "alg" in _header and _header["alg"] != "none": if not key: raise MissingSigningKey( "alg=%s" % _header["alg"]) logger.debug("Found signing key.") try: _jw.verify_compact(txt, key) except NoSuitableSigningKeys: if keyjar: update_keyjar(keyjar) key = self.get_verify_keys(keyjar, key, jso, _header, _jw, **kwargs) _jw.verify_compact(txt, key) except Exception: raise else: self.jws_header = _jwt.headers else: jso = json.loads(txt) self.jwt = txt return self.from_dict(jso) def __str__(self): return '{}'.format(self.to_dict()) def _type_check(self, typ, _allowed, val, na=False): if typ is six.string_types: if val not in _allowed: raise NotAllowedValue(val) elif typ is int: if val not in _allowed: raise NotAllowedValue(val) elif isinstance(typ, list): if isinstance(val, list): # _typ = typ[0] for item in val: if item not in _allowed: raise NotAllowedValue(val) elif val is None and na is False: raise NotAllowedValue(val) def verify(self, **kwargs): """ Make sure all the required values are there and that the values are of the correct type """ _spec = self.c_param try: _allowed = self.c_allowed_values except KeyError: _allowed = {} for (attribute, (typ, required, _, _, na)) in _spec.items(): if attribute == "*": continue try: val = self._dict[attribute] except KeyError: if required: raise MissingRequiredAttribute("%s" % attribute) continue else: if typ == bool: pass elif not val: if required: raise MissingRequiredAttribute("%s" % attribute) continue if attribute not in _allowed: continue if isinstance(typ, tuple): _ityp = None for _typ in typ: try: self._type_check(_typ, _allowed[attribute], val) _ityp = _typ break except ValueError: pass if _ityp is None: raise NotAllowedValue(val) else: self._type_check(typ, _allowed[attribute], val, na) return True def keys(self): """ Return a list of attribute/keys/parameters of this class that has values. :return: A list of attribute names """ return self._dict.keys() def __getitem__(self, item): return self._dict[item] def get(self, item, default=None): try: return self[item] except KeyError: return default def items(self): return self._dict.items() def values(self): return self._dict.values() def __contains__(self, item): return item in self._dict def request(self, location, fragment_enc=False): _l = as_unicode(location) _qp = as_unicode(self.to_urlencoded()) if fragment_enc: return "%s#%s" % (_l, _qp) else: if "?" in location: return "%s&%s" % (_l, _qp) else: return "%s?%s" % (_l, _qp) def __setitem__(self, key, value): try: (vtyp, req, _, _deser, na) = self.c_param[key] self._add_value(str(key), vtyp, key, value, _deser, na) except KeyError: self._dict[key] = value def __eq__(self, other): if not isinstance(other, Message): return False if self.type() != other.type(): return False if self._dict != other._dict: return False return True # def __getattr__(self, item): # return self._dict[item] def __delitem__(self, key): del self._dict[key] def __len__(self): return len(self._dict) def extra(self): return dict([(key, val) for key, val in self._dict.items() if key not in self.c_param]) def
(self): extras = [key for key in self._dict.keys() if key in self.c_param] if not extras: return True else: return False def update(self, item): if isinstance(item, dict): self._dict.update(item) elif isinstance(item, Message): for key, val in item.items(): self._dict[key] = val else: raise ValueError("Can't update message using: '%s'" % (item,)) def to_jwe(self, keys, enc, alg, lev=0): """ Place the information in this instance in a JSON object. Make that JSON object the body of a JWT. Then encrypt that JWT using the specified algorithms and the given keys. Return the encrypted JWT. :param keys: Dictionary, keys are key type and key is the value or simple list. :param enc: Content Encryption Algorithm :param alg: Key Management Algorithm :param lev: Used for JSON construction :return: An encrypted JWT. If encryption failed an exception will be raised. """ if isinstance(keys, dict): keys = keyitems2keyreps(keys) _jwe = JWE(self.to_json(lev), alg=alg, enc=enc) return _jwe.encrypt(keys) def from_jwe(self, msg, keys): """ Decrypt an encrypted JWT and load the JSON object that was the body of the JWT into this object. :param msg: An encrypted JWT :param keys: Dictionary, keys are key type and key is the value or simple list. :return: The decrypted message. If decryption failed an exception will be raised. """ if isinstance(keys, dict): keys = keyitems2keyreps(keys) jwe = JWE() _res = jwe.decrypt(msg, keys) return self.from_json(_res.decode()) def copy(self): return copy.deepcopy(self) def weed(self): """ Get rid of key value pairs that are not standard """ _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k] def rm_blanks(self): """ Get rid of parameters that has no value. """ _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key] # ============================================================================= def by_schema(cls, **kwa): return dict([(key, val) for key, val in kwa.items() if key in cls.c_param]) def add_non_standard(msg1, msg2): for key, val in msg2.extra().items(): if key not in msg1.c_param: msg1[key] = val # ============================================================================= def list_serializer(vals, sformat="urlencoded", lev=0): if isinstance(vals, six.string_types) or not isinstance(vals, list): raise ValueError("Expected list: %s" % vals) if sformat == "urlencoded": return " ".join(vals) else: return vals def list_deserializer(val, sformat="urlencoded"): if sformat == "urlencoded": if isinstance(val, six.string_types): return val.split(" ") elif isinstance(val, list) and len(val) == 1: return val[0].split(" ") else: return val def sp_sep_list_serializer(vals, sformat="urlencoded", lev=0): if isinstance(vals, six.string_types): return vals else: return " ".join(vals) def sp_sep_list_deserializer(val, sformat="urlencoded"): if isinstance(val, six.string_types): return val.split(" ") elif isinstance(val, list) and len(val) == 1: return val[0].split(" ") else: return val def json_serializer(obj, sformat="urlencoded", lev=0): return json.dumps(obj) def json_deserializer(txt, sformat="urlencoded"): return json.loads(txt) VTYPE = 0 VREQUIRED = 1 VSER = 2 VDESER = 3 VNULLALLOWED = 4 SINGLE_REQUIRED_STRING = (basestring, True, None, None, False) SINGLE_OPTIONAL_STRING = (basestring, False, None, None, False) SINGLE_OPTIONAL_INT = (int, False, None, None, False) OPTIONAL_LIST_OF_STRINGS = ([basestring], False, list_serializer, list_deserializer, False) REQUIRED_LIST_OF_STRINGS = ([basestring], True, list_serializer, list_deserializer, False) OPTIONAL_LIST_OF_SP_SEP_STRINGS = ([basestring], False, sp_sep_list_serializer, sp_sep_list_deserializer, False) REQUIRED_LIST_OF_SP_SEP_STRINGS = ([basestring], True, sp_sep_list_serializer, sp_sep_list_deserializer, False) SINGLE_OPTIONAL_JSON = (basestring, False, json_serializer, json_deserializer, False) REQUIRED = [SINGLE_REQUIRED_STRING, REQUIRED_LIST_OF_STRINGS, REQUIRED_LIST_OF_SP_SEP_STRINGS] # # ============================================================================= # class ErrorResponse(Message): c_param = {"error": SINGLE_REQUIRED_STRING, "error_description": SINGLE_OPTIONAL_STRING, "error_uri": SINGLE_OPTIONAL_STRING} class AuthorizationErrorResponse(ErrorResponse): c_param = ErrorResponse.c_param.copy() c_param.update({"state": SINGLE_OPTIONAL_STRING}) c_allowed_values = ErrorResponse.c_allowed_values.copy() c_allowed_values.update({"error": ["invalid_request", "unauthorized_client", "access_denied", "unsupported_response_type", "invalid_scope", "server_error", "temporarily_unavailable"]}) class TokenErrorResponse(ErrorResponse): c_allowed_values = {"error": ["invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", "invalid_scope"]} class AccessTokenRequest(Message): c_param = { "grant_type": SINGLE_REQUIRED_STRING, "code": SINGLE_REQUIRED_STRING, "redirect_uri": SINGLE_REQUIRED_STRING, "client_id": SINGLE_OPTIONAL_STRING, "client_secret": SINGLE_OPTIONAL_STRING, 'state': SINGLE_OPTIONAL_STRING } c_default = {"grant_type": "authorization_code"} class AuthorizationRequest(Message): c_param = { "response_type": REQUIRED_LIST_OF_SP_SEP_STRINGS, "client_id": SINGLE_REQUIRED_STRING, "scope": OPTIONAL_LIST_OF_SP_SEP_STRINGS, "redirect_uri": SINGLE_OPTIONAL_STRING, "state": SINGLE_OPTIONAL_STRING, } class AuthorizationResponse(Message): c_param = { "code": SINGLE_REQUIRED_STRING, "state": SINGLE_OPTIONAL_STRING, 'iss': SINGLE_OPTIONAL_STRING, 'client_id': SINGLE_OPTIONAL_STRING } def verify(self, **kwargs): super(AuthorizationResponse, self).verify(**kwargs) if 'client_id' in self: try: if self['client_id'] != kwargs['client_id']: raise VerificationError('client_id mismatch') except KeyError: logger.info('No client_id to verify against') pass if 'iss' in self: try: # Issuer URL for the authorization server issuing the response. if self['iss'] != kwargs['iss']: raise VerificationError('Issuer mismatch') except KeyError: logger.info('No issuer set in the Client config') pass return True class AccessTokenResponse(Message): c_param = { "access_token": SINGLE_REQUIRED_STRING, "token_type": SINGLE_REQUIRED_STRING, "expires_in": SINGLE_OPTIONAL_INT, "refresh_token": SINGLE_OPTIONAL_STRING, "scope": OPTIONAL_LIST_OF_SP_SEP_STRINGS, "state": SINGLE_OPTIONAL_STRING } class NoneResponse(Message): c_param = { "state": SINGLE_OPTIONAL_STRING } class ROPCAccessTokenRequest(Message): c_param = { "grant_type": SINGLE_REQUIRED_STRING, "username": SINGLE_OPTIONAL_STRING, "password": SINGLE_OPTIONAL_STRING, "scope": OPTIONAL_LIST_OF_SP_SEP_STRINGS } class CCAccessTokenRequest(Message): c_param = { "grant_type": SINGLE_REQUIRED_STRING, "scope": OPTIONAL_LIST_OF_SP_SEP_STRINGS } c_default = {"grant_type": "client_credentials"} c_allowed_values = {"grant_type": ["client_credentials"]} class RefreshAccessTokenRequest(Message): c_param = { "grant_type": SINGLE_REQUIRED_STRING, "refresh_token": SINGLE_REQUIRED_STRING, "scope": OPTIONAL_LIST_OF_SP_SEP_STRINGS, "client_id": SINGLE_OPTIONAL_STRING, "client_secret": SINGLE_OPTIONAL_STRING } c_default = {"grant_type": "refresh_token"} c_allowed_values = {"grant_type": ["refresh_token"]} class ResourceRequest(Message): c_param = {"access_token": SINGLE_OPTIONAL_STRING} class ASConfigurationResponse(Message): c_param = { "issuer": SINGLE_REQUIRED_STRING, "authorization_endpoint": SINGLE_OPTIONAL_STRING, "token_endpoint": SINGLE_OPTIONAL_STRING, "jwks_uri": SINGLE_OPTIONAL_STRING, "registration_endpoint": SINGLE_OPTIONAL_STRING, "scopes_supported": OPTIONAL_LIST_OF_STRINGS, "response_types_supported": REQUIRED_LIST_OF_STRINGS, "response_modes_supported": OPTIONAL_LIST_OF_STRINGS, "grant_types_supported": REQUIRED_LIST_OF_STRINGS, "token_endpoint_auth_methods_supported": OPTIONAL_LIST_OF_STRINGS, "token_endpoint_auth_signing_alg_values_supported": OPTIONAL_LIST_OF_STRINGS, "service_documentation": SINGLE_OPTIONAL_STRING, "ui_locales_supported": OPTIONAL_LIST_OF_STRINGS, "op_policy_uri": SINGLE_OPTIONAL_STRING, "op_tos_uri": SINGLE_OPTIONAL_STRING, 'revocation_endpoint': SINGLE_OPTIONAL_STRING, 'introspection_endpoint': SINGLE_OPTIONAL_STRING, } c_default = {"version": "3.0"} MSG = { "Message": Message, "ErrorResponse": ErrorResponse, "AuthorizationErrorResponse": AuthorizationErrorResponse, "TokenErrorResponse": TokenErrorResponse, "AccessTokenRequest": AccessTokenRequest, "AuthorizationRequest": AuthorizationRequest, "AuthorizationResponse": AuthorizationResponse, "AccessTokenResponse": AccessTokenResponse, "NoneResponse": NoneResponse, "ROPCAccessTokenRequest": ROPCAccessTokenRequest, "CCAccessTokenRequest": CCAccessTokenRequest, "RefreshAccessTokenRequest": RefreshAccessTokenRequest, "ResourceRequest": ResourceRequest, 'ASConfigurationResponse': ASConfigurationResponse } def factory(msgtype): try: return MSG[msgtype] except KeyError: raise FormatError("Unknown message type: %s" % msgtype)
only_extras
index.ts
import PAClient, { AuthInfo, ClientInfo, ServerInfo, Sink } from '@tmigone/pulseaudio' import { retry } from 'ts-retry-promise' export interface BalenaAudioInfo { client: ClientInfo, protocol: AuthInfo, server: ServerInfo } export default class BalenaAudio extends PAClient { public defaultSink: string constructor( public address: string = 'tcp:audio:4317', public subToEvents: boolean = true, public name: string = 'BalenaAudio' ) { super(address) } async listen(): Promise<BalenaAudioInfo> { const protocol: AuthInfo = await this.connectWithRetry() const client: ClientInfo = await this.setClientName(this.name) const server: ServerInfo = await this.getServerInfo() this.defaultSink = server.defaultSink if (this.subToEvents) { await this.subscribe() this.on('sink', async data => { let sink: Sink = await this.getSink(data.index) switch (sink.state) { // running case 0: this.emit('play', sink) break // idle case 1: this.emit('stop', sink) break // suspended case 2: default: break; } }) } return { client, protocol, server } }
return await this.connect() }, { retries: 'INFINITELY', delay: 5000, backoff: 'LINEAR', timeout: 10 * 60 * 1000, logger: (msg) => { console.log(`Error connecting to audio block - ${msg}`) } }) } async getInfo() { if (!this.connected) { throw new Error('Not connected to audio block.') } return await this.getServerInfo() } async setVolume(volume: number, sink?: string | number) { if (!this.connected) { throw new Error('Not connected to audio block.') } let sinkObject: Sink = await this.getSink(sink ?? this.defaultSink) let level: number = Math.round(Math.max(0, Math.min(volume, 100)) / 100 * sinkObject.baseVolume) return await this.setSinkVolume(sinkObject.index, level) } async getVolume(sink?: string | number) { if (!this.connected) { throw new Error('Not connected to audio block.') } let sinkObject: Sink = await this.getSink(sink ?? this.defaultSink) return Math.round(sinkObject.channelVolumes.volumes[0] / sinkObject.baseVolume * 100) } }
async connectWithRetry(): Promise<AuthInfo> { return await retry(async () => {
main-ja.py
# https://huggingface.co/vumichien/wav2vec2-large-xlsr-japanese import torch import torchaudio import librosa from datasets import load_dataset import MeCab from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor import re # config wakati = MeCab.Tagger("-Owakati") chars_to_ignore_regex = '[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\、\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\「\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\」\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\…\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\・]' # load data, processor and model test_dataset = load_dataset("common_voice", "ja", split="test[:2%]") processor = Wav2Vec2Processor.from_pretrained("vumichien/wav2vec2-large-xlsr-japanese") model = Wav2Vec2ForCTC.from_pretrained("vumichien/wav2vec2-large-xlsr-japanese") resampler = lambda sr, y: librosa.resample(y.numpy().squeeze(), sr, 16_000) # Preprocessing the datasets. def speech_file_to_a
ch["sentence"] = wakati.parse(batch["sentence"]).strip() batch["sentence"] = re.sub(chars_to_ignore_regex,'', batch["sentence"]).strip() speech_array, sampling_rate = torchaudio.load(batch["path"]) batch["speech"] = resampler(sampling_rate, speech_array).squeeze() print(batch["sentence"]) return batch test_dataset = test_dataset.map(speech_file_to_array_fn) inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True) with torch.no_grad(): logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits predicted_ids = torch.argmax(logits, dim=-1) print("Prediction:", processor.batch_decode(predicted_ids)) print("Reference:", test_dataset["sentence"][:2])
rray_fn(batch): bat
setup.rs
use azure_core::HttpClient; use azure_cosmos::prelude::*; use std::sync::Arc; pub fn
() -> Result<CosmosClient, CosmosError> { let account = std::env::var("COSMOS_ACCOUNT").expect("Set env variable COSMOS_ACCOUNT first!"); let key = std::env::var("COSMOS_MASTER_KEY").expect("Set env variable COSMOS_MASTER_KEY first!"); let authorization_token = AuthorizationToken::primary_from_base64(&key)?; let http_client: Arc<Box<dyn HttpClient>> = Arc::new(Box::new(reqwest::Client::new())); let client = CosmosClient::new(http_client, account, authorization_token); Ok(client) }
initialize
Artillery.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Artillery = void 0; const Fortifiable_1 = require("@civ-clone/base-unit-type-fortifiable/Fortifiable"); class Artillery extends Fortifiable_1.Fortifiable { } exports.Artillery = Artillery;
exports.default = Artillery; //# sourceMappingURL=Artillery.js.map
fs.rs
#![allow(non_camel_case_types)] use super::fs_helpers::path_get; use crate::ctx::WasiCtx; use crate::fdentry::{Descriptor, FdEntry}; use crate::helpers::*; use crate::memory::*; use crate::sandboxed_tty_writer::SandboxedTTYWriter; use crate::sys::hostcalls_impl::fs_helpers::path_open_rights; use crate::sys::hoststring_from_osstring; use crate::sys::{host_impl, hostcalls_impl}; use crate::{helpers, host, wasi, wasi32, Error, Result}; use filetime::{set_file_handle_times, FileTime}; use log::trace; use std::ffi::OsStr; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::ops::DerefMut; use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub(crate) unsafe fn fd_close( wasi_ctx: &mut WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, ) -> Result<()> { trace!("fd_close(fd={:?})", fd); if let Ok(fe) = wasi_ctx.get_fd_entry(fd) { // can't close preopened files if fe.preopen_path.is_some() { return Err(Error::ENOTSUP); } } wasi_ctx.remove_fd_entry(fd)?; Ok(()) } pub(crate) unsafe fn fd_datasync( wasi_ctx: &WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, ) -> Result<()> { trace!("fd_datasync(fd={:?})", fd); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_DATASYNC, 0)? .as_file()?; fd.sync_data().map_err(Into::into) } pub(crate) unsafe fn fd_pread( wasi_ctx: &WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, iovs_ptr: wasi32::uintptr_t, iovs_len: wasi32::size_t, offset: wasi::__wasi_filesize_t, nread: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_pread(fd={:?}, iovs_ptr={:#x?}, iovs_len={:?}, offset={}, nread={:#x?})", fd, iovs_ptr, iovs_len, offset, nread ); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_READ | wasi::__WASI_RIGHTS_FD_SEEK, 0)? .as_file()?; let iovs = dec_iovec_slice(memory, iovs_ptr, iovs_len)?; if offset > i64::max_value() as u64 { return Err(Error::EIO); } let buf_size = iovs.iter().map(|v| v.buf_len).sum(); let mut buf = vec![0; buf_size]; let host_nread = hostcalls_impl::fd_pread(fd, &mut buf, offset)?; let mut buf_offset = 0; let mut left = host_nread; for iov in &iovs { if left == 0 { break; } let vec_len = std::cmp::min(iov.buf_len, left); std::slice::from_raw_parts_mut(iov.buf as *mut u8, vec_len) .copy_from_slice(&buf[buf_offset..buf_offset + vec_len]); buf_offset += vec_len; left -= vec_len; } trace!(" | *nread={:?}", host_nread); enc_usize_byref(memory, nread, host_nread) } pub(crate) unsafe fn fd_pwrite( wasi_ctx: &WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, iovs_ptr: wasi32::uintptr_t, iovs_len: wasi32::size_t, offset: wasi::__wasi_filesize_t, nwritten: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_pwrite(fd={:?}, iovs_ptr={:#x?}, iovs_len={:?}, offset={}, nwritten={:#x?})", fd, iovs_ptr, iovs_len, offset, nwritten ); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor( wasi::__WASI_RIGHTS_FD_WRITE | wasi::__WASI_RIGHTS_FD_SEEK, 0, )? .as_file()?; let iovs = dec_ciovec_slice(memory, iovs_ptr, iovs_len)?; if offset > i64::max_value() as u64 { return Err(Error::EIO); } let buf_size = iovs.iter().map(|v| v.buf_len).sum(); let mut buf = Vec::with_capacity(buf_size); for iov in &iovs { buf.extend_from_slice(std::slice::from_raw_parts( iov.buf as *const u8, iov.buf_len, )); } let host_nwritten = hostcalls_impl::fd_pwrite(fd, &buf, offset)?; trace!(" | *nwritten={:?}", host_nwritten); enc_usize_byref(memory, nwritten, host_nwritten) } pub(crate) unsafe fn fd_read( wasi_ctx: &mut WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, iovs_ptr: wasi32::uintptr_t, iovs_len: wasi32::size_t, nread: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_read(fd={:?}, iovs_ptr={:#x?}, iovs_len={:?}, nread={:#x?})", fd, iovs_ptr, iovs_len, nread ); let mut iovs = dec_iovec_slice(memory, iovs_ptr, iovs_len)?; let mut iovs: Vec<io::IoSliceMut> = iovs .iter_mut() .map(|vec| host::iovec_to_host_mut(vec)) .collect(); let maybe_host_nread = match wasi_ctx .get_fd_entry_mut(fd)? .as_descriptor_mut(wasi::__WASI_RIGHTS_FD_READ, 0)? { Descriptor::OsHandle(file) => file.read_vectored(&mut iovs), Descriptor::Stdin => io::stdin().read_vectored(&mut iovs), _ => return Err(Error::EBADF), }; let host_nread = maybe_host_nread?; trace!(" | *nread={:?}", host_nread); enc_usize_byref(memory, nread, host_nread) } pub(crate) unsafe fn fd_renumber( wasi_ctx: &mut WasiCtx, _memory: &mut [u8], from: wasi::__wasi_fd_t, to: wasi::__wasi_fd_t, ) -> Result<()> { trace!("fd_renumber(from={:?}, to={:?})", from, to); if !wasi_ctx.contains_fd_entry(from) { return Err(Error::EBADF); } // Don't allow renumbering over a pre-opened resource. // TODO: Eventually, we do want to permit this, once libpreopen in // userspace is capable of removing entries from its tables as well. let from_fe = wasi_ctx.get_fd_entry(from)?; if from_fe.preopen_path.is_some() { return Err(Error::ENOTSUP); } if let Ok(to_fe) = wasi_ctx.get_fd_entry(to) { if to_fe.preopen_path.is_some() { return Err(Error::ENOTSUP); } } let fe = wasi_ctx.remove_fd_entry(from)?; wasi_ctx.insert_fd_entry_at(to, fe); Ok(()) } pub(crate) unsafe fn fd_seek( wasi_ctx: &mut WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, offset: wasi::__wasi_filedelta_t, whence: wasi::__wasi_whence_t, newoffset: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_seek(fd={:?}, offset={:?}, whence={}, newoffset={:#x?})", fd, offset, wasi::whence_to_str(whence), newoffset ); let rights = if offset == 0 && whence == wasi::__WASI_WHENCE_CUR { wasi::__WASI_RIGHTS_FD_TELL } else { wasi::__WASI_RIGHTS_FD_SEEK | wasi::__WASI_RIGHTS_FD_TELL }; let fd = wasi_ctx .get_fd_entry_mut(fd)? .as_descriptor_mut(rights, 0)? .as_file_mut()?; let pos = match whence { wasi::__WASI_WHENCE_CUR => SeekFrom::Current(offset), wasi::__WASI_WHENCE_END => SeekFrom::End(offset), wasi::__WASI_WHENCE_SET => SeekFrom::Start(offset as u64), _ => return Err(Error::EINVAL), }; let host_newoffset = fd.seek(pos)?; trace!(" | *newoffset={:?}", host_newoffset); enc_filesize_byref(memory, newoffset, host_newoffset) } pub(crate) unsafe fn fd_tell( wasi_ctx: &mut WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, newoffset: wasi32::uintptr_t, ) -> Result<()> { trace!("fd_tell(fd={:?}, newoffset={:#x?})", fd, newoffset); let fd = wasi_ctx .get_fd_entry_mut(fd)? .as_descriptor_mut(wasi::__WASI_RIGHTS_FD_TELL, 0)? .as_file_mut()?; let host_offset = fd.seek(SeekFrom::Current(0))?; trace!(" | *newoffset={:?}", host_offset); enc_filesize_byref(memory, newoffset, host_offset) } pub(crate) unsafe fn fd_fdstat_get( wasi_ctx: &WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, fdstat_ptr: wasi32::uintptr_t, // *mut wasi::__wasi_fdstat_t ) -> Result<()> { trace!("fd_fdstat_get(fd={:?}, fdstat_ptr={:#x?})", fd, fdstat_ptr); let mut fdstat = dec_fdstat_byref(memory, fdstat_ptr)?; let host_fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(0, 0)? .as_os_handle(); let fs_flags = hostcalls_impl::fd_fdstat_get(&host_fd)?; let fe = wasi_ctx.get_fd_entry(fd)?; fdstat.fs_filetype = fe.file_type; fdstat.fs_rights_base = fe.rights_base; fdstat.fs_rights_inheriting = fe.rights_inheriting; fdstat.fs_flags = fs_flags; trace!(" | *buf={:?}", fdstat); enc_fdstat_byref(memory, fdstat_ptr, fdstat) } pub(crate) unsafe fn fd_fdstat_set_flags( wasi_ctx: &mut WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, fdflags: wasi::__wasi_fdflags_t, ) -> Result<()> { trace!("fd_fdstat_set_flags(fd={:?}, fdflags={:#x?})", fd, fdflags); let descriptor = wasi_ctx .get_fd_entry_mut(fd)? .as_descriptor_mut(wasi::__WASI_RIGHTS_FD_FDSTAT_SET_FLAGS, 0)?; if let Some(new_handle) = hostcalls_impl::fd_fdstat_set_flags(&descriptor.as_os_handle(), fdflags)? { *descriptor = Descriptor::OsHandle(new_handle); } Ok(()) } pub(crate) unsafe fn fd_fdstat_set_rights( wasi_ctx: &mut WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, fs_rights_base: wasi::__wasi_rights_t, fs_rights_inheriting: wasi::__wasi_rights_t, ) -> Result<()> { trace!( "fd_fdstat_set_rights(fd={:?}, fs_rights_base={:#x?}, fs_rights_inheriting={:#x?})", fd, fs_rights_base, fs_rights_inheriting ); let fe = wasi_ctx.get_fd_entry_mut(fd)?; if fe.rights_base & fs_rights_base != fs_rights_base || fe.rights_inheriting & fs_rights_inheriting != fs_rights_inheriting { return Err(Error::ENOTCAPABLE); } fe.rights_base = fs_rights_base; fe.rights_inheriting = fs_rights_inheriting; Ok(()) } pub(crate) unsafe fn fd_sync( wasi_ctx: &WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, ) -> Result<()> { trace!("fd_sync(fd={:?})", fd); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_SYNC, 0)? .as_file()?; fd.sync_all().map_err(Into::into) } pub(crate) unsafe fn fd_write( wasi_ctx: &mut WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, iovs_ptr: wasi32::uintptr_t, iovs_len: wasi32::size_t, nwritten: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_write(fd={:?}, iovs_ptr={:#x?}, iovs_len={:?}, nwritten={:#x?})", fd, iovs_ptr, iovs_len, nwritten ); let iovs = dec_ciovec_slice(memory, iovs_ptr, iovs_len)?; let iovs: Vec<io::IoSlice> = iovs.iter().map(|vec| host::ciovec_to_host(vec)).collect(); // perform unbuffered writes let entry = wasi_ctx.get_fd_entry_mut(fd)?; let isatty = entry.isatty(); let desc = entry.as_descriptor_mut(wasi::__WASI_RIGHTS_FD_WRITE, 0)?; let host_nwritten = match desc { Descriptor::OsHandle(file) => { if isatty { SandboxedTTYWriter::new(file.deref_mut()).write_vectored(&iovs)? } else { file.write_vectored(&iovs)? } } Descriptor::Stdin => return Err(Error::EBADF), Descriptor::Stdout => { // lock for the duration of the scope let stdout = io::stdout(); let mut stdout = stdout.lock(); let nwritten = if isatty { SandboxedTTYWriter::new(&mut stdout).write_vectored(&iovs)? } else { stdout.write_vectored(&iovs)? }; stdout.flush()?; nwritten } // Always sanitize stderr, even if it's not directly connected to a tty, // because stderr is meant for diagnostics rather than binary output, // and may be redirected to a file which could end up being displayed // on a tty later. Descriptor::Stderr => SandboxedTTYWriter::new(&mut io::stderr()).write_vectored(&iovs)?, }; trace!(" | *nwritten={:?}", host_nwritten); enc_usize_byref(memory, nwritten, host_nwritten) } pub(crate) unsafe fn fd_advise( wasi_ctx: &WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, offset: wasi::__wasi_filesize_t, len: wasi::__wasi_filesize_t, advice: wasi::__wasi_advice_t, ) -> Result<()> { trace!( "fd_advise(fd={:?}, offset={}, len={}, advice={:?})", fd, offset, len, advice ); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_ADVISE, 0)? .as_file()?; hostcalls_impl::fd_advise(fd, advice, offset, len) } pub(crate) unsafe fn fd_allocate( wasi_ctx: &WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, offset: wasi::__wasi_filesize_t, len: wasi::__wasi_filesize_t, ) -> Result<()> { trace!("fd_allocate(fd={:?}, offset={}, len={})", fd, offset, len); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_ALLOCATE, 0)? .as_file()?; let metadata = fd.metadata()?; let current_size = metadata.len(); let wanted_size = offset.checked_add(len).ok_or(Error::E2BIG)?; // This check will be unnecessary when rust-lang/rust#63326 is fixed if wanted_size > i64::max_value() as u64 { return Err(Error::E2BIG); } if wanted_size > current_size { fd.set_len(wanted_size).map_err(Into::into) } else { Ok(()) } } pub(crate) unsafe fn path_create_directory( wasi_ctx: &WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, ) -> Result<()> { trace!( "path_create_directory(dirfd={:?}, path_ptr={:#x?}, path_len={})", dirfd, path_ptr, path_len, ); let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(helpers::path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", path); let rights = wasi::__WASI_RIGHTS_PATH_OPEN | wasi::__WASI_RIGHTS_PATH_CREATE_DIRECTORY; let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get(fe, rights, 0, 0, path, false)?; hostcalls_impl::path_create_directory(resolved) } pub(crate) unsafe fn path_link( wasi_ctx: &WasiCtx, memory: &mut [u8], old_dirfd: wasi::__wasi_fd_t, old_flags: wasi::__wasi_lookupflags_t, old_path_ptr: wasi32::uintptr_t, old_path_len: wasi32::size_t, new_dirfd: wasi::__wasi_fd_t, new_path_ptr: wasi32::uintptr_t, new_path_len: wasi32::size_t, ) -> Result<()> { trace!( "path_link(old_dirfd={:?}, old_flags={:?}, old_path_ptr={:#x?}, old_path_len={}, new_dirfd={:?}, new_path_ptr={:#x?}, new_path_len={})", old_dirfd, old_flags, old_path_ptr, old_path_len, new_dirfd, new_path_ptr, new_path_len, ); let old_path = dec_slice_of_u8(memory, old_path_ptr, old_path_len).and_then(path_from_slice)?; let new_path = dec_slice_of_u8(memory, new_path_ptr, new_path_len).and_then(path_from_slice)?; trace!(" | (old_path_ptr,old_path_len)='{}'", old_path); trace!(" | (new_path_ptr,new_path_len)='{}'", new_path); let old_fe = wasi_ctx.get_fd_entry(old_dirfd)?; let new_fe = wasi_ctx.get_fd_entry(new_dirfd)?; let resolved_old = path_get( old_fe, wasi::__WASI_RIGHTS_PATH_LINK_SOURCE, 0, 0, old_path, false, )?; let resolved_new = path_get( new_fe, wasi::__WASI_RIGHTS_PATH_LINK_TARGET, 0, 0, new_path, false, )?; hostcalls_impl::path_link(resolved_old, resolved_new) } pub(crate) unsafe fn path_open( wasi_ctx: &mut WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, dirflags: wasi::__wasi_lookupflags_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, oflags: wasi::__wasi_oflags_t, fs_rights_base: wasi::__wasi_rights_t, fs_rights_inheriting: wasi::__wasi_rights_t, fs_flags: wasi::__wasi_fdflags_t, fd_out_ptr: wasi32::uintptr_t, ) -> Result<()> { trace!( "path_open(dirfd={:?}, dirflags={:?}, path_ptr={:#x?}, path_len={:?}, oflags={:#x?}, fs_rights_base={:#x?}, fs_rights_inheriting={:#x?}, fs_flags={:#x?}, fd_out_ptr={:#x?})", dirfd, dirflags, path_ptr, path_len, oflags, fs_rights_base, fs_rights_inheriting, fs_flags, fd_out_ptr ); // pre-encode fd_out_ptr to -1 in case of error in opening a path enc_fd_byref(memory, fd_out_ptr, wasi::__wasi_fd_t::max_value())?; let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", path); let (needed_base, needed_inheriting) = path_open_rights(fs_rights_base, fs_rights_inheriting, oflags, fs_flags); trace!( " | needed_base = {}, needed_inheriting = {}", needed_base, needed_inheriting ); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get( fe, needed_base, needed_inheriting, dirflags, path, oflags & wasi::__WASI_OFLAGS_CREAT != 0, )?; // which open mode do we need? let read = fs_rights_base & (wasi::__WASI_RIGHTS_FD_READ | wasi::__WASI_RIGHTS_FD_READDIR) != 0; let write = fs_rights_base & (wasi::__WASI_RIGHTS_FD_DATASYNC | wasi::__WASI_RIGHTS_FD_WRITE | wasi::__WASI_RIGHTS_FD_ALLOCATE | wasi::__WASI_RIGHTS_FD_FILESTAT_SET_SIZE) != 0; trace!( " | calling path_open impl: read={}, write={}", read, write ); let fd = hostcalls_impl::path_open(resolved, read, write, oflags, fs_flags)?; let mut fe = FdEntry::from(fd)?; // We need to manually deny the rights which are not explicitly requested // because FdEntry::from will assign maximal consistent rights. fe.rights_base &= fs_rights_base; fe.rights_inheriting &= fs_rights_inheriting; let guest_fd = wasi_ctx.insert_fd_entry(fe)?; trace!(" | *fd={:?}", guest_fd); enc_fd_byref(memory, fd_out_ptr, guest_fd) } pub(crate) unsafe fn path_readlink( wasi_ctx: &WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, buf_ptr: wasi32::uintptr_t, buf_len: wasi32::size_t, buf_used: wasi32::uintptr_t, ) -> Result<()> { trace!( "path_readlink(dirfd={:?}, path_ptr={:#x?}, path_len={:?}, buf_ptr={:#x?}, buf_len={}, buf_used={:#x?})", dirfd, path_ptr, path_len, buf_ptr, buf_len, buf_used, ); enc_usize_byref(memory, buf_used, 0)?; let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(helpers::path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", &path); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get(fe, wasi::__WASI_RIGHTS_PATH_READLINK, 0, 0, &path, false)?; let mut buf = dec_slice_of_mut_u8(memory, buf_ptr, buf_len)?; let host_bufused = hostcalls_impl::path_readlink(resolved, &mut buf)?; trace!(" | (buf_ptr,*buf_used)={:?}", buf); trace!(" | *buf_used={:?}", host_bufused); enc_usize_byref(memory, buf_used, host_bufused) } pub(crate) unsafe fn path_rename( wasi_ctx: &WasiCtx, memory: &mut [u8], old_dirfd: wasi::__wasi_fd_t, old_path_ptr: wasi32::uintptr_t, old_path_len: wasi32::size_t, new_dirfd: wasi::__wasi_fd_t, new_path_ptr: wasi32::uintptr_t, new_path_len: wasi32::size_t, ) -> Result<()> { trace!( "path_rename(old_dirfd={:?}, old_path_ptr={:#x?}, old_path_len={:?}, new_dirfd={:?}, new_path_ptr={:#x?}, new_path_len={:?})", old_dirfd, old_path_ptr, old_path_len, new_dirfd, new_path_ptr, new_path_len, ); let old_path = dec_slice_of_u8(memory, old_path_ptr, old_path_len).and_then(path_from_slice)?; let new_path = dec_slice_of_u8(memory, new_path_ptr, new_path_len).and_then(path_from_slice)?; trace!(" | (old_path_ptr,old_path_len)='{}'", old_path); trace!(" | (new_path_ptr,new_path_len)='{}'", new_path); let old_fe = wasi_ctx.get_fd_entry(old_dirfd)?; let new_fe = wasi_ctx.get_fd_entry(new_dirfd)?; let resolved_old = path_get( old_fe, wasi::__WASI_RIGHTS_PATH_RENAME_SOURCE, 0, 0, old_path, true, )?; let resolved_new = path_get( new_fe, wasi::__WASI_RIGHTS_PATH_RENAME_TARGET, 0, 0, new_path, true, )?; log::debug!("path_rename resolved_old={:?}", resolved_old); log::debug!("path_rename resolved_new={:?}", resolved_new); hostcalls_impl::path_rename(resolved_old, resolved_new) } pub(crate) unsafe fn fd_filestat_get( wasi_ctx: &WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, filestat_ptr: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_filestat_get(fd={:?}, filestat_ptr={:#x?})", fd, filestat_ptr ); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_FILESTAT_GET, 0)? .as_file()?; let host_filestat = hostcalls_impl::fd_filestat_get(fd)?; trace!(" | *filestat_ptr={:?}", host_filestat); enc_filestat_byref(memory, filestat_ptr, host_filestat) } pub(crate) unsafe fn
( wasi_ctx: &WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, st_atim: wasi::__wasi_timestamp_t, st_mtim: wasi::__wasi_timestamp_t, fst_flags: wasi::__wasi_fstflags_t, ) -> Result<()> { trace!( "fd_filestat_set_times(fd={:?}, st_atim={}, st_mtim={}, fst_flags={:#x?})", fd, st_atim, st_mtim, fst_flags ); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_FILESTAT_SET_TIMES, 0)? .as_file()?; fd_filestat_set_times_impl(fd, st_atim, st_mtim, fst_flags) } pub(crate) fn fd_filestat_set_times_impl( fd: &File, st_atim: wasi::__wasi_timestamp_t, st_mtim: wasi::__wasi_timestamp_t, fst_flags: wasi::__wasi_fstflags_t, ) -> Result<()> { let set_atim = fst_flags & wasi::__WASI_FSTFLAGS_ATIM != 0; let set_atim_now = fst_flags & wasi::__WASI_FSTFLAGS_ATIM_NOW != 0; let set_mtim = fst_flags & wasi::__WASI_FSTFLAGS_MTIM != 0; let set_mtim_now = fst_flags & wasi::__WASI_FSTFLAGS_MTIM_NOW != 0; if (set_atim && set_atim_now) || (set_mtim && set_mtim_now) { return Err(Error::EINVAL); } let atim = if set_atim { let time = UNIX_EPOCH + Duration::from_nanos(st_atim); Some(FileTime::from_system_time(time)) } else if set_atim_now { let time = SystemTime::now(); Some(FileTime::from_system_time(time)) } else { None }; let mtim = if set_mtim { let time = UNIX_EPOCH + Duration::from_nanos(st_mtim); Some(FileTime::from_system_time(time)) } else if set_mtim_now { let time = SystemTime::now(); Some(FileTime::from_system_time(time)) } else { None }; set_file_handle_times(fd, atim, mtim).map_err(Into::into) } pub(crate) unsafe fn fd_filestat_set_size( wasi_ctx: &WasiCtx, _memory: &mut [u8], fd: wasi::__wasi_fd_t, st_size: wasi::__wasi_filesize_t, ) -> Result<()> { trace!("fd_filestat_set_size(fd={:?}, st_size={})", fd, st_size); let fd = wasi_ctx .get_fd_entry(fd)? .as_descriptor(wasi::__WASI_RIGHTS_FD_FILESTAT_SET_SIZE, 0)? .as_file()?; // This check will be unnecessary when rust-lang/rust#63326 is fixed if st_size > i64::max_value() as u64 { return Err(Error::E2BIG); } fd.set_len(st_size).map_err(Into::into) } pub(crate) unsafe fn path_filestat_get( wasi_ctx: &WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, dirflags: wasi::__wasi_lookupflags_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, filestat_ptr: wasi32::uintptr_t, ) -> Result<()> { trace!( "path_filestat_get(dirfd={:?}, dirflags={:?}, path_ptr={:#x?}, path_len={}, filestat_ptr={:#x?})", dirfd, dirflags, path_ptr, path_len, filestat_ptr ); let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", path); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get( fe, wasi::__WASI_RIGHTS_PATH_FILESTAT_GET, 0, dirflags, path, false, )?; let host_filestat = hostcalls_impl::path_filestat_get(resolved, dirflags)?; trace!(" | *filestat_ptr={:?}", host_filestat); enc_filestat_byref(memory, filestat_ptr, host_filestat) } pub(crate) unsafe fn path_filestat_set_times( wasi_ctx: &WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, dirflags: wasi::__wasi_lookupflags_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, st_atim: wasi::__wasi_timestamp_t, st_mtim: wasi::__wasi_timestamp_t, fst_flags: wasi::__wasi_fstflags_t, ) -> Result<()> { trace!( "path_filestat_set_times(dirfd={:?}, dirflags={:?}, path_ptr={:#x?}, path_len={}, st_atim={}, st_mtim={}, fst_flags={:#x?})", dirfd, dirflags, path_ptr, path_len, st_atim, st_mtim, fst_flags ); let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", path); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get( fe, wasi::__WASI_RIGHTS_PATH_FILESTAT_SET_TIMES, 0, dirflags, path, false, )?; hostcalls_impl::path_filestat_set_times(resolved, dirflags, st_atim, st_mtim, fst_flags) } pub(crate) unsafe fn path_symlink( wasi_ctx: &WasiCtx, memory: &mut [u8], old_path_ptr: wasi32::uintptr_t, old_path_len: wasi32::size_t, dirfd: wasi::__wasi_fd_t, new_path_ptr: wasi32::uintptr_t, new_path_len: wasi32::size_t, ) -> Result<()> { trace!( "path_symlink(old_path_ptr={:#x?}, old_path_len={}, dirfd={:?}, new_path_ptr={:#x?}, new_path_len={})", old_path_ptr, old_path_len, dirfd, new_path_ptr, new_path_len ); let old_path = dec_slice_of_u8(memory, old_path_ptr, old_path_len).and_then(path_from_slice)?; let new_path = dec_slice_of_u8(memory, new_path_ptr, new_path_len).and_then(path_from_slice)?; trace!(" | (old_path_ptr,old_path_len)='{}'", old_path); trace!(" | (new_path_ptr,new_path_len)='{}'", new_path); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved_new = path_get(fe, wasi::__WASI_RIGHTS_PATH_SYMLINK, 0, 0, new_path, true)?; let owned_old = hoststring_from_osstring(OsStr::new(old_path).to_os_string()); hostcalls_impl::path_symlink(owned_old.as_ref(), resolved_new) } pub(crate) unsafe fn path_unlink_file( wasi_ctx: &WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, ) -> Result<()> { trace!( "path_unlink_file(dirfd={:?}, path_ptr={:#x?}, path_len={})", dirfd, path_ptr, path_len ); let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", path); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get(fe, wasi::__WASI_RIGHTS_PATH_UNLINK_FILE, 0, 0, path, false)?; hostcalls_impl::path_unlink_file(resolved) } pub(crate) unsafe fn path_remove_directory( wasi_ctx: &WasiCtx, memory: &mut [u8], dirfd: wasi::__wasi_fd_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, ) -> Result<()> { trace!( "path_remove_directory(dirfd={:?}, path_ptr={:#x?}, path_len={})", dirfd, path_ptr, path_len ); let path = dec_slice_of_u8(memory, path_ptr, path_len).and_then(path_from_slice)?; trace!(" | (path_ptr,path_len)='{}'", path); let fe = wasi_ctx.get_fd_entry(dirfd)?; let resolved = path_get( fe, wasi::__WASI_RIGHTS_PATH_REMOVE_DIRECTORY, 0, 0, path, true, )?; log::debug!("path_remove_directory resolved={:?}", resolved); hostcalls_impl::path_remove_directory(resolved) } pub(crate) unsafe fn fd_prestat_get( wasi_ctx: &WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, prestat_ptr: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_prestat_get(fd={:?}, prestat_ptr={:#x?})", fd, prestat_ptr ); // TODO: should we validate any rights here? let fe = wasi_ctx.get_fd_entry(fd)?; let po_path = fe.preopen_path.as_ref().ok_or(Error::ENOTSUP)?; if fe.file_type != wasi::__WASI_FILETYPE_DIRECTORY { return Err(Error::ENOTDIR); } let path = host_impl::path_from_host(po_path.as_os_str())?; enc_prestat_byref( memory, prestat_ptr, host::__wasi_prestat_t { tag: wasi::__WASI_PREOPENTYPE_DIR, u: host::__wasi_prestat_u_t { dir: host::__wasi_prestat_dir_t { pr_name_len: path.len(), }, }, }, ) } pub(crate) unsafe fn fd_prestat_dir_name( wasi_ctx: &WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, path_ptr: wasi32::uintptr_t, path_len: wasi32::size_t, ) -> Result<()> { trace!( "fd_prestat_dir_name(fd={:?}, path_ptr={:#x?}, path_len={})", fd, path_ptr, path_len ); // TODO: should we validate any rights here? let fe = wasi_ctx.get_fd_entry(fd)?; let po_path = fe.preopen_path.as_ref().ok_or(Error::ENOTSUP)?; if fe.file_type != wasi::__WASI_FILETYPE_DIRECTORY { return Err(Error::ENOTDIR); } let path = host_impl::path_from_host(po_path.as_os_str())?; if path.len() > dec_usize(path_len) { return Err(Error::ENAMETOOLONG); } trace!(" | (path_ptr,path_len)='{}'", path); enc_slice_of_u8(memory, path.as_bytes(), path_ptr) } pub(crate) unsafe fn fd_readdir( wasi_ctx: &mut WasiCtx, memory: &mut [u8], fd: wasi::__wasi_fd_t, buf: wasi32::uintptr_t, buf_len: wasi32::size_t, cookie: wasi::__wasi_dircookie_t, buf_used: wasi32::uintptr_t, ) -> Result<()> { trace!( "fd_readdir(fd={:?}, buf={:#x?}, buf_len={}, cookie={:#x?}, buf_used={:#x?})", fd, buf, buf_len, cookie, buf_used, ); enc_usize_byref(memory, buf_used, 0)?; let file = wasi_ctx .get_fd_entry_mut(fd)? .as_descriptor_mut(wasi::__WASI_RIGHTS_FD_READDIR, 0)? .as_file_mut()?; let mut host_buf = dec_slice_of_mut_u8(memory, buf, buf_len)?; trace!(" | (buf,buf_len)={:?}", host_buf); let iter = hostcalls_impl::fd_readdir(file, cookie)?; let mut host_bufused = 0; for dirent in iter { let dirent_raw = dirent?.to_wasi_raw()?; let offset = dirent_raw.len(); if host_buf.len() < offset { break; } else { host_buf[0..offset].copy_from_slice(&dirent_raw); host_bufused += offset; host_buf = &mut host_buf[offset..]; } } trace!(" | *buf_used={:?}", host_bufused); enc_usize_byref(memory, buf_used, host_bufused) }
fd_filestat_set_times
index.js
let _id = 1; export function uniqueId() { return _id++; }
type: 'CREATE_TASK', payload: { id: uniqueId(), title, description, status: 'Unstarted' }, }; } export function editTask(id, params = {}) { return { type: 'EDIT_TASK', payload: { id, params, }, }; }
export function createTask({ title, description }) { return {
netapp_e_volume_copy.py
#!/usr/bin/python # (c) 2016, NetApp, Inc # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = """ --- module: netapp_e_volume_copy short_description: Create volume copy pairs description: - Create and delete snapshots images on volume groups for NetApp E-series storage arrays. version_added: '2.2' author: Kevin Hulquest (@hulquest) options: api_username: required: true description: - The username to authenticate with the SANtricity WebServices Proxy or embedded REST API. api_password: required: true description: - The password to authenticate with the SANtricity WebServices Proxy or embedded REST API. api_url: required: true description: - The url to the SANtricity WebServices Proxy or embedded REST API. example: - https://prod-1.wahoo.acme.com/devmgr/v2 validate_certs: required: false default: true description: - Should https certificates be validated? source_volume_id: description: - The the id of the volume copy source. - If used, must be paired with destination_volume_id - Mutually exclusive with volume_copy_pair_id, and search_volume_id destination_volume_id: description: - The the id of the volume copy destination. - If used, must be paired with source_volume_id - Mutually exclusive with volume_copy_pair_id, and search_volume_id volume_copy_pair_id: description: - The the id of a given volume copy pair - Mutually exclusive with destination_volume_id, source_volume_id, and search_volume_id - Can use to delete or check presence of volume pairs - Must specify this or (destination_volume_id and source_volume_id) state: description: - Whether the specified volume copy pair should exist or not. required: True choices: ['present', 'absent'] create_copy_pair_if_does_not_exist: description: - Defines if a copy pair will be created if it does not exist. - If set to True destination_volume_id and source_volume_id are required. choices: [True, False] default: True start_stop_copy: description: - starts a re-copy or stops a copy in progress - "Note: If you stop the initial file copy before it it done the copy pair will be destroyed" - Requires volume_copy_pair_id search_volume_id: description: - Searches for all valid potential target and source volumes that could be used in a copy_pair - Mutually exclusive with volume_copy_pair_id, destination_volume_id and source_volume_id """ RESULTS = """ """ EXAMPLES = """ --- msg: description: Success message returned: success type: string sample: Json facts for the volume copy that was created. """ RETURN = """ msg: description: Success message returned: success type: string sample: Created Volume Copy Pair with ID """ import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.urls import open_url from ansible.module_utils.six.moves.urllib.error import HTTPError HEADERS = { "Content-Type": "application/json", "Accept": "application/json", } def request(url, data=None, headers=None, method='GET', use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False): try: r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) except HTTPError: err = get_exception() r = err.fp try: raw_data = r.read() if raw_data: data = json.loads(raw_data) else: raw_data = None except: if ignore_errors: pass else: raise Exception(raw_data) resp_code = r.getcode() if resp_code >= 400 and not ignore_errors: raise Exception(resp_code, data) else: return resp_code, data def find_volume_copy_pair_id_from_source_volume_id_and_destination_volume_id(params): get_status = 'storage-systems/%s/volume-copy-jobs' % params['ssid'] url = params['api_url'] + get_status (rc, resp) = request(url, method='GET', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) volume_copy_pair_id = None for potential_copy_pair in resp: if potential_copy_pair['sourceVolume'] == params['source_volume_id']: if potential_copy_pair['sourceVolume'] == params['source_volume_id']: volume_copy_pair_id = potential_copy_pair['id'] return volume_copy_pair_id def create_copy_pair(params): get_status = 'storage-systems/%s/volume-copy-jobs' % params['ssid'] url = params['api_url'] + get_status rData = { "sourceId": params['source_volume_id'], "targetId": params['destination_volume_id'] } (rc, resp) = request(url, data=json.dumps(rData), ignore_errors=True, method='POST', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) if rc != 200: return False, (rc, resp) else: return True, (rc, resp) def delete_copy_pair_by_copy_pair_id(params): get_status = 'storage-systems/%s/volume-copy-jobs/%s?retainRepositories=false' % ( params['ssid'], params['volume_copy_pair_id']) url = params['api_url'] + get_status (rc, resp) = request(url, ignore_errors=True, method='DELETE', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) if rc != 204: return False, (rc, resp) else: return True, (rc, resp) def find_volume_copy_pair_id_by_volume_copy_pair_id(params): get_status = 'storage-systems/%s/volume-copy-jobs/%s?retainRepositories=false' % ( params['ssid'], params['volume_copy_pair_id']) url = params['api_url'] + get_status (rc, resp) = request(url, ignore_errors=True, method='DELETE', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) if rc != 200: return False, (rc, resp) else: return True, (rc, resp) def start_stop_copy(params): get_status = 'storage-systems/%s/volume-copy-jobs-control/%s?control=%s' % ( params['ssid'], params['volume_copy_pair_id'], params['start_stop_copy']) url = params['api_url'] + get_status (response_code, response_data) = request(url, ignore_errors=True, method='POST', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) if response_code == 200: return True, response_data[0]['percentComplete'] else: return False, response_data def check_copy_status(params): get_status = 'storage-systems/%s/volume-copy-jobs-control/%s' % ( params['ssid'], params['volume_copy_pair_id']) url = params['api_url'] + get_status (response_code, response_data) = request(url, ignore_errors=True, method='GET', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) if response_code == 200: if response_data['percentComplete'] != -1: return True, response_data['percentComplete'] else: return False, response_data['percentComplete'] else: return False, response_data def find_valid_copy_pair_targets_and_sources(params): get_status = 'storage-systems/%s/volumes' % params['ssid'] url = params['api_url'] + get_status (response_code, response_data) = request(url, ignore_errors=True, method='GET', url_username=params['api_username'], url_password=params['api_password'], headers=HEADERS, validate_certs=params['validate_certs']) if response_code == 200:
if volume['id'] == params['search_volume_id']: source_capacity = volume['capacity'] else: candidates.append(volume) potential_sources = [] potential_targets = [] for volume in candidates: if volume['capacity'] > source_capacity: if volume['volumeCopyTarget'] is False: if volume['volumeCopySource'] is False: potential_targets.append(volume['id']) else: if volume['volumeCopyTarget'] is False: if volume['volumeCopySource'] is False: potential_sources.append(volume['id']) return potential_targets, potential_sources else: raise Exception("Response [%s]" % response_code) def main(): module = AnsibleModule(argument_spec=dict( source_volume_id=dict(type='str'), destination_volume_id=dict(type='str'), copy_priority=dict(required=False, default=0, type='int'), ssid=dict(required=True, type='str'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True), validate_certs=dict(required=False, default=True), targetWriteProtected=dict(required=False, default=True, type='bool'), onlineCopy=dict(required=False, default=False, type='bool'), volume_copy_pair_id=dict(type='str'), status=dict(required=True, choices=['present', 'absent'], type='str'), create_copy_pair_if_does_not_exist=dict(required=False, default=True, type='bool'), start_stop_copy=dict(required=False, choices=['start', 'stop'], type='str'), search_volume_id=dict(type='str'), ), mutually_exclusive=[['volume_copy_pair_id', 'destination_volume_id'], ['volume_copy_pair_id', 'source_volume_id'], ['volume_copy_pair_id', 'search_volume_id'], ['search_volume_id', 'destination_volume_id'], ['search_volume_id', 'source_volume_id'], ], required_together=[['source_volume_id', 'destination_volume_id'], ], required_if=[["create_copy_pair_if_does_not_exist", True, ['source_volume_id', 'destination_volume_id'], ], ["start_stop_copy", 'stop', ['volume_copy_pair_id'], ], ["start_stop_copy", 'start', ['volume_copy_pair_id'], ], ] ) params = module.params if not params['api_url'].endswith('/'): params['api_url'] += '/' # Check if we want to search if params['search_volume_id'] is not None: try: potential_targets, potential_sources = find_valid_copy_pair_targets_and_sources(params) except: e = get_exception() module.fail_json(msg="Failed to find valid copy pair candidates. Error [%s]" % str(e)) module.exit_json(changed=False, msg=' Valid source devices found: %s Valid target devices found: %s' % (len(potential_sources), len(potential_targets)), search_volume_id=params['search_volume_id'], valid_targets=potential_targets, valid_sources=potential_sources) # Check if we want to start or stop a copy operation if params['start_stop_copy'] == 'start' or params['start_stop_copy'] == 'stop': # Get the current status info currenty_running, status_info = check_copy_status(params) # If we want to start if params['start_stop_copy'] == 'start': # If we have already started if currenty_running is True: module.exit_json(changed=False, msg='Volume Copy Pair copy has started.', volume_copy_pair_id=params['volume_copy_pair_id'], percent_done=status_info) # If we need to start else: start_status, info = start_stop_copy(params) if start_status is True: module.exit_json(changed=True, msg='Volume Copy Pair copy has started.', volume_copy_pair_id=params['volume_copy_pair_id'], percent_done=info) else: module.fail_json(msg="Could not start volume copy pair Error: %s" % info) # If we want to stop else: # If it has already stopped if currenty_running is False: module.exit_json(changed=False, msg='Volume Copy Pair copy is stopped.', volume_copy_pair_id=params['volume_copy_pair_id']) # If we need to stop it else: start_status, info = start_stop_copy(params) if start_status is True: module.exit_json(changed=True, msg='Volume Copy Pair copy has been stopped.', volume_copy_pair_id=params['volume_copy_pair_id']) else: module.fail_json(msg="Could not stop volume copy pair Error: %s" % info) # If we want the copy pair to exist we do this stuff if params['status'] == 'present': # We need to check if it exists first if params['volume_copy_pair_id'] is None: params['volume_copy_pair_id'] = find_volume_copy_pair_id_from_source_volume_id_and_destination_volume_id( params) # If no volume copy pair is found we need need to make it. if params['volume_copy_pair_id'] is None: # In order to create we can not do so with just a volume_copy_pair_id copy_began_status, (rc, resp) = create_copy_pair(params) if copy_began_status is True: module.exit_json(changed=True, msg='Created Volume Copy Pair with ID: %s' % resp['id']) else: module.fail_json(msg="Could not create volume copy pair Code: %s Error: %s" % (rc, resp)) # If it does exist we do nothing else: # We verify that it exists exist_status, (exist_status_code, exist_status_data) = find_volume_copy_pair_id_by_volume_copy_pair_id( params) if exist_status: module.exit_json(changed=False, msg=' Volume Copy Pair with ID: %s exists' % params['volume_copy_pair_id']) else: if exist_status_code == 404: module.fail_json( msg=' Volume Copy Pair with ID: %s does not exist. Can not create without source_volume_id and destination_volume_id' % params['volume_copy_pair_id']) else: module.fail_json(msg="Could not find volume copy pair Code: %s Error: %s" % ( exist_status_code, exist_status_data)) module.fail_json(msg="Done") # If we want it to not exist we do this else: if params['volume_copy_pair_id'] is None: params['volume_copy_pair_id'] = find_volume_copy_pair_id_from_source_volume_id_and_destination_volume_id( params) # We delete it by the volume_copy_pair_id delete_status, (delete_status_code, delete_status_data) = delete_copy_pair_by_copy_pair_id(params) if delete_status is True: module.exit_json(changed=True, msg=' Volume Copy Pair with ID: %s was deleted' % params['volume_copy_pair_id']) else: if delete_status_code == 404: module.exit_json(changed=False, msg=' Volume Copy Pair with ID: %s does not exist' % params['volume_copy_pair_id']) else: module.fail_json(msg="Could not delete volume copy pair Code: %s Error: %s" % ( delete_status_code, delete_status_data)) if __name__ == '__main__': main()
source_capacity = None candidates = [] for volume in response_data:
loyalty.py
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ import urllib from google.appengine.api import images from google.appengine.ext import db, blobstore from rogerthat.bizz.gcs import get_serving_url from rogerthat.dal import parent_key, parent_key_unsafe from rogerthat.rpc import users from rogerthat.utils import now from rogerthat.utils.app import create_app_user_by_email from rogerthat.utils.crypto import sha256_hex from rogerthat.utils.service import get_identity_from_service_identity_user, \ get_service_user_from_service_identity_user from solutions.common import SOLUTION_COMMON from solutions.common.models.properties import SolutionUserProperty from solutions.common.utils import create_service_identity_user_wo_default class SolutionLoyaltySlide(db.Model): timestamp = db.IntegerProperty() name = db.StringProperty(indexed=False) time = db.IntegerProperty(indexed=False) item = blobstore.BlobReferenceProperty() gcs_filename = db.StringProperty(indexed=False) content_type = db.StringProperty(indexed=False) deleted = db.BooleanProperty(default=False) @property def id(self): return self.key().id() @property def function_dependencies(self): return 0 def item_url(self): if self.gcs_filename: k = blobstore.create_gs_key('/gs' + self.gcs_filename) else: k = self.item return unicode(images.get_serving_url(k, secure_url=True)) def slide_url(self): from rogerthat.settings import get_server_settings server_settings = get_server_settings() if self.gcs_filename: return get_serving_url(self.gcs_filename) return unicode("%s/unauthenticated/loyalty/slide?%s" % (server_settings.baseUrl, urllib.urlencode(dict(slide_key=self.item.key())))) @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) class SolutionLoyaltyVisitRevenueDiscount(db.Model): app_user = db.UserProperty() app_user_info = SolutionUserProperty() admin_user = db.UserProperty() timestamp = db.IntegerProperty() redeemed = db.BooleanProperty(default=False) redeemed_admin_user = db.UserProperty() redeemed_timestamp = db.IntegerProperty() price = db.IntegerProperty(indexed=False) # in euro cents @property def key_str(self): return str(self.key()) @property def loyalty_type(self): return SolutionLoyaltySettings.LOYALTY_TYPE_REVENUE_DISCOUNT @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @property def price_in_euro(self): return '{:0,.2f}'.format(self.price / 100.0) def discount_in_euro(self, x_discount): return '{:0,.2f}'.format(self.price * x_discount / 10000.0) @classmethod def load(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) qry = cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) qry.filter('redeemed', False) qry.order('-timestamp') return qry @classmethod def get_for_time_period(cls, service_user, service_identity, first_day, last_day): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return cls.all() \ .ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) \ .filter('redeemed_timestamp >=', first_day) \ .filter('redeemed_timestamp <', last_day) class SolutionLoyaltyVisitLottery(db.Model): app_user = db.UserProperty() app_user_info = SolutionUserProperty() admin_user = db.UserProperty() timestamp = db.IntegerProperty() redeemed = db.BooleanProperty(default=False) redeemed_timestamp = db.IntegerProperty() @property def key_str(self): return str(self.key()) @property def timestamp_day(self): return long(self.key().name().split("|")[0]) @property def loyalty_type(self): return SolutionLoyaltySettings.LOYALTY_TYPE_LOTTERY @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @classmethod def load(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) qry = cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) qry.filter('redeemed =', False) qry.order('-timestamp') return qry @classmethod def create_key(cls, service_user, service_identity, app_user, timestamp_day): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return db.Key.from_path(cls.kind(), "%s|%s" % (timestamp_day, app_user.email()), parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) class SolutionLoyaltyVisitStamps(db.Model): app_user = db.UserProperty() app_user_info = SolutionUserProperty() admin_user = db.UserProperty() timestamp = db.IntegerProperty() redeemed = db.BooleanProperty(default=False) redeemed_admin_user = db.UserProperty() redeemed_timestamp = db.IntegerProperty() count = db.IntegerProperty() x_stamps = db.IntegerProperty(indexed=False) winnings = db.TextProperty() @property def key_str(self): return str(self.key()) @property def loyalty_type(self): return SolutionLoyaltySettings.LOYALTY_TYPE_STAMPS @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @classmethod def load(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) qry = cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) qry.filter('redeemed', False) qry.order('-timestamp') return qry @classmethod def get_for_time_period(cls, service_user, service_identity, first_day, last_day): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return cls.all() \ .ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) \ .filter('redeemed_timestamp >=', first_day) \ .filter('redeemed_timestamp <', last_day) class SolutionLoyaltyIdentitySettings(db.Model): admins = db.StringListProperty(indexed=False) app_ids = db.StringListProperty(indexed=False) names = db.StringListProperty(indexed=False) functions = db.ListProperty(int, indexed=False) name_index = db.IntegerProperty(indexed=False) image_uri = db.StringProperty(indexed=False) content_uri = db.StringProperty(indexed=False) @staticmethod def create_key(service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return db.Key.from_path(SolutionLoyaltyIdentitySettings.kind(), service_identity_user.email(), parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) @classmethod def get_by_user(cls, service_user, service_identity): return cls.get(cls.create_key(service_user, service_identity)) class SolutionLoyaltySettings(SolutionLoyaltyIdentitySettings): LOYALTY_TYPE_REVENUE_DISCOUNT = 1 LOYALTY_TYPE_LOTTERY = 2 LOYALTY_TYPE_STAMPS = 3 LOYALTY_TYPE_CITY_WIDE_LOTTERY = 4 LOYALTY_TYPE_SLIDES_ONLY = 5 LOYALTY_TYPE_MAPPING = {LOYALTY_TYPE_REVENUE_DISCOUNT: SolutionLoyaltyVisitRevenueDiscount, LOYALTY_TYPE_LOTTERY: SolutionLoyaltyVisitLottery, LOYALTY_TYPE_STAMPS: SolutionLoyaltyVisitStamps} FUNCTION_SCAN = 1 FUNCTION_SLIDESHOW = 2 FUNCTION_ADD_REDEEM_LOYALTY_POINTS = 4 loyalty_type = db.IntegerProperty(default=LOYALTY_TYPE_REVENUE_DISCOUNT) website = db.StringProperty(indexed=False) branding_key = db.StringProperty(indexed=False) # rogerthat branding key branding_creation_time = db.IntegerProperty(default=0, indexed=False) modification_time = db.IntegerProperty(default=0, indexed=False) # LOYALTY_TYPE_REVENUE_DISCOUNT x_visits = db.IntegerProperty(indexed=False, default=10) x_discount = db.IntegerProperty(indexed=False, default=5) # LOYALTY_TYPE_LOTTERY has its own model # LOYALTY_TYPE_STAMPS x_stamps = db.IntegerProperty(indexed=False, default=8) stamps_type = db.IntegerProperty(indexed=False, default=1) stamps_winnings = db.TextProperty() stamps_auto_redeem = db.BooleanProperty(indexed=False, default=False) @property def service_user(self): return users.User(self.parent_key().name()) @classmethod def create_key(cls, service_user): return db.Key.from_path(cls.kind(), service_user.email(), parent=parent_key(service_user, SOLUTION_COMMON)) @classmethod def get_by_user(cls, service_user): return cls.get(cls.create_key(service_user)) class SolutionUserLoyaltySettings(db.Model): reminders_disabled = db.BooleanProperty(indexed=False, default=False) reminders_disabled_for = db.StringListProperty(indexed=False) @property def app_user(self): return users.User(self.parent_key().name()) @classmethod def createKey(cls, app_user): return db.Key.from_path(cls.kind(), app_user.email(), parent=parent_key(app_user, SOLUTION_COMMON)) @classmethod def get_by_user(cls, app_user): return cls.get(cls.createKey(app_user)) class SolutionLoyaltyScan(db.Model): tablet_email = db.StringProperty(indexed=False) tablet_app_id = db.StringProperty(indexed=False) tablet_name = db.StringProperty(indexed=False) user_name = db.StringProperty(indexed=False) timestamp = db.IntegerProperty() processed = db.BooleanProperty(default=False) app_user_info = SolutionUserProperty() @property def key_str(self): return str(self.key()) @property def admin_user(self): return create_app_user_by_email(self.tablet_email, self.tablet_app_id) @property def app_user(self): return users.User(self.key().name()) @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @classmethod def create_key(cls, app_user, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return db.Key.from_path(cls.kind(), app_user.email(), parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) @classmethod def get_by_service_user(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)).filter("processed =", False).filter("timestamp >", now() - (60 * 60 * 24)).order("timestamp") class SolutionLoyaltyLottery(db.Model): schedule_loot_time = db.IntegerProperty() timestamp = db.IntegerProperty() end_timestamp = db.IntegerProperty() winnings = db.TextProperty() winner = db.UserProperty() # app_user winner_info = SolutionUserProperty() winner_timestamp = db.IntegerProperty() skip_winners = db.ListProperty(users.User, indexed=False) solution_inbox_message_key = db.StringProperty(indexed=False) deleted = db.BooleanProperty(default=False) pending = db.BooleanProperty(default=False) redeemed = db.BooleanProperty(default=False) claimed = db.BooleanProperty(default=False) count = db.ListProperty(int, indexed=False) # this will be filled in when the lottery is redeemed app_users = db.ListProperty(users.User, indexed=False) # this will be filled in when the lottery is redeemed @property def key_str(self): return str(self.key()) @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @classmethod def load_all(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) qry = cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) qry.filter('deleted =', False) return qry @classmethod def load_active(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) qry = cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) qry.filter('deleted =', False) qry.filter('redeemed =', False) return qry @classmethod def load_pending(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) qry = cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) qry.filter('deleted =', False) qry.filter('pending =', True) qry.order("end_timestamp") return qry.get() @classmethod def get_for_time_period(cls, service_user, service_identity, first_day, last_day): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return cls.all() \ .ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) \ .filter('winner_timestamp >', first_day) \ .filter('winner_timestamp <', last_day) \ .filter('deleted =', False) \ .filter('claimed', True) class SolutionLoyaltyLotteryStatistics(db.Model): count = db.ListProperty(int, indexed=False) app_users = db.ListProperty(users.User, indexed=False) @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @classmethod def create_key(cls, service_user, service_identity): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return db.Key.from_path(cls.kind(), service_user.email(), parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) @classmethod def get_by_user(cls, service_user, service_identity): return cls.get(cls.create_key(service_user, service_identity)) class SolutionLoyaltyExport(db.Model): pdf = db.BlobProperty() year_month = db.IntegerProperty() # 201511 @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @classmethod def create_key(cls, service_user, service_identity, year, month): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return db.Key.from_path(cls.kind(), '%s_%s' % (year, month), parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) @classmethod def list_by_service_user(cls, service_user, service_identity):
class SolutionCityWideLotteryVisit(db.Model): original_visit_key = db.StringProperty(indexed=True) original_loyalty_type = db.IntegerProperty(indexed=False) app_user = db.UserProperty() app_user_info = SolutionUserProperty() timestamp = db.IntegerProperty(indexed=True) redeemed = db.BooleanProperty(indexed=True) redeemed_timestamp = db.IntegerProperty(indexed=False) @property def key_str(self): return str(self.key()) @property def loyalty_type(self): return SolutionLoyaltySettings.LOYALTY_TYPE_LOTTERY @property def service_identity_user(self): return users.User(self.parent_key().name()) @property def service_user(self): return get_service_user_from_service_identity_user(self.service_identity_user) @property def service_identity(self): return get_identity_from_service_identity_user(self.service_identity_user) @property def app_id(self): return self.parent_key().parent().name() @property def timestamp_day(self): return self.timestamp - (self.timestamp % (3600 * 24)) # TODO communities: should be service user as parent instead @classmethod def create_city_parent_key(cls, app_id): return db.Key.from_path(u"city_wide_lottery", app_id) @classmethod def create_parent_key(cls, app_id, service_user, service_identity, app_user): service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) city_ancestor_key = cls.create_city_parent_key(app_id) service_ancestor_key = db.Key.from_path(SOLUTION_COMMON, service_identity_user.email(), parent=city_ancestor_key) return db.Key.from_path(cls.kind(), app_user.email(), parent=service_ancestor_key) @classmethod def list_by_app_id(cls, app_id): city_ancestor_key = cls.create_city_parent_key(app_id) return cls.all().ancestor(city_ancestor_key).filter('redeemed =', False) @classmethod def get_visit_by_original_visit_key(cls, app_id, service_user, service_identity, app_user, visit_key): parent_key = cls.create_parent_key(app_id, service_user, service_identity, app_user) return cls.all().ancestor(parent_key).filter("original_visit_key =", visit_key).get() @classmethod def load(cls, app_id): city_ancestor_key = cls.create_city_parent_key(app_id) qry = cls.all().ancestor(city_ancestor_key) qry.filter("redeemed =", False) qry.order('-timestamp') return qry class SolutionCityWideLottery(db.Model): schedule_loot_time = db.IntegerProperty() timestamp = db.IntegerProperty() end_timestamp = db.IntegerProperty() winnings = db.TextProperty() x_winners = db.IntegerProperty(indexed=False, default=1) winners = db.ListProperty(users.User, indexed=False) # app_user winners_info = db.TextProperty() # json [ExtendedUserDetailsTO] skip_winners = db.ListProperty(users.User, indexed=False) deleted = db.BooleanProperty(default=False) pending = db.BooleanProperty(default=False) count = db.ListProperty(int, indexed=False) # this will be filled in when the lottery is redeemed app_users = db.ListProperty(users.User, indexed=False) # this will be filled in when the lottery is redeemed @property def key_str(self): return str(self.key()) # TODO communities: refactor to NDB and don't use app_id as parent. # Use service user as parent like other models @property def app_id(self): return self.parent_key().name() @classmethod def create_parent_key(cls, app_id): return db.Key.from_path(u"city_wide_lottery", app_id) @classmethod def load_all(cls, app_id): qry = cls.all().ancestor(cls.create_parent_key(app_id)) qry.filter('deleted =', False) return qry @classmethod def load_pending(cls, app_id): qry = cls.all().ancestor(cls.create_parent_key(app_id)) qry.filter('deleted =', False) qry.filter('pending =', True) qry.order("end_timestamp") return qry.get() class SolutionCityWideLotteryStatistics(db.Model): count = db.ListProperty(int, indexed=False) app_users = db.ListProperty(users.User, indexed=False) @classmethod def create_key(cls, app_id): parent_key = db.Key.from_path(SOLUTION_COMMON, app_id) return db.Key.from_path(cls.kind(), app_id, parent=parent_key) @classmethod def get_by_app_id(cls, app_id): return cls.get(cls.create_key(app_id)) class CustomLoyaltyCard(db.Model): TYPE = u'custom_loyalty_card' # The unknown QR which is used by the enduser custom_qr_content = db.TextProperty(required=True) # The loyalty QR which is created by Rogerthat-backend when coupling the custom loyalty card loyalty_qr_content = db.StringProperty(indexed=False, required=True) creation_time = db.DateTimeProperty(auto_now_add=True, indexed=False) # The email:app_id of the enduser app_user = db.UserProperty(indexed=False, required=True) @classmethod def get_by_url(cls, url): return cls.get(cls.create_key(url)) @classmethod def create_key(cls, url): return db.Key.from_path(cls.kind(), sha256_hex(url)) class CityPostalCodes(db.Model): app_id = db.StringProperty(indexed=False) postal_codes = db.StringListProperty(indexed=False) @classmethod def create_key(cls, app_id): return db.Key.from_path(cls.kind(), app_id)
service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) return cls.all().ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)).order('-year_month')
issue-11374.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{self, Read}; use std::vec; pub struct Container<'a> { reader: &'a mut Read } impl<'a> Container<'a> { pub fn wrap<'s>(reader: &'s mut io::Read) -> Container<'s> { Container { reader: reader } } pub fn read_to(&mut self, vec: &mut [u8]) { self.reader.read(vec); } } pub fn for_stdin<'a>() -> Container<'a>
fn main() { let mut c = for_stdin(); let mut v = Vec::new(); c.read_to(v); //~ ERROR mismatched types }
{ let mut r = io::stdin(); Container::wrap(&mut r as &mut io::Read) }
test_notes.py
import unittest from alertaclient.api import Client class AlertTestCase(unittest.TestCase): def setUp(self): self.client = Client(endpoint='http://api:8080', key='demo-key') def
(self): # add tests here when /notes endpoints are created pass
test_notes
k8s_test.go
// Copyright 2019 Sorint.lab // // 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 driver import ( "bytes" "context" "io/ioutil" "os" "reflect" "testing" "time" "agola.io/agola/internal/testutil" "github.com/gofrs/uuid" ) func TestK8sPod(t *testing.T)
func TestParseGitVersion(t *testing.T) { tests := []struct { gitVersion string out *serverVersion err bool }{ { gitVersion: "v1.8.0", out: &serverVersion{Major: 1, Minor: 8}, }, { gitVersion: "v1.12.0", out: &serverVersion{Major: 1, Minor: 12}, }, { gitVersion: "v1.12.20", out: &serverVersion{Major: 1, Minor: 12}, }, { gitVersion: "v1.12.8-test.10", out: &serverVersion{Major: 1, Minor: 12}, }, { gitVersion: "v1.a", err: true, }, } for _, tt := range tests { t.Run("", func(t *testing.T) { sv, err := parseGitVersion(tt.gitVersion) if tt.err { if err == nil { t.Errorf("expected error, got nil error") } return } if err != nil { t.Errorf("unexpected err: %v", err) return } if !reflect.DeepEqual(sv, tt.out) { t.Errorf("expected %v, got %v", tt.out, sv) } }) } }
{ if os.Getenv("SKIP_K8S_TESTS") == "1" { t.Skip("skipping since env var SKIP_K8S_TESTS is 1") } toolboxPath := os.Getenv("AGOLA_TOOLBOX_PATH") if toolboxPath == "" { t.Fatalf("env var AGOLA_TOOLBOX_PATH is undefined") } log := testutil.NewLogger(t) initImage := "busybox:stable" d, err := NewK8sDriver(log, "executorid01", toolboxPath, initImage, nil) if err != nil { t.Fatalf("unexpected err: %v", err) } ctx := context.Background() if err := d.Setup(ctx); err != nil { t.Fatalf("unexpected err: %v", err) } t.Run("create a pod with one container", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() }) t.Run("execute a command inside a pod", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() var buf bytes.Buffer ce, err := pod.Exec(ctx, &ExecConfig{ Cmd: []string{"ls"}, Stdout: &buf, }) if err != nil { t.Fatalf("unexpected err: %v", err) } code, err := ce.Wait(ctx) if err != nil { t.Fatalf("unexpected err: %v", err) } if code != 0 { t.Fatalf("unexpected exit code: %d", code) } }) t.Run("test pod environment", func(t *testing.T) { env := map[string]string{ "ENV01": "ENVVALUE01", "ENV02": "ENVVALUE02", } pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", Env: env, }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() var buf bytes.Buffer ce, err := pod.Exec(ctx, &ExecConfig{ Cmd: []string{"env"}, Stdout: &buf, Stderr: os.Stdout, }) if err != nil { t.Fatalf("unexpected err: %v", err) } code, err := ce.Wait(ctx) if err != nil { t.Fatalf("unexpected err: %v", err) } if code != 0 { t.Fatalf("unexpected exit code: %d", code) } curEnv, err := testutil.ParseEnvs(bytes.NewReader(buf.Bytes())) if err != nil { t.Fatalf("unexpected err: %v", err) } for n, e := range env { if ce, ok := curEnv[n]; !ok { t.Fatalf("missing env var %s", n) } else { if ce != e { t.Fatalf("different env var %s value, want: %q, got %q", n, e, ce) } } } }) t.Run("create a pod with two containers", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", }, &ContainerConfig{ Image: "nginx:1.16", }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() }) t.Run("test communication between two containers", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", }, &ContainerConfig{ Image: "nginx:1.16", }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() // wait for nginx up time.Sleep(1 * time.Second) var buf bytes.Buffer ce, err := pod.Exec(ctx, &ExecConfig{ Cmd: []string{"nc", "-z", "localhost", "80"}, Stdout: &buf, }) if err != nil { t.Fatalf("unexpected err: %v", err) } code, err := ce.Wait(ctx) if err != nil { t.Fatalf("unexpected err: %v", err) } if code != 0 { t.Fatalf("unexpected exit code: %d", code) } }) t.Run("test get pods", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() pods, err := d.GetPods(ctx, true) if err != nil { t.Fatalf("unexpected err: %v", err) } ok := false for _, p := range pods { if p.ID() == pod.ID() { ok = true } } if !ok { t.Fatalf("pod with id %q not found", pod.ID()) } }) t.Run("test pod with a tmpfs volume", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", Volumes: []Volume{ { Path: "/mnt/tmpfs", TmpFS: &VolumeTmpFS{ Size: 1024 * 1024, }, }, }, }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() var buf bytes.Buffer ce, err := pod.Exec(ctx, &ExecConfig{ // k8s doesn't set size=1024k in the tmpf mount options but uses other modes to detect the size Cmd: []string{"sh", "-c", "if [ $(grep -c /mnt/tmpfs /proc/mounts) -ne 1 ]; then exit 1; fi"}, Stdout: &buf, }) if err != nil { t.Fatalf("unexpected err: %v", err) } code, err := ce.Wait(ctx) if err != nil { t.Fatalf("unexpected err: %v", err) } if code != 0 { t.Fatalf("unexpected exit code: %d", code) } }) t.Run("test pod with two tmpfs volumes", func(t *testing.T) { pod, err := d.NewPod(ctx, &PodConfig{ ID: uuid.Must(uuid.NewV4()).String(), TaskID: uuid.Must(uuid.NewV4()).String(), Containers: []*ContainerConfig{ &ContainerConfig{ Cmd: []string{"cat"}, Image: "busybox", Volumes: []Volume{ { Path: "/mnt/vol1", TmpFS: &VolumeTmpFS{ Size: 1024 * 1024, }, }, { Path: "/mnt/vol2", TmpFS: &VolumeTmpFS{ Size: 1024 * 1024, }, }, }, }, }, InitVolumeDir: "/tmp/agola", }, ioutil.Discard) if err != nil { t.Fatalf("unexpected err: %v", err) } defer func() { _ = pod.Remove(ctx) }() var buf bytes.Buffer ce, err := pod.Exec(ctx, &ExecConfig{ // k8s doesn't set size=1024k in the tmpf mount options but uses other modes to detect the size Cmd: []string{"sh", "-c", "if [ $(grep -c /mnt/vol1 /proc/mounts) -ne 1 -o $(grep -c /mnt/vol2 /proc/mounts) ]; then exit 1; fi"}, Stdout: &buf, }) if err != nil { t.Fatalf("unexpected err: %v", err) } code, err := ce.Wait(ctx) if err != nil { t.Fatalf("unexpected err: %v", err) } if code != 0 { t.Fatalf("unexpected exit code: %d", code) } }) }
sub-category-kb-dialog.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; import { SubCategoryKb } from './sub-category-kb.model'; import { SubCategoryKbPopupService } from './sub-category-kb-popup.service'; import { SubCategoryKbService } from './sub-category-kb.service'; import { CategoryKb, CategoryKbService } from '../category-kb'; import { ProductKb, ProductKbService } from '../product-kb'; @Component({ selector: 'jhi-sub-category-kb-dialog', templateUrl: './sub-category-kb-dialog.component.html' }) export class SubCategoryKbDialogComponent implements OnInit { subCategory: SubCategoryKb; isSaving: boolean; categories: CategoryKb[]; products: ProductKb[]; constructor( public activeModal: NgbActiveModal, private jhiAlertService: JhiAlertService, private subCategoryService: SubCategoryKbService, private categoryService: CategoryKbService, private productService: ProductKbService, private eventManager: JhiEventManager ) { } ngOnInit() { this.isSaving = false; this.categoryService.query() .subscribe((res: HttpResponse<CategoryKb[]>) => { this.categories = res.body; }, (res: HttpErrorResponse) => this.onError(res.message)); this.productService.query() .subscribe((res: HttpResponse<ProductKb[]>) => { this.products = res.body; }, (res: HttpErrorResponse) => this.onError(res.message)); } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; if (this.subCategory.id !== undefined) { this.subscribeToSaveResponse( this.subCategoryService.update(this.subCategory)); } else { this.subscribeToSaveResponse( this.subCategoryService.create(this.subCategory)); } } private subscribeToSaveResponse(result: Observable<HttpResponse<SubCategoryKb>>) { result.subscribe((res: HttpResponse<SubCategoryKb>) => this.onSaveSuccess(res.body), (res: HttpErrorResponse) => this.onSaveError()); } private onSaveSuccess(result: SubCategoryKb) { this.eventManager.broadcast({ name: 'subCategoryListModification', content: 'OK'}); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError() { this.isSaving = false; } private onError(error: any) { this.jhiAlertService.error(error.message, null, null); } trackCategoryById(index: number, item: CategoryKb) { return item.id; } trackProductById(index: number, item: ProductKb) { return item.id; } getSelected(selectedVals: Array<any>, option: any) { if (selectedVals) { for (let i = 0; i < selectedVals.length; i++) { if (option.id === selectedVals[i].id) { return selectedVals[i]; } } } return option; } } @Component({ selector: 'jhi-sub-category-kb-popup', template: '' }) export class
implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private subCategoryPopupService: SubCategoryKbPopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { if ( params['id'] ) { this.subCategoryPopupService .open(SubCategoryKbDialogComponent as Component, params['id']); } else { this.subCategoryPopupService .open(SubCategoryKbDialogComponent as Component); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } }
SubCategoryKbPopupComponent
palindrome-partitioning.js
// Hi, I'm Yanzhan. I'm interested in all kinds of algorithmic problems. Also, I'm fascinated with javascript. If you want to learn more about programming problems and javascript, please visit my Youtube Channel (https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber), Twitter Account (https://twitter.com/YangYanzhan), GitHub Repo (https://github.com/yangyanzhan/code-camp) or HomePage (https://yanzhan.site/). // 开始分析 // 1. 按照要求执行即可。 // 结束分析 // 开始编码 /** * @param {string} s * @return {string[][]} */ var partition = function(s) { var n = s.length; var dp = []; for (var i = 0; i < n; i++) { var row = []; for (var j = 0; j < n; j++) { row.push(false); } dp.push(row); } for (var i = 0; i < n; i++) { dp[i][i] = true; } for (var i = 0; i < n - 1; i++) { dp[i][i + 1] = s[i] == s[i + 1]; } for (var len = 3; len <= n; len++) { for (var i = 0; i + len - 1 <= n - 1; i++) { dp[i][i + len - 1] = s[i] == s[i + len - 1] && dp[i + 1][i + len - 2]; } } var res = []; var path = []; function check(s, i) { if (i >= n) {
res.push([...path]); return; } for (var j = i; j < n; j++) { if (dp[i][j]) { path.push(s.substr(i, j - i + 1)); check(s, j + 1); path.pop(); } } } check(s, 0); return res; };
plugin_manager.go
package restapi import ( "sync" "github.com/labstack/echo/v4" restapipkg "github.com/gohornet/hornet/pkg/restapi" ) type RestPluginManager struct { sync.RWMutex plugins []string proxy *restapipkg.DynamicProxy } func newRestPluginManager(e *echo.Echo) *RestPluginManager
func (p *RestPluginManager) Plugins() []string { p.RLock() defer p.RUnlock() return p.plugins } // AddPlugin adds a plugin route to the RouteInfo endpoint and returns the route for this plugin. func (p *RestPluginManager) AddPlugin(pluginRoute string) *echo.Group { p.Lock() defer p.Unlock() found := false for _, plugin := range p.plugins { if plugin == pluginRoute { found = true break } } if !found { p.plugins = append(p.plugins, pluginRoute) } // existing groups get overwritten (necessary if last plugin was not cleaned up properly) return p.proxy.AddGroup(pluginRoute) } // AddPluginProxy adds a plugin route to the RouteInfo endpoint and configures a remote proxy for this route. func (p *RestPluginManager) AddPluginProxy(pluginRoute string, host string, port uint32) { p.Lock() defer p.Unlock() found := false for _, plugin := range p.plugins { if plugin == pluginRoute { found = true break } } if !found { p.plugins = append(p.plugins, pluginRoute) } // existing proxies get overwritten (necessary if last plugin was not cleaned up properly) p.proxy.AddReverseProxy(pluginRoute, host, port) } // RemovePlugin removes a plugin route to the RouteInfo endpoint. func (p *RestPluginManager) RemovePlugin(pluginRoute string) { p.Lock() defer p.Unlock() newPlugins := make([]string, 0) for _, plugin := range p.plugins { if plugin != pluginRoute { newPlugins = append(newPlugins, plugin) } } p.plugins = newPlugins p.proxy.RemoveReverseProxy(pluginRoute) }
{ return &RestPluginManager{ plugins: []string{}, proxy: restapipkg.NewDynamicProxy(deps.Echo, "/api/plugins"), } }
mod.rs
// Copyright Materialize, Inc. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! Renders a plan into a timely/differential dataflow computation. //! //! ## Error handling //! //! Timely and differential have no idioms for computations that can error. The //! philosophy is, reasonably, to define the semantics of the computation such //! that errors are unnecessary: e.g., by using wrap-around semantics for //! integer overflow. //! //! Unfortunately, SQL semantics are not nearly so elegant, and require errors //! in myriad cases. The classic example is a division by zero, but invalid //! input for casts, overflowing integer operations, and dozens of other //! functions need the ability to produce errors ar runtime. //! //! At the moment, only *scalar* expression evaluation can fail, so only //! operators that evaluate scalar expressions can fail. At the time of writing, //! that includes map, filter, reduce, and join operators. Constants are a bit //! of a special case: they can be either a constant vector of rows *or* a //! constant, singular error. //! //! The approach taken is to build two parallel trees of computation: one for //! the rows that have been successfully evaluated (the "oks tree"), and one for //! the errors that have been generated (the "errs tree"). For example: //! //! ```text //! oks1 errs1 oks2 errs2 //! | | | | //! | | | | //! project | | | //! | | | | //! | | | | //! map | | | //! |\ | | | //! | \ | | | //! | \ | | | //! | \ | | | //! | \| | | //! project + + + //! | | / / //! | | / / //! join ------------+ / //! | | / //! | | +----------+ //! | |/ //! oks errs //! ``` //! //! The project operation cannot fail, so errors from errs1 are propagated //! directly. Map operators are fallible and so can inject additional errors //! into the stream. Join operators combine the errors from each of their //! inputs. //! //! The semantics of the error stream are minimal. From the perspective of SQL, //! a dataflow is considered to be in an error state if there is at least one //! element in the final errs collection. The error value returned to the user //! is selected arbitrarily; SQL only makes provisions to return one error to //! the user at a time. There are plans to make the err collection accessible to //! end users, so they can see all errors at once. //! //! To make errors transient, simply ensure that the operator can retract any //! produced errors when corrected data arrives. To make errors permanent, write //! the operator such that it never retracts the errors it produced. Future work //! will likely want to introduce some sort of sort order for errors, so that //! permanent errors are returned to the user ahead of transient errors—probably //! by introducing a new error type a la: //! //! ```no_run //! # struct EvalError; //! # struct SourceError; //! enum DataflowError { //! Transient(EvalError), //! Permanent(SourceError), //! } //! ``` //! //! If the error stream is empty, the oks stream must be correct. If the error //! stream is non-empty, then there are no semantics for the oks stream. This is //! sufficient to support SQL in its current form, but is likely to be //! unsatisfactory long term. We suspect that we can continue to imbue the oks //! stream with semantics if we are very careful in describing what data should //! and should not be produced upon encountering an error. Roughly speaking, the //! oks stream could represent the correct result of the computation where all //! rows that caused an error have been pruned from the stream. There are //! strange and confusing questions here around foreign keys, though: what if //! the optimizer proves that a particular key must exist in a collection, but //! the key gets pruned away because its row participated in a scalar expression //! evaluation that errored? //! //! In the meantime, it is probably wise for operators to keep the oks stream //! roughly "as correct as possible" even when errors are present in the errs //! stream. This reduces the amount of recomputation that must be performed //! if/when the errors are retracted. use std::collections::{HashMap, HashSet}; use std::iter; use std::rc::Rc; use std::rc::Weak; use std::{any::Any, cell::RefCell}; use differential_dataflow::hashable::Hashable; use differential_dataflow::lattice::Lattice; use differential_dataflow::operators::arrange::arrangement::ArrangeByKey; use differential_dataflow::operators::Consolidate; use differential_dataflow::{AsCollection, Collection}; use timely::communication::Allocate; use timely::dataflow::operators::exchange::Exchange; use timely::dataflow::operators::to_stream::ToStream; use timely::dataflow::operators::unordered_input::UnorderedInput; use timely::dataflow::operators::Map; use timely::dataflow::scopes::Child; use timely::dataflow::Scope; use timely::worker::Worker as TimelyWorker; use tokio::sync::mpsc; use dataflow_types::*; use expr::{GlobalId, Id, MapFilterProject, MirRelationExpr, SourceInstanceId}; use interchange::envelopes::{combine_at_timestamp, dbz_format, upsert_format}; use mz_avro::types::Value; use mz_avro::Schema; use ore::cast::CastFrom; use ore::collections::CollectionExt as _; use ore::iter::IteratorExt; use repr::adt::decimal::Significand; use repr::{Datum, RelationType, Row, RowArena, RowPacker, Timestamp}; use crate::decode::{decode_avro_values, decode_values, get_decoder}; use crate::operator::{CollectionExt, StreamExt}; use crate::render::context::{ArrangementFlavor, Context}; use crate::server::{CacheMessage, LocalInput, TimestampDataUpdates}; use crate::sink; use crate::source::{self, FileSourceInfo, KafkaSourceInfo, KinesisSourceInfo, S3SourceInfo}; use crate::source::{SourceConfig, SourceToken}; use crate::{ arrangement::manager::{TraceBundle, TraceManager}, logging::materialized::Logger, }; mod arrange_by; mod context; pub(crate) mod filter; mod flat_map; mod join; mod reduce; mod threshold; mod top_k; mod upsert; /// Worker-local state used during rendering. pub struct RenderState { /// The traces available for sharing across dataflows. pub traces: TraceManager, /// Handles to local inputs, keyed by ID. pub local_inputs: HashMap<GlobalId, LocalInput>, /// Handles to external sources, keyed by ID. pub ts_source_mapping: HashMap<GlobalId, Vec<Weak<Option<SourceToken>>>>, /// Timestamp data updates for each source. pub ts_histories: TimestampDataUpdates, /// Tokens that should be dropped when a dataflow is dropped to clean up /// associated state. pub dataflow_tokens: HashMap<GlobalId, Box<dyn Any>>, /// Sender to give data to be cached. pub caching_tx: Option<mpsc::UnboundedSender<CacheMessage>>, } /// Build a dataflow from a description. pub fn build_dataflow<A: Allocate>( timely_worker: &mut TimelyWorker<A>, render_state: &mut RenderState, dataflow: DataflowDesc, ) { let worker_logging = timely_worker.log_register().get("timely"); let name = format!("Dataflow: {}", &dataflow.debug_name); let materialized_logging = timely_worker.log_register().get("materialized"); timely_worker.dataflow_core(&name, worker_logging, Box::new(()), |_, scope| { // The scope.clone() occurs to allow import in the region. // We build a region here to establish a pattern of a scope inside the dataflow, // so that other similar uses (e.g. with iterative scopes) do not require weird // alternate type signatures. scope.clone().region(|region| { let mut context = Context::for_dataflow(&dataflow, scope.addr().into_element()); assert!( !dataflow .source_imports .iter() .map(|(id, _src)| id) .has_duplicates(), "computation of unique IDs assumes a source appears no more than once per dataflow" ); // Import declared sources into the rendering context. for (src_id, src) in dataflow.source_imports.clone() { context.import_source( render_state, region, materialized_logging.clone(), src_id, src, ); } // Import declared indexes into the rendering context. for (idx_id, idx) in &dataflow.index_imports { context.import_index(render_state, scope, region, *idx_id, idx); } // Build declared objects. for object in &dataflow.objects_to_build { context.build_object(region, object); } // Export declared indexes. for (idx_id, idx, typ) in &dataflow.index_exports { let imports = dataflow.get_imports(&idx.on_id); context.export_index(render_state, imports, *idx_id, idx, typ); } // Export declared sinks. for (sink_id, sink) in &dataflow.sink_exports { let imports = dataflow.get_imports(&sink.from); context.export_sink(render_state, imports, *sink_id, sink); } }); }) } impl<'g, G> Context<Child<'g, G, G::Timestamp>, MirRelationExpr, Row, Timestamp> where G: Scope<Timestamp = Timestamp>, { fn import_source( &mut self, render_state: &mut RenderState, scope: &mut Child<'g, G, G::Timestamp>, materialized_logging: Option<Logger>, src_id: GlobalId, mut src: SourceDesc, ) { if let Some(operator) = &src.operators { if operator.is_trivial(src.arity()) { src.operators = None; } } match src.connector { SourceConnector::Local => { let ((handle, capability), stream) = scope.new_unordered_input(); render_state .local_inputs .insert(src_id, LocalInput { handle, capability }); let err_collection = Collection::empty(scope); self.collections.insert( MirRelationExpr::global_get(src_id, src.bare_desc.typ().clone()), (stream.as_collection(), err_collection), ); } SourceConnector::External { connector, encoding, envelope,
// This uid must be unique across all different instantiations of a source let uid = SourceInstanceId { source_id: src_id, dataflow_id: self.dataflow_id, }; // TODO(benesch): we force all sources to have an empty // error stream. Likely we will want to plumb this // collection into the source connector so that sources // can produce errors. let mut err_collection = Collection::empty(scope); let fast_forwarded = match &connector { ExternalSourceConnector::Kafka(KafkaSourceConnector { start_offsets, .. }) => start_offsets.values().any(|&val| val > 0), _ => false, }; // All workers are responsible for reading in Kafka sources. Other sources // support single-threaded ingestion only. Note that in all cases we want all // readers of the same source or same partition to reside on the same worker, // and only load-balance responsibility across distinct sources. let active_read_worker = if let ExternalSourceConnector::Kafka(_) = connector { true } else { (usize::cast_from(src_id.hashed()) % scope.peers()) == scope.index() }; let caching_tx = if let (true, Some(caching_tx)) = (connector.caching_enabled(), render_state.caching_tx.clone()) { Some(caching_tx) } else { None }; let source_config = SourceConfig { name: format!("{}-{}", connector.name(), uid), id: uid, scope, // Distribute read responsibility among workers. active: active_read_worker, timestamp_histories: render_state.ts_histories.clone(), consistency, timestamp_frequency: ts_frequency, worker_id: scope.index(), worker_count: scope.peers(), logger: materialized_logging, encoding: encoding.clone(), caching_tx, }; let (stream, capability) = if let ExternalSourceConnector::AvroOcf(_) = connector { let ((source, err_source), capability) = source::create_source::<_, FileSourceInfo<Value>, Value>( source_config, connector, ); err_collection = err_collection.concat( &err_source .map(DataflowError::SourceError) .pass_through("AvroOCF-errors") .as_collection(), ); let reader_schema = match &encoding { DataEncoding::AvroOcf(AvroOcfEncoding { reader_schema }) => reader_schema, _ => unreachable!( "Internal error: \ Avro OCF schema should have already been resolved.\n\ Encoding is: {:?}", encoding ), }; let reader_schema: Schema = reader_schema.parse().unwrap(); ( decode_avro_values(&source, &envelope, reader_schema, &self.debug_name), capability, ) } else if let ExternalSourceConnector::Postgres(_pg_connector) = connector { unimplemented!("Postgres sources are not supported yet"); } else { let ((ok_source, err_source), capability) = match connector { ExternalSourceConnector::Kafka(_) => { source::create_source::<_, KafkaSourceInfo, _>(source_config, connector) } ExternalSourceConnector::Kinesis(_) => { source::create_source::<_, KinesisSourceInfo, _>( source_config, connector, ) } ExternalSourceConnector::S3(_) => { source::create_source::<_, S3SourceInfo, _>(source_config, connector) } ExternalSourceConnector::File(_) => { source::create_source::<_, FileSourceInfo<Vec<u8>>, Vec<u8>>( source_config, connector, ) } ExternalSourceConnector::AvroOcf(_) => unreachable!(), ExternalSourceConnector::Postgres(_) => unreachable!(), }; err_collection = err_collection.concat( &err_source .map(DataflowError::SourceError) .pass_through("source-errors") .as_collection(), ); let stream = if let SourceEnvelope::Upsert(key_encoding) = &envelope { let value_decoder = get_decoder(encoding, &self.debug_name, scope.index()); let key_decoder = get_decoder(key_encoding.clone(), &self.debug_name, scope.index()); upsert::decode_stream( &ok_source, self.as_of_frontier.clone(), key_decoder, value_decoder, ) } else { // TODO(brennan) -- this should just be a MirRelationExpr::FlatMap using regexp_extract, csv_extract, // a hypothetical future avro_extract, protobuf_extract, etc. let (stream, extra_token) = decode_values( &ok_source, encoding, &self.debug_name, &envelope, &mut src.operators, fast_forwarded, src.desc, ); if let Some(tok) = extra_token { self.additional_tokens .entry(src_id) .or_insert_with(Vec::new) .push(Rc::new(tok)); } stream }; (stream, capability) }; let mut collection = stream.as_collection(); // Implement source filtering and projection. // At the moment this is strictly optional, but we perform it anyhow // to demonstrate the intended use. if let Some(mut operators) = src.operators.clone() { // Determine replacement values for unused columns. let source_type = src.bare_desc.typ(); let position_or = (0..source_type.arity()) .map(|col| { if operators.projection.contains(&col) { Some(col) } else { None } }) .collect::<Vec<_>>(); // Apply predicates and insert dummy values into undemanded columns. let (collection2, errors) = collection.inner.flat_map_fallible({ let mut datums = crate::render::datum_vec::DatumVec::new(); let mut row_packer = repr::RowPacker::new(); let predicates = std::mem::take(&mut operators.predicates); // The predicates may be temporal, which requires the nuance // of an explicit plan capable of evaluating the predicates. let filter_plan = filter::FilterPlan::create_from(predicates) .unwrap_or_else(|e| panic!(e)); move |(input_row, time, diff)| { let mut datums_local = datums.borrow_with(&input_row); let times_diffs = filter_plan.evaluate(&mut datums_local, time, diff); // The output row may need to have `Datum::Dummy` values stitched in. let output_row = row_packer.pack(position_or.iter().map(|pos_or| match pos_or { Some(index) => datums_local[*index], None => Datum::Dummy, })); // Each produced (time, diff) results in a copy of `output_row` in the output. // TODO: It would be nice to avoid the `output_row.clone()` for the last output. times_diffs.map(move |time_diff| { time_diff.map(|(t, d)| (output_row.clone(), t, d)) }) } }); collection = collection2.as_collection(); err_collection = err_collection.concat(&errors.as_collection()); }; // Apply `as_of` to each timestamp. match envelope { SourceEnvelope::Upsert(_) => {} _ => { let as_of_frontier1 = self.as_of_frontier.clone(); collection = collection .inner .map_in_place(move |(_, time, _)| { time.advance_by(as_of_frontier1.borrow()) }) .as_collection(); let as_of_frontier2 = self.as_of_frontier.clone(); err_collection = err_collection .inner .map_in_place(move |(_, time, _)| { time.advance_by(as_of_frontier2.borrow()) }) .as_collection(); } } let get = MirRelationExpr::Get { id: Id::BareSource(src_id), typ: src.bare_desc.typ().clone(), }; // Introduce the stream by name, as an unarranged collection. self.collections .insert(get.clone(), (collection, err_collection)); let mut expr = src.optimized_expr.0; expr.visit_mut(&mut |node| { if let MirRelationExpr::Get { id: Id::LocalBareSource, .. } = node { *node = get.clone() } }); // Do whatever envelope processing is required. self.ensure_rendered(&expr, scope, scope.index()); let new_get = MirRelationExpr::global_get(src_id, expr.typ()); self.clone_from_to(&expr, &new_get); let token = Rc::new(capability); self.source_tokens.insert(src_id, token.clone()); // We also need to keep track of this mapping globally to activate sources // on timestamp advancement queries render_state .ts_source_mapping .entry(uid.source_id) .or_insert_with(Vec::new) .push(Rc::downgrade(&token)); } } } fn import_index( &mut self, render_state: &mut RenderState, scope: &mut G, region: &mut Child<'g, G, G::Timestamp>, idx_id: GlobalId, (idx, typ): &(IndexDesc, RelationType), ) { if let Some(traces) = render_state.traces.get_mut(&idx_id) { let token = traces.to_drop().clone(); let (ok_arranged, ok_button) = traces.oks_mut().import_frontier_core( scope, &format!("Index({}, {:?})", idx.on_id, idx.keys), self.as_of_frontier.clone(), ); let (err_arranged, err_button) = traces.errs_mut().import_frontier_core( scope, &format!("ErrIndex({}, {:?})", idx.on_id, idx.keys), self.as_of_frontier.clone(), ); let ok_arranged = ok_arranged.enter(region); let err_arranged = err_arranged.enter(region); let get_expr = MirRelationExpr::global_get(idx.on_id, typ.clone()); self.set_trace(idx_id, &get_expr, &idx.keys, (ok_arranged, err_arranged)); self.additional_tokens .entry(idx_id) .or_insert_with(Vec::new) .push(Rc::new(( ok_button.press_on_drop(), err_button.press_on_drop(), token, ))); } else { panic!( "import of index {} failed while building dataflow {}", idx_id, self.dataflow_id ); } } fn build_object(&mut self, scope: &mut Child<'g, G, G::Timestamp>, object: &BuildDesc) { self.ensure_rendered(object.relation_expr.as_ref(), scope, scope.index()); if let Some(typ) = &object.typ { self.clone_from_to( &object.relation_expr.as_ref(), &MirRelationExpr::global_get(object.id, typ.clone()), ); } else { self.render_arrangeby(&object.relation_expr.as_ref(), Some(&object.id.to_string())); // Under the premise that this is always an arrange_by aroung a global get, // this will leave behind the arrangements bound to the global get, so that // we will not tidy them up in the next pass. } // After building each object, we want to tear down all other cached collections // and arrangements to avoid accidentally providing hits on local identifiers. // We could relax this if we better understood which expressions are dangerous // (e.g. expressions containing gets of local identifiers not covered by a let). // // TODO: Improve collection and arrangement re-use. self.collections.retain(|e, _| { matches!(e, MirRelationExpr::Get { id: Id::Global(_), typ: _, }) }); self.local.retain(|e, _| { matches!(e, MirRelationExpr::Get { id: Id::Global(_), typ: _, }) }); // We do not install in `context.trace`, and can skip deleting things from it. } fn export_index( &mut self, render_state: &mut RenderState, import_ids: HashSet<GlobalId>, idx_id: GlobalId, idx: &IndexDesc, typ: &RelationType, ) { // put together tokens that belong to the export let mut needed_source_tokens = Vec::new(); let mut needed_additional_tokens = Vec::new(); for import_id in import_ids { if let Some(addls) = self.additional_tokens.get(&import_id) { needed_additional_tokens.extend_from_slice(addls); } if let Some(source_token) = self.source_tokens.get(&import_id) { needed_source_tokens.push(source_token.clone()); } } let tokens = Rc::new((needed_source_tokens, needed_additional_tokens)); let get_expr = MirRelationExpr::global_get(idx.on_id, typ.clone()); match self.arrangement(&get_expr, &idx.keys) { Some(ArrangementFlavor::Local(oks, errs)) => { render_state.traces.set( idx_id, TraceBundle::new(oks.trace, errs.trace).with_drop(tokens), ); } Some(ArrangementFlavor::Trace(gid, _, _)) => { // Duplicate of existing arrangement with id `gid`, so // just create another handle to that arrangement. let trace = render_state.traces.get(&gid).unwrap().clone(); render_state.traces.set(idx_id, trace); } None => { panic!("Arrangement alarmingly absent!"); } }; } fn export_sink( &mut self, render_state: &mut RenderState, import_ids: HashSet<GlobalId>, sink_id: GlobalId, sink: &SinkDesc, ) { // put together tokens that belong to the export let mut needed_source_tokens = Vec::new(); let mut needed_additional_tokens = Vec::new(); let mut needed_sink_tokens = Vec::new(); for import_id in import_ids { if let Some(addls) = self.additional_tokens.get(&import_id) { needed_additional_tokens.extend_from_slice(addls); } if let Some(source_token) = self.source_tokens.get(&import_id) { needed_source_tokens.push(source_token.clone()); } } let (collection, _err_collection) = self .collection(&MirRelationExpr::global_get( sink.from, sink.from_desc.typ().clone(), )) .expect("Sink source collection not loaded"); // Some connectors support keys - extract them. let key_indices = sink .connector .get_key_indices() .map(|key_indices| key_indices.to_vec()); let keyed = collection.map(move |row| { let key = key_indices.as_ref().map(|key_indices| { // TODO[perf] (btv) - is there a way to avoid unpacking and repacking every row and cloning the datums? // Does it matter? let datums = row.unpack(); Row::pack(key_indices.iter().map(|&idx| datums[idx].clone())) }); (key, row) }); // Each partition needs to be handled by its own worker, so that we can write messages in order. // For now, we only support single-partition sinks. let keyed = keyed .inner .exchange(move |_| sink_id.hashed()) .as_collection(); // Apply the envelope. // * "Debezium" consolidates the stream, sorts it by time, and produces DiffPairs from it. // It then renders those as Avro. // * Upsert" does the same, except at the last step, it renders the diff pair in upsert format. // (As part of doing so, it asserts that there are not multiple conflicting values at the same timestamp) // * "Tail" writes some metadata. let collection = match sink.envelope { SinkEnvelope::Debezium => { let combined = combine_at_timestamp(keyed.arrange_by_key().stream); // This has to be an `Rc<RefCell<...>>` because the inner closure (passed to `Iterator::map`) references it, and it might outlive the outer closure. let rp = Rc::new(RefCell::new(RowPacker::new())); let collection = combined.flat_map(move |(mut k, v)| { let max_idx = v.len() - 1; let rp = rp.clone(); v.into_iter().enumerate().map(move |(idx, dp)| { let k = if idx == max_idx { k.take() } else { k.clone() }; (k, Some(dbz_format(&mut *rp.borrow_mut(), dp))) }) }); collection } SinkEnvelope::Upsert => { let combined = combine_at_timestamp(keyed.arrange_by_key().stream); let collection = combined.map(|(k, v)| { let v = upsert_format(v); (k, v) }); collection } SinkEnvelope::Tail { emit_progress } => keyed .consolidate() .inner .map({ let mut rp = RowPacker::new(); move |((k, v), time, diff)| { rp.push(Datum::Decimal(Significand::new(i128::from(time)))); if emit_progress { rp.push(Datum::False); } rp.push(Datum::Int64(i64::cast_from(diff))); rp.extend_by_row(&v); let v = rp.finish_and_reuse(); ((k, Some(v)), time, 1) } }) .as_collection(), }; // Some sinks require that the timestamp be appended to the end of the value. let append_timestamp = match &sink.connector { SinkConnector::Kafka(c) => c.consistency.is_some(), SinkConnector::Tail(_) => false, SinkConnector::AvroOcf(_) => false, }; let collection = if append_timestamp { collection .inner .map(|((k, v), t, diff)| { let v = v.map(|v| { let mut rp = RowPacker::new(); rp.extend_by_row(&v); let t = t.to_string(); rp.push_list_with(|rp| { rp.push(Datum::String(&t)); }); rp.finish() }); ((k, v), t, diff) }) .as_collection() } else { collection }; // TODO(benesch): errors should stream out through the sink, // if we figure out a protocol for that. match sink.connector.clone() { SinkConnector::Kafka(c) => { let token = sink::kafka( collection, sink_id, c, sink.key_desc.clone(), sink.value_desc.clone(), ); needed_sink_tokens.push(token); } SinkConnector::Tail(c) => { let batches = collection .map(move |(k, v)| { assert!(k.is_none(), "tail does not support keys"); let v = v.expect("tail must have values"); (sink_id, v) }) .arrange_by_key() .stream; sink::tail(batches, sink_id, c); } SinkConnector::AvroOcf(c) => { sink::avro_ocf(collection, sink_id, c, sink.value_desc.clone()); } }; let tokens = Rc::new(( needed_sink_tokens, needed_source_tokens, needed_additional_tokens, )); render_state .dataflow_tokens .insert(sink_id, Box::new(tokens)); } } impl<G> Context<G, MirRelationExpr, Row, Timestamp> where G: Scope<Timestamp = Timestamp>, { /// Attempt to render a chain of map/filter/project operators on top of another operator. /// /// Returns true if it was successful, and false otherwise. If this method returns false, /// we should continue with the traditional individual render implementations of each /// operator. fn try_render_map_filter_project( &mut self, relation_expr: &MirRelationExpr, scope: &mut G, worker_index: usize, ) -> bool { // Extract a MapFilterProject and residual from `relation_expr`. let (mut mfp, input) = MapFilterProject::extract_from_expression(relation_expr); mfp.optimize(); match input { MirRelationExpr::Get { .. } => { // TODO: determine if `mfp` is no-op to simplify implementation. let mfp2 = mfp.clone(); self.ensure_rendered(&input, scope, worker_index); let (ok_collection, mut err_collection) = self .flat_map_ref(&input, move |exprs| mfp2.literal_constraints(exprs), { let mut row_packer = repr::RowPacker::new(); let mut datums = vec![]; move |row| { let pack_result = { let temp_storage = RowArena::new(); let mut datums_local = std::mem::take(&mut datums); datums_local.extend(row.iter()); // Temporary assignment looks weird, but seems needed to convince // Rust that the lifetime of `evaluate_iter` does not escape. let result = match mfp.evaluate_iter(&mut datums_local, &temp_storage) { Ok(Some(iter)) => { row_packer.clear(); row_packer.extend(iter); Some(Ok(())) } Ok(None) => None, Err(e) => Some(Err(e.into())), }; datums = ore::vec::repurpose_allocation(datums_local); result }; // Re-use the input `row` if at all possible. pack_result.map(|res| { res.map(|()| match row { timely::communication::message::RefOrMut::Ref(_) => { row_packer.finish_and_reuse() } timely::communication::message::RefOrMut::Mut(r) => { row_packer.finish_into(r); std::mem::take(r) } }) }) } }) .unwrap(); use timely::dataflow::operators::ok_err::OkErr; let (oks, errors) = ok_collection.inner.ok_err(|(x, t, d)| match x { Ok(x) => Ok((x, t, d)), Err(x) => Err((x, t, d)), }); err_collection = err_collection.concat(&errors.as_collection()); self.collections .insert(relation_expr.clone(), (oks.as_collection(), err_collection)); true } MirRelationExpr::FlatMap { input: input2, .. } => { self.ensure_rendered(&input2, scope, worker_index); let (oks, err) = self.render_flat_map(input, Some(mfp)); self.collections.insert(relation_expr.clone(), (oks, err)); true } MirRelationExpr::Join { inputs, implementation, .. } => { for input in inputs { self.ensure_rendered(input, scope, worker_index); } match implementation { expr::JoinImplementation::Differential(_start, _order) => { let collection = self.render_join(input, mfp, scope); self.collections.insert(relation_expr.clone(), collection); } expr::JoinImplementation::DeltaQuery(_orders) => { let collection = self.render_delta_join(input, mfp, scope, worker_index, |t| { t.saturating_sub(1) }); self.collections.insert(relation_expr.clone(), collection); } expr::JoinImplementation::Unimplemented => { panic!("Attempt to render unimplemented join"); } } true } _ => false, } } /// Ensures the context contains an entry for `relation_expr`. /// /// This method may construct new dataflow elements and register then in the context, /// and is only obliged to ensure that a call to `self.collection(relation_expr)` will /// result in a non-`None` result. This may be a raw collection or an arrangement by /// any set of keys. /// /// The rough structure of the logic for each expression is to ensure that any input /// collections are rendered, pub fn ensure_rendered( &mut self, relation_expr: &MirRelationExpr, scope: &mut G, worker_index: usize, ) { if !self.has_collection(relation_expr) { // Each of the `MirRelationExpr` variants have logic to render themselves to either // a collection or an arrangement. In either case, we associate the result with // the `relation_expr` argument in the context. match relation_expr { // The constant collection is instantiated only on worker zero. MirRelationExpr::Constant { rows, .. } => { // Determine what this worker will contribute. let locally = if worker_index == 0 { rows.clone() } else { Ok(vec![]) }; // Produce both rows and errs to avoid conditional dataflow construction. let (rows, errs) = match locally { Ok(rows) => (rows, Vec::new()), Err(e) => (Vec::new(), vec![e]), }; let ok_collection = rows .into_iter() .map(|(x, diff)| (x, timely::progress::Timestamp::minimum(), diff)) .to_stream(scope) .as_collection(); let err_collection = errs .into_iter() .map(|e| { ( DataflowError::from(e), timely::progress::Timestamp::minimum(), 1, ) }) .to_stream(scope) .as_collection(); self.collections .insert(relation_expr.clone(), (ok_collection, err_collection)); } // A get should have been loaded into the context, and it is surprising to // reach this point given the `has_collection()` guard at the top of the method. MirRelationExpr::Get { id, typ } => { // TODO: something more tasteful. // perhaps load an empty collection, warn? panic!("Collection {} (typ: {:?}) not pre-loaded", id, typ); } MirRelationExpr::Let { id, value, body } => { let typ = value.typ(); let bind = MirRelationExpr::Get { id: Id::Local(*id), typ, }; if self.has_collection(&bind) { panic!("Inappropriate to re-bind name: {:?}", bind); } else { self.ensure_rendered(value, scope, worker_index); self.clone_from_to(value, &bind); self.ensure_rendered(body, scope, worker_index); self.clone_from_to(body, relation_expr); } } MirRelationExpr::Project { input, outputs } => { if !self.try_render_map_filter_project(relation_expr, scope, worker_index) { self.ensure_rendered(input, scope, worker_index); let outputs = outputs.clone(); let (ok_collection, err_collection) = self.collection(input).unwrap(); let ok_collection = ok_collection.map({ let mut row_packer = repr::RowPacker::new(); move |row| { let datums = row.unpack(); row_packer.pack(outputs.iter().map(|i| datums[*i])) } }); self.collections .insert(relation_expr.clone(), (ok_collection, err_collection)); } } MirRelationExpr::Map { input, scalars } => { if !self.try_render_map_filter_project(relation_expr, scope, worker_index) { self.ensure_rendered(input, scope, worker_index); let scalars = scalars.clone(); let (ok_collection, err_collection) = self.collection(input).unwrap(); let (ok_collection, new_err_collection) = ok_collection.map_fallible({ let mut row_packer = repr::RowPacker::new(); move |input_row| { let mut datums = input_row.unpack(); let temp_storage = RowArena::new(); for scalar in &scalars { let datum = scalar.eval(&datums, &temp_storage)?; // Scalar is allowed to see the outputs of previous scalars. // To avoid repeatedly unpacking input_row, we just push the outputs into datums so later scalars can see them. // Note that this doesn't mutate input_row. datums.push(datum); } Ok::<_, DataflowError>(row_packer.pack(&*datums)) } }); let err_collection = err_collection.concat(&new_err_collection); self.collections .insert(relation_expr.clone(), (ok_collection, err_collection)); } } MirRelationExpr::FlatMap { input, .. } => { self.ensure_rendered(input, scope, worker_index); let (oks, err) = self.render_flat_map(relation_expr, None); self.collections.insert(relation_expr.clone(), (oks, err)); } MirRelationExpr::Filter { input, .. } => { if !self.try_render_map_filter_project(relation_expr, scope, worker_index) { self.ensure_rendered(input, scope, worker_index); let collections = self.render_filter(relation_expr); self.collections.insert(relation_expr.clone(), collections); } } MirRelationExpr::Join { inputs, implementation, .. } => { for input in inputs { self.ensure_rendered(input, scope, worker_index); } let input_mapper = expr::JoinInputMapper::new(inputs); let mfp = MapFilterProject::new(input_mapper.total_columns()); match implementation { expr::JoinImplementation::Differential(_start, _order) => { let collection = self.render_join(relation_expr, mfp, scope); self.collections.insert(relation_expr.clone(), collection); } expr::JoinImplementation::DeltaQuery(_orders) => { let collection = self.render_delta_join( relation_expr, mfp, scope, worker_index, |t| t.saturating_sub(1), ); self.collections.insert(relation_expr.clone(), collection); } expr::JoinImplementation::Unimplemented => { panic!("Attempt to render unimplemented join"); } } } MirRelationExpr::Reduce { input, .. } => { self.ensure_rendered(input, scope, worker_index); self.render_reduce(relation_expr); } MirRelationExpr::TopK { input, .. } => { self.ensure_rendered(input, scope, worker_index); self.render_topk(relation_expr); } MirRelationExpr::Negate { input } => { self.ensure_rendered(input, scope, worker_index); let (ok_collection, err_collection) = self.collection(input).unwrap(); let ok_collection = ok_collection.negate(); self.collections .insert(relation_expr.clone(), (ok_collection, err_collection)); } MirRelationExpr::Threshold { input } => { self.ensure_rendered(input, scope, worker_index); self.render_threshold(relation_expr); } MirRelationExpr::Union { base, inputs } => { let (oks, errs): (Vec<_>, Vec<_>) = iter::once(&**base) .chain(inputs) .map(|input| { self.ensure_rendered(input, scope, worker_index); self.collection(input).unwrap() }) .unzip(); let ok = differential_dataflow::collection::concatenate(scope, oks); let err = differential_dataflow::collection::concatenate(scope, errs); self.collections.insert(relation_expr.clone(), (ok, err)); } MirRelationExpr::ArrangeBy { input, keys } => { // We can avoid rendering if we have all arrangements present, // and there is at least one of them (to ensure the collection // is available independent of arrangements). if keys.is_empty() || keys .iter() .any(|key| self.arrangement(&input, key).is_none()) { self.ensure_rendered(input, scope, worker_index); } self.render_arrangeby(relation_expr, None); } MirRelationExpr::DeclareKeys { input, keys: _ } => { // TODO - some kind of debug mode where we assert that the keys are truly keys? self.ensure_rendered(input, scope, worker_index); self.clone_from_to(input, relation_expr); } }; } } } /// A re-useable vector of `Datum` with varying lifetimes. /// /// This type is meant to allow us to recycle an underlying allocation with /// a specific lifetime, under the condition that the vector is emptied before /// this happens (to prevent leaking of invalid references). /// /// It uses `ore::vec::repurpose_allocation` to accomplish this, which contains /// unsafe code. pub mod datum_vec { use repr::{Datum, Row}; /// A re-useable vector of `Datum` with no particular lifetime. pub struct DatumVec { outer: Vec<Datum<'static>>, } impl DatumVec { /// Allocate a new instance. pub fn new() -> Self { Self { outer: Vec::new() } } /// Borrow an instance with a specific lifetime. /// /// When the result is dropped, its allocation will be returned to `self`. pub fn borrow<'a>(&'a mut self) -> DatumVecBorrow<'a> { let inner = std::mem::take(&mut self.outer); DatumVecBorrow { outer: &mut self.outer, inner, } } /// Borrow an instance with a specific lifetime, and pre-populate with a `Row`. pub fn borrow_with<'a>(&'a mut self, row: &'a Row) -> DatumVecBorrow<'a> { let mut borrow = self.borrow(); borrow.extend(row.iter()); borrow } } /// A borrowed allocation of `Datum` with a specific lifetime. /// /// When an instance is dropped, its allocation is returned to the vector from /// which it was extracted. pub struct DatumVecBorrow<'outer> { outer: &'outer mut Vec<Datum<'static>>, inner: Vec<Datum<'outer>>, } impl<'outer> Drop for DatumVecBorrow<'outer> { fn drop(&mut self) { *self.outer = ore::vec::repurpose_allocation(std::mem::take(&mut self.inner)); } } impl<'outer> std::ops::Deref for DatumVecBorrow<'outer> { type Target = Vec<Datum<'outer>>; fn deref(&self) -> &Self::Target { &self.inner } } impl<'outer> std::ops::DerefMut for DatumVecBorrow<'outer> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } }
consistency, ts_frequency, } => { // TODO(benesch): this match arm is hard to follow. Refactor.
dumpsgy.py
#!/usr/bin/env pnpython3 # # Simple program to read and display SEG-Y file # # Steve Azevedo # import argparse import logging import os from ph5.core import segy_h, ibmfloat, ebcdic import construct PROG_VERSION = '2019.14' LOGGER = logging.getLogger(__name__) SAMPLE_LENGTH = {1: 4, 2: 4, 3: 2, 4: 4, 5: 4, 8: 1} SIZEOF = {"lineSeq": 32, "reelSeq": 32, "event_number": 32, "channel_number": 32, "energySourcePt": 32, "cdpEns": 32, "traceInEnsemble": 32, "traceID": 16, "vertSum": 16, "horSum": 16, "dataUse": 16, "sourceToRecDist": 32, "recElevation": 32, "sourceSurfaceElevation": 32, "sourceDepth": 32, "datumElevRec": 32, "datumElevSource": 32, "sourceWaterDepth": 32, "recWaterDepth": 32, "elevationScale": 16, "coordScale": 16, "sourceLongOrX": 32, "sourceLatOrY": 32, "recLongOrX": 32, "recLatOrY": 32, "coordUnits": 16, "weatheringVelocity": 16, "subWeatheringVelocity": 16, "sourceUpholeTime": 16, "recUpholeTime": 16, "sourceStaticCor": 16, "recStaticCor": 16, "totalStatic": 16, "lagTimeA": 16, "lagTimeB": 16, "delay": 16, "muteStart": 16, "muteEnd": 16, "sampleLength": 16, "deltaSample": 16, "gainType": 16, "gainConst": 16, "initialGain": 16, "correlated": 16, "sweepStart": 16, "sweepEnd": 16, "sweepLength": 16, "sweepType": 16, "sweepTaperAtStart": 16, "sweepTaperAtEnd": 16, "taperType": 16, "aliasFreq": 16, "aliasSlope": 16, "notchFreq": 16, "notchSlope": 16, "lowCutFreq": 16, "hiCutFreq": 16, "lowCutSlope": 16, "hiCutSlope": 16, "year": 16, "day": 16, "hour": 16, "minute": 16, "second": 16, "timeBasisCode": 16, "traceWeightingFactor": 16, "phoneRollPos1": 16, "phoneFirstTrace": 16, "phoneLastTrace": 16, "gapSize": 16, "taperOvertravel": 16, "station_name": 48, "sensor_serial": 64, "channel_name": 16, "totalStaticHi": 16, "samp_rate": 32, "data_form": 16, "m_secs": 16, "trigyear": 16, "trigday": 16, "trighour": 16, "trigminute": 16, "trigsecond": 16, "trigmills": 16, "scale_fac": 32, "inst_no": 16, "unassigned": 16, "num_samps": 32, "max": 32, "min": 32, "start_usec": 32, "shot_size": 16, "shot_year": 16, "shot_doy": 16, "shot_hour": 16, "shot_minute": 16, "shot_second": 16, "shot_us": 32, "si_override": 32, "sensor_azimuth": 16, "sensor_inclination": 16, "lmo_ms": 32, "lmo_flag": 16, "inst_type": 16, "correction": 16, "azimuth": 16, "sensor_type": 16, "sensor_sn": 16, "das_sn": 16, "empty1": 16, "samples": 32, "empty2": 32, "clock_drift": 16, "empty3": 16, "waterDelay": 32, "startMute": 32, "endMute": 32, "sampleInt": 32, "waterBottomTime": 32, "endOfRp": 32, "dummy1": 32, "dummy2": 32, "dummy3": 32, "dummy4": 32, "dummy5": 32, "dummy6": 32, "dummy7": 32, "dummy8": 32, "dummy9": 32, "Xcoor": 32, "Ycoor": 32, "Inn": 32, "Cnn": 32, "Spn": 32, "Scal": 16, "Tvmu": 16, "Tucmant": 32, "Tucexp": 16, "Tdu": 16, "Dti": 16, "Tscaler": 16, "Sto": 16, "Sed": 48, "Smsmant": 32, "Smsexp": 16, "Smu": 16, "num_samps": 32, "samp_rate": 32, "Revision": 16, "ShotID": 32, "AuxChanSig": 8, "AuxChanID": 8, "SPL": 32, "SPS": 32, "unass01": 16, "unass02": 16, "SenInt": 8, "VectSens": 8, "HorAz": 16, "VertAngle": 16, "SourceType": 8, "SensorType": 8, "AuxChanSetType": 8, "NoiseEditType": 8, "NoiseEditGate": 16, "SystemDevice": 8, "FSU": 3, "DevChan": 8, "SourceCoCo": 8, "DevStatusBits": 8, "BITTest": 8, "SweepPhaseRot": 16, "unass03": 8, "BoxFun": 8, "SourceEffortM": 32, "SourceEffortE": 16, "SourceUnits": 16, "EventType": 8, "SensorTypeID": 8, "SensorSerial": 3, "SensorVersion": 8, "SensorRev": 8, "VOR": 8, } def get_args(): global FH, TYPE, PRINT, L, T, F, ENDIAN, EBCDIC FH = None TYPE = None PRINT = False L = None T = None F = None parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.usage = "Version: {0} Usage: dumpsgy [options]".format( PROG_VERSION) parser.add_argument("-f", action="store", dest="infile", type=str, required=True) parser.add_argument("-t", action="store", dest="ttype", choices=['U', 'P', 'S', 'N', 'I'], help=("Extended trace header style. U => USGS Menlo, " "P => PASSCAL, S => SEG, I => SIOSEIS, " "N => iNova FireFly"), default='S') parser.add_argument("-p", action="store_true", dest="print_true", default=False) parser.add_argument("-L", action="store", dest="bytes_per_trace", type=int) parser.add_argument("-T", action="store", dest="traces_per_ensemble", type=int) parser.add_argument("-F", action="store", dest="trace_format", type=int, help=("1 = IBM - 4 bytes, 2 = INT - 4 bytes, " "3 = INT - 2 bytes, 5 = IEEE - 4 bytes, " "8 = INT - 1 byte")) parser.add_argument("-e", action="store", dest="endian", type=str, default='big', help="Endianess: 'big' or 'little'. Default = 'big'") parser.add_argument("-i", action="store_false", dest="ebcdic", default=True, help="EBCDIC textural header.") args = parser.parse_args() FH = open(args.infile, 'rb') TYPE = args.ttype PRINT = args.print_true L = args.bytes_per_trace T = args.traces_per_ensemble F = args.trace_format ENDIAN = args.endian EBCDIC = args.ebcdic def read_text_header(): buf = FH.read(3200) t = segy_h.Text() return t.parse(buf) def last_extended_header(container): ''' Return True if this contains an EndText stanza? ''' import re lastRE = re.compile(r".*\(\(.*SEG\:.*[Ee][Nn][Dd][Tt][Ee][Xx][Tt].*\)\).*") keys = segy_h.Text().__keys__ for k in keys: what = "container.{0}".format(k) if EBCDIC: t = ebcdic.EbcdicToAscii(eval(what)) else: t = eval(what) if lastRE.match(t): return True return False def print_text_header(container): global TYPE keys = segy_h.Text().__keys__ print "--------------- Textural Header ---------------" for k in keys: what = "container.{0}".format(k) if EBCDIC: print "{0}\t-\t{1:s}".format(k, ebcdic.EbcdicToAscii(eval(what))) else: print "{0}\t-\t{1:s}".format(k, eval(what)) if TYPE is None: if k == '_38_': try: if EBCDIC: s = ebcdic.EbcdicToAscii(eval(what)) else: s = eval(what) try: flds = s.split() if flds[1] == 'MENLO': TYPE = 'U' elif flds[1] == 'PASSCAL': TYPE = 'P' elif flds[1] == 'SEG': TYPE = 'S' elif flds[1] == 'SIOSEIS': TYPE = 'I' else: TYPE = 'S' except BaseException: pass except BaseException: TYPE = 'P' def read_binary_header(): buf = FH.read(400) b = segy_h.Reel(ENDIAN) ret = None try: ret = b.parse(buf) except Exception as e: LOGGER.error(e) return ret def print_binary_header(container): if not container: return keys = segy_h.Reel().__keys__ print "---------- Binary Header ----------" for k in keys: what = "container.{0}".format(k) print "{0:<20}\t---\t{1}".format(k, eval(what)) def read_trace_header():
def print_trace_header(container): keys = segy_h.Trace().__keys__ tt = 0 print "---------- Trace Header ----------" for k in keys: what = "container.{0}".format(k) try: if tt == 9999: raise s = SIZEOF[k] / 8 foffset = "{0:<3} - {1:>3}".format(tt, tt + s - 1) tt += s except BaseException: tt = 9999 foffset = "{0:<3} - {1:>3}".format('_', '_') print "{2} {0:<20}\t---\t{1}".format(k, eval(what), foffset) def read_extended_header(): buf = FH.read(60) if TYPE == 'U': e = segy_h.Menlo(ENDIAN) elif TYPE == 'S': e = segy_h.Seg(ENDIAN) elif TYPE == 'P': e = segy_h.Passcal(ENDIAN) elif TYPE == 'I': e = segy_h.Sioseis(ENDIAN) elif TYPE == 'N': e = segy_h.iNova(ENDIAN) else: return None return e.parse(buf) def print_extended_header(container): if TYPE == 'U': keys = segy_h.Menlo().__keys__ elif TYPE == 'S': keys = segy_h.Seg().__keys__ elif TYPE == 'P': keys = segy_h.Passcal().__keys__ elif TYPE == 'I': keys = segy_h.Sioseis().__keys__ elif TYPE == 'N': keys = segy_h.iNova().__keys__ else: return None tt = 180 print "---------- Extended Header ----------" for k in keys: what = "container.{0}".format(k) try: if tt == 9999: raise s = SIZEOF[k] / 8 if s < 1: raise foffset = "{0:<3} - {1:>3}".format(tt, tt + s - 1) tt += s except BaseException: tt = 9999 foffset = "{0:<3} - {1:>3}".format('_', '_') print "{2} {0:<20}\t---\t{1}".format(k, eval(what), foffset) def read_trace(n, l, f=5): ret = [] if PRINT is True: for i in range(n): buf = FH.read(l) # IBM floats - 4 byte - Must be big endian if f == 1: ret.append(construct.BFloat32( "x").parse(ibmfloat.ibm2ieee32(buf))) # INT - 4 byte or 2 byte elif f == 2: if ENDIAN == 'little': # Swap 4 byte b = construct.SLInt32("x").parse(buf) else: b = construct.SBInt32("x").parse(buf) ret.append(b) elif f == 3: if ENDIAN == 'little': # Swap 2 byte b = construct.SLInt16("x").parse(buf) else: b = construct.SBInt16("x").parse(buf) ret.append(b) # IEEE floats - 4 byte elif f == 5: if ENDIAN == 'little': # Swap 4 byte b = construct.LFloat32("x").parse(buf) else: b = construct.BFloat32("x").parse(buf) ret.append(b) # INT - 1 byte elif f == 8: ret.append(construct.SBInt8("x").parse(buf)) else: FH.read(n * l) return ret def isEOF(): try: n = FH.read(240) if n != 240: raise EOFError FH.seek(-240, os.SEEK_CUR) return False except EOFError: return True def main(): global L, F, T get_args() text_container = read_text_header() print_text_header(text_container) binary_container = read_binary_header() print_binary_header(binary_container) if binary_container: # Number of Extended Textural Headers nt = binary_container.extxt # Samples per trace n = binary_container.hns # Trace sample format if F is None: F = binary_container.format # Bytes per sample try: ll = SAMPLE_LENGTH[binary_container.format] except KeyError: ll = 4 # Bytes per trace if L is None: L = ll * n else: n = int(L) / ll # Traces per record if T is None: T = binary_container.ntrpr else: T = 1 n = ll = F = 0 # Print Extended Textural Headers if nt > 0: for x in range(nt): text_container = read_text_header() print_text_header(text_container) elif nt == -1: while True: text_container = read_text_header() print_text_header(text_container) if last_extended_header(text_container): break while True: for t in range(T): trace_container = read_trace_header() extended_header = read_extended_header() # print t, print_trace_header(trace_container) print_extended_header(extended_header) trace = read_trace(n, ll, F) if trace: print '------------------------' for t in trace: print t if isEOF(): break if __name__ == "__main__": main()
buf = FH.read(180) t = segy_h.Trace(ENDIAN) return t.parse(buf)
ssh.js
const {spawn} = require('child_process'); let reBuilding = false; let reBuildCode = 0; let reBuildData = ''; let waitReBuild = false; const cmdStr = 'cd ./public/home && npm install --registry=https://registry.npm.taobao.org/ && npm run export-cb && cd ../m && npm install --registry=https://registry.npm.taobao.org/ && npm run export-cb'; // const cmdStr = 'cd ../home && npm install && npm run export-cb'; const reBuildHome = () => { console.log(reBuilding); if(reBuilding){ // return new Promise((resolve) => { // const interval = setInterval(() => { // if(!reBuilding){ // clearInterval(interval); // if(reBuildCode !== 0){ // resolve({success: false, code: reBuildCode, error: '异常退出'}); // } // resolve({success: true, code: reBuildCode}); // }
// }) if(!waitReBuild){ waitReBuild = true; const interval = setInterval(() => { if(waitReBuild){ console.log(waitReBuild); reBuildHome(); }else{ clearInterval(interval); } }, 1000); } }else{ waitReBuild = false; reBuilding = true; reBuildData = ''; const reBuildHomeSpawn = spawn(cmdStr, [], {shell: true}); return new Promise((resolve) => { reBuildHomeSpawn.stdout.on('data', (data) => { console.log(`stdout: ${data}`); reBuildData += data.toString(); }); reBuildHomeSpawn.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); reBuildHomeSpawn.on('close', (code) => { console.log(`子进程退出,退出码 ${code}`); reBuildCode = code; reBuilding = false; // if(code !== 0){ // resolve({success: false, code, error: '异常退出'}); // } // resolve({success: true, code}); }); }) } } const getReBuildHomeStatus = () => { return {success: true, reBuilding, reBuildCode, reBuildData}; } module.exports = { reBuildHome, getReBuildHomeStatus }
// }, 5000);
waker_ref.rs
use super::arc_wake::ArcWake; use super::waker::waker_vtable; use alloc::sync::Arc; use core::marker::PhantomData; use core::mem::ManuallyDrop; use core::ops::Deref; use core::task::{RawWaker, Waker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`](std::ops::Deref), /// so it can be used to get a `&Waker`. #[derive(Debug)] pub struct WakerRef<'a> { waker: ManuallyDrop<Waker>, _marker: PhantomData<&'a ()>, } impl<'a> WakerRef<'a> { /// Create a new [`WakerRef`] from a [`Waker`] reference. pub fn
(waker: &'a Waker) -> Self { // copy the underlying (raw) waker without calling a clone, // as we won't call Waker::drop either. let waker = ManuallyDrop::new(unsafe { core::ptr::read(waker) }); Self { waker, _marker: PhantomData } } /// Create a new [`WakerRef`] from a [`Waker`] that must not be dropped. /// /// Note: this if for rare cases where the caller created a [`Waker`] in /// an unsafe way (that will be valid only for a lifetime to be determined /// by the caller), and the [`Waker`] doesn't need to or must not be /// destroyed. pub fn new_unowned(waker: ManuallyDrop<Waker>) -> Self { Self { waker, _marker: PhantomData } } } impl Deref for WakerRef<'_> { type Target = Waker; fn deref(&self) -> &Waker { &self.waker } } /// Creates a reference to a [`Waker`] from a reference to `Arc<impl ArcWake>`. /// /// The resulting [`Waker`] will call /// [`ArcWake.wake()`](ArcWake::wake) if awoken. #[inline] pub fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_> where W: ArcWake, { // simply copy the pointer instead of using Arc::into_raw, // as we don't actually keep a refcount by using ManuallyDrop.< let ptr = (&**wake as *const W) as *const (); let waker = ManuallyDrop::new(unsafe { Waker::from_raw(RawWaker::new(ptr, waker_vtable::<W>())) }); WakerRef::new_unowned(waker) }
new
error.rs
//! Traits for working with Errors. #![stable(feature = "rust1", since = "1.0.0")] // A note about crates and the facade: // // Originally, the `Error` trait was defined in libcore, and the impls // were scattered about. However, coherence objected to this // arrangement, because to create the blanket impls for `Box` required // knowing that `&str: !Error`, and we have no means to deal with that // sort of conflict just now. Therefore, for the time being, we have // moved the `Error` trait into libstd. As we evolve a sol'n to the // coherence challenge (e.g., specialization, neg impls, etc) we can // reconsider what crate these items belong in. use alloc::{AllocErr, LayoutErr, CannotReallocInPlace}; use any::TypeId; use borrow::Cow; use cell; use char; use core::array; use fmt::{self, Debug, Display}; use mem::transmute; use num; use str; use string; /// `Error` is a trait representing the basic expectations for error values, /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe /// themselves through the [`Display`] and [`Debug`] traits, and may provide /// cause chain information: /// /// The [`source`] method is generally used when errors cross "abstraction /// boundaries". If one module must report an error that is caused by an error /// from a lower-level module, it can allow access to that error via the /// [`source`] method. This makes it possible for the high-level module to /// provide its own errors while also revealing some of the implementation for /// debugging via [`source`] chains. /// /// [`Result<T, E>`]: ../result/enum.Result.html /// [`Display`]: ../fmt/trait.Display.html /// [`Debug`]: ../fmt/trait.Debug.html /// [`source`]: trait.Error.html#method.source #[stable(feature = "rust1", since = "1.0.0")] pub trait Error: Debug + Display { /// **This method is soft-deprecated.** /// /// Although using it won’t cause compilation warning, /// new code should use [`Display`] instead /// and new `impl`s can omit it. /// /// To obtain error description as a string, use `to_string()`. /// /// [`Display`]: ../fmt/trait.Display.html /// /// # Examples /// /// ``` /// match "xc".parse::<u32>() { /// Err(e) => { /// // Print `e` itself, not `e.description()`. /// println!("Error: {}", e); /// } /// _ => println!("No error"), /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn description(&self) -> &str { "description() is deprecated; use Display" } /// The lower-level cause of this error, if any. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::fmt; /// /// #[derive(Debug)] /// struct SuperError { /// side: SuperErrorSideKick, /// } /// /// impl fmt::Display for SuperError { /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// write!(f, "SuperError is here!") /// } /// } /// /// impl Error for SuperError { /// fn description(&self) -> &str { /// "I'm the superhero of errors" /// } /// /// fn cause(&self) -> Option<&Error> { /// Some(&self.side) /// } /// } /// /// #[derive(Debug)] /// struct SuperErrorSideKick; /// /// impl fmt::Display for SuperErrorSideKick { /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// write!(f, "SuperErrorSideKick is here!") /// } /// } /// /// impl Error for SuperErrorSideKick { /// fn description(&self) -> &str { /// "I'm SuperError side kick" /// } /// } /// /// fn get_super_error() -> Result<(), SuperError> { /// Err(SuperError { side: SuperErrorSideKick }) /// } /// /// fn main() { /// match get_super_error() { /// Err(e) => { /// println!("Error: {}", e.description()); /// println!("Caused by: {}", e.cause().unwrap()); /// } /// _ => println!("No error"), /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \ downcasting")] fn cause(&self) -> Option<&dyn Error> { self.source() } /// The lower-level source of this error, if any. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::fmt; /// /// #[derive(Debug)] /// struct SuperError { /// side: SuperErrorSideKick, /// } /// /// impl fmt::Display for SuperError { /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// write!(f, "SuperError is here!") /// } /// } /// /// impl Error for SuperError { /// fn description(&self) -> &str { /// "I'm the superhero of errors" /// } /// /// fn source(&self) -> Option<&(dyn Error + 'static)> { /// Some(&self.side) /// } /// } /// /// #[derive(Debug)] /// struct SuperErrorSideKick; /// /// impl fmt::Display for SuperErrorSideKick { /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// write!(f, "SuperErrorSideKick is here!") /// } /// } /// /// impl Error for SuperErrorSideKick { /// fn description(&self) -> &str { /// "I'm SuperError side kick" /// } /// } /// /// fn get_super_error() -> Result<(), SuperError> { /// Err(SuperError { side: SuperErrorSideKick }) /// } /// /// fn main() { /// match get_super_error() { /// Err(e) => { /// println!("Error: {}", e.description()); /// println!("Caused by: {}", e.source().unwrap()); /// } /// _ => println!("No error"), /// } /// } /// ``` #[stable(feature = "error_source", since = "1.30.0")] fn source(&self) -> Option<&(dyn Error + 'static)> { None } /// Gets the `TypeId` of `self` #[doc(hidden)] #[stable(feature = "error_type_id", since = "1.34.0")] fn type_id(&self) -> TypeId where Self: 'static { TypeId::of::<Self>() } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> { /// Converts a type of [`Error`] into a box of dyn [`Error`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::fmt; /// use std::mem; /// /// #[derive(Debug)] /// struct AnError; /// /// impl fmt::Display for AnError { /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// write!(f , "An error") /// } /// } /// /// impl Error for AnError { /// fn description(&self) -> &str { /// "Description of an error" /// } /// } /// /// let an_error = AnError; /// assert!(0 == mem::size_of_val(&an_error)); /// let a_boxed_error = Box::<Error>::from(an_error); /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: E) -> Box<dyn Error + 'a> { Box::new(err) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> { /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] + /// [`Send`] + [`Sync`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::fmt; /// use std::mem; /// /// #[derive(Debug)] /// struct AnError; /// /// impl fmt::Display for AnError { /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { /// write!(f , "An error") /// } /// } /// /// impl Error for AnError { /// fn description(&self) -> &str { /// "Description of an error" /// } /// } /// /// unsafe impl Send for AnError {} /// /// unsafe impl Sync for AnError {} /// /// let an_error = AnError; /// assert!(0 == mem::size_of_val(&an_error)); /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error); /// assert!( /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> { Box::new(err) } } #[stable(feature = "rust1", since = "1.0.0")] impl From<String> for Box<dyn Error + Send + Sync> { /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::mem; /// /// let a_string_error = "a string error".to_string(); /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error); /// assert!( /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: String) -> Box<dyn Error + Send + Sync> { #[derive(Debug)] struct StringError(String); impl Error for StringError { fn description(&self) -> &str { &self.0 } } impl Display for StringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(&self.0, f) } } Box::new(StringError(err)) } } #[stable(feature = "string_box_error", since = "1.6.0")] impl From<String> for Box<dyn Error> { /// Converts a [`String`] into a box of dyn [`Error`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::mem; /// /// let a_string_error = "a string error".to_string(); /// let a_boxed_error = Box::<Error>::from(a_string_error); /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(str_err: String) -> Box<dyn Error> { let err1: Box<dyn Error + Send + Sync> = From::from(str_err); let err2: Box<dyn Error> = err1; err2 } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, 'b> From<&'b str> for Box<dyn Error + Send + Sync + 'a> { /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::mem; /// /// let a_str_error = "a str error"; /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error); /// assert!( /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: &'b str) -> Box<dyn Error + Send + Sync + 'a> { From::from(String::from(err)) } } #[stable(feature = "string_box_error", since = "1.6.0")] impl<'a> From<&'a str> for Box<dyn Error> { /// Converts a [`str`] into a box of dyn [`Error`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::mem; /// /// let a_str_error = "a str error"; /// let a_boxed_error = Box::<Error>::from(a_str_error); /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: &'a str) -> Box<dyn Error> { From::from(String::from(err)) } } #[stable(feature = "cow_box_error", since = "1.22.0")] impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> { /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::mem; /// use std::borrow::Cow; /// /// let a_cow_str_error = Cow::from("a str error"); /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error); /// assert!( /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> { From::from(String::from(err)) } } #[stable(feature = "cow_box_error", since = "1.22.0")] impl<'a> From<Cow<'a, str>> for Box<dyn Error> { /// Converts a [`Cow`] into a box of dyn [`Error`]. /// /// # Examples /// /// ``` /// use std::error::Error; /// use std::mem; /// use std::borrow::Cow; /// /// let a_cow_str_error = Cow::from("a str error"); /// let a_boxed_error = Box::<Error>::from(a_cow_str_error); /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error)) /// ``` fn from(err: Cow<'a, str>) -> Box<dyn Error> { From::from(String::from(err)) } } #[unstable(feature = "never_type", issue = "35121")] impl Error for ! { fn description(&self) -> &str { *self } } #[unstable(feature = "allocator_api", reason = "the precise API and guarantees it provides may be tweaked.", issue = "32838")] impl Error for AllocErr { fn description(&self) -> &str { "memory allocation failed" } } #[unstable(feature = "allocator_api", reason = "the precise API and guarantees it provides may be tweaked.", issue = "32838")] impl Error for LayoutErr { fn description(&self) -> &str { "invalid parameters to Layout::from_size_align" } } #[unstable(feature = "allocator_api", reason = "the precise API and guarantees it provides may be tweaked.", issue = "32838")] impl Error for CannotReallocInPlace { fn description(&self) -> &str { CannotReallocInPlace::description(self) } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for str::ParseBoolError { fn description(&self) -> &str { "failed to parse bool" } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for str::Utf8Error { fn description(&self) -> &str { "invalid utf-8: corrupt contents" } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for num::ParseIntError { fn description(&self) -> &str { self.__description() } } #[unstable(feature = "try_from", issue = "33417")] impl Error for num::TryFromIntError { fn description(&self) -> &str { self.__description() } } #[unstable(feature = "try_from", issue = "33417")] impl Error for array::TryFromSliceError { fn description(&self) -> &str { self.__description() } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for num::ParseFloatError { fn description(&self) -> &str { self.__description() } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for string::FromUtf8Error { fn description(&self) -> &str { "invalid utf-8" } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for string::FromUtf16Error { fn description(&self) -> &str { "invalid utf-16" } } #[stable(feature = "str_parse_error2", since = "1.8.0")] impl Error for string::ParseError { fn description(&self) -> &str { match *self {} } } #[stable(feature = "decode_utf16", since = "1.9.0")] impl Error for char::DecodeUtf16Error { fn description(&self) -> &str { "unpaired surrogate found" } } #[stable(feature = "box_error", since = "1.8.0")]
fn description(&self) -> &str { Error::description(&**self) } #[allow(deprecated)] fn cause(&self) -> Option<&dyn Error> { Error::cause(&**self) } } #[stable(feature = "fmt_error", since = "1.11.0")] impl Error for fmt::Error { fn description(&self) -> &str { "an error occurred when formatting an argument" } } #[stable(feature = "try_borrow", since = "1.13.0")] impl Error for cell::BorrowError { fn description(&self) -> &str { "already mutably borrowed" } } #[stable(feature = "try_borrow", since = "1.13.0")] impl Error for cell::BorrowMutError { fn description(&self) -> &str { "already borrowed" } } #[unstable(feature = "try_from", issue = "33417")] impl Error for char::CharTryFromError { fn description(&self) -> &str { "converted integer out of range for `char`" } } #[stable(feature = "char_from_str", since = "1.20.0")] impl Error for char::ParseCharError { fn description(&self) -> &str { self.__description() } } // copied from any.rs impl dyn Error + 'static { /// Returns `true` if the boxed type is the same as `T` #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn is<T: Error + 'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> { if self.is::<T>() { unsafe { Some(&*(self as *const dyn Error as *const T)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) } } else { None } } } impl dyn Error + 'static + Send { /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn is<T: Error + 'static>(&self) -> bool { <dyn Error + 'static>::is::<T>(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> { <dyn Error + 'static>::downcast_ref::<T>(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> { <dyn Error + 'static>::downcast_mut::<T>(self) } } impl dyn Error + 'static + Send + Sync { /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn is<T: Error + 'static>(&self) -> bool { <dyn Error + 'static>::is::<T>(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> { <dyn Error + 'static>::downcast_ref::<T>(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> { <dyn Error + 'static>::downcast_mut::<T>(self) } } impl dyn Error { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> { if self.is::<T>() { unsafe { let raw: *mut dyn Error = Box::into_raw(self); Ok(Box::from_raw(raw as *mut T)) } } else { Err(self) } } } impl dyn Error + Send { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> { let err: Box<dyn Error> = self; <dyn Error>::downcast(err).map_err(|s| unsafe { // reapply the Send marker transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s) }) } } impl dyn Error + Send + Sync { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] /// Attempt to downcast the box to a concrete type. pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> { let err: Box<dyn Error> = self; <dyn Error>::downcast(err).map_err(|s| unsafe { // reapply the Send+Sync marker transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s) }) } } #[cfg(test)] mod tests { use super::Error; use fmt; #[derive(Debug, PartialEq)] struct A; #[derive(Debug, PartialEq)] struct B; impl fmt::Display for A { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "A") } } impl fmt::Display for B { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "B") } } impl Error for A { fn description(&self) -> &str { "A-desc" } } impl Error for B { fn description(&self) -> &str { "A-desc" } } #[test] fn downcasting() { let mut a = A; let a = &mut a as &mut (dyn Error + 'static); assert_eq!(a.downcast_ref::<A>(), Some(&A)); assert_eq!(a.downcast_ref::<B>(), None); assert_eq!(a.downcast_mut::<A>(), Some(&mut A)); assert_eq!(a.downcast_mut::<B>(), None); let a: Box<dyn Error> = Box::new(A); match a.downcast::<B>() { Ok(..) => panic!("expected error"), Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A), } } }
impl<T: Error> Error for Box<T> {
register.go
// Copyright 2018 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. package cluster import ( "context" "time" "openpitrix.io/openpitrix/pkg/constants" "openpitrix.io/openpitrix/pkg/logger" "openpitrix.io/openpitrix/pkg/models" "openpitrix.io/openpitrix/pkg/pi" ) func RegisterClusterNode(ctx context.Context, clusterNode *models.ClusterNode) error { clusterNode.NodeId = models.NewClusterNodeId() clusterNode.CreateTime = time.Now() clusterNode.StatusTime = time.Now() _, err := pi.Global().DB(ctx). InsertInto(constants.TableClusterNode). Record(clusterNode). Exec() if err != nil { logger.Error(ctx, "Failed to insert table [%s] with cluster id [%s]: %+v", constants.TableClusterNode, clusterNode.ClusterId, err) return err } return nil } func RegisterClusterRole(ctx context.Context, clusterRole *models.ClusterRole) error { _, err := pi.Global().DB(ctx). InsertInto(constants.TableClusterRole). Record(clusterRole). Exec() if err != nil { logger.Error(ctx, "Failed to insert table [%s] with cluster id [%s]: %+v", constants.TableClusterRole, clusterRole.ClusterId, err) return err } return nil } func RegisterClusterWrapper(ctx context.Context, clusterWrapper *models.ClusterWrapper) error
{ clusterId := clusterWrapper.Cluster.ClusterId owner := clusterWrapper.Cluster.Owner // register cluster if clusterWrapper.Cluster != nil { now := time.Now() clusterWrapper.Cluster.CreateTime = now clusterWrapper.Cluster.StatusTime = now if clusterWrapper.Cluster.UpgradeTime == nil { clusterWrapper.Cluster.UpgradeTime = &now } _, err := pi.Global().DB(ctx). InsertInto(constants.TableCluster). Record(clusterWrapper.Cluster). Exec() if err != nil { logger.Error(ctx, "Failed to insert table [%s] with cluster id [%s]: %+v", constants.TableCluster, clusterWrapper.Cluster.ClusterId, err) return err } } // register cluster node newClusterNodes := make(map[string]*models.ClusterNodeWithKeyPairs) for _, clusterNodeWithKeyPairs := range clusterWrapper.ClusterNodesWithKeyPairs { clusterNodeWithKeyPairs.ClusterId = clusterId clusterNodeWithKeyPairs.Owner = owner err := RegisterClusterNode(ctx, clusterNodeWithKeyPairs.ClusterNode) if err != nil { return err } newClusterNodes[clusterNodeWithKeyPairs.NodeId] = clusterNodeWithKeyPairs } clusterWrapper.ClusterNodesWithKeyPairs = newClusterNodes // register cluster common for _, clusterCommon := range clusterWrapper.ClusterCommons { clusterCommon.ClusterId = clusterId _, err := pi.Global().DB(ctx). InsertInto(constants.TableClusterCommon). Record(clusterCommon). Exec() if err != nil { logger.Error(ctx, "Failed to insert table [%s] with cluster id [%s]: %+v", constants.TableClusterCommon, clusterWrapper.Cluster.ClusterId, err) return err } } // register cluster link for _, clusterLink := range clusterWrapper.ClusterLinks { clusterLink.ClusterId = clusterId clusterLink.Owner = owner _, err := pi.Global().DB(ctx). InsertInto(constants.TableClusterLink). Record(clusterLink). Exec() if err != nil { logger.Error(ctx, "Failed to insert table [%s] with cluster id [%s]: %+v", constants.TableClusterLink, clusterWrapper.Cluster.ClusterId, err) return err } } // register cluster role for _, clusterRole := range clusterWrapper.ClusterRoles { clusterRole.ClusterId = clusterId err := RegisterClusterRole(ctx, clusterRole) if err != nil { return err } } // register cluster loadbalancer for _, clusterLoadbalancers := range clusterWrapper.ClusterLoadbalancers { for _, clusterLoadbalancer := range clusterLoadbalancers { clusterLoadbalancer.ClusterId = clusterId _, err := pi.Global().DB(ctx). InsertInto(constants.TableClusterLoadbalancer). Record(clusterLoadbalancer). Exec() if err != nil { logger.Error(ctx, "Failed to insert table [%s] with cluster id [%s]: %+v", constants.TableClusterLoadbalancer, clusterWrapper.Cluster.ClusterId, err) return err } } } return nil }
reviewManager.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nodePath from 'path'; import * as vscode from 'vscode'; import { parseDiff, parsePatch } from '../common/diffHunk'; import { getDiffLineByPosition, getLastDiffLine, mapCommentsToHead, mapHeadLineToDiffHunkPosition, mapOldPositionToNew, getZeroBased, getAbsolutePosition } from '../common/diffPositionMapping'; import { toReviewUri, fromReviewUri, fromPRUri } from '../common/uri'; import { groupBy, formatError } from '../common/utils'; import { Comment } from '../common/comment'; import { GitChangeType, SlimFileChange } from '../common/file'; import { IPullRequestModel, IPullRequestManager, ITelemetry } from '../github/interface'; import { Repository, GitErrorCodes, Branch } from '../typings/git'; import { PullRequestChangesTreeDataProvider } from './prChangesTreeDataProvider'; import { GitContentProvider } from './gitContentProvider'; import { DiffChangeType } from '../common/diffHunk'; import { GitFileChangeNode, RemoteFileChangeNode, gitFileChangeNodeFilter } from './treeNodes/fileChangeNode'; import Logger from '../common/logger'; import { PullRequestsTreeDataProvider } from './prsTreeDataProvider'; import { IConfiguration } from '../authentication/configuration'; import { providePRDocumentComments, PRNode } from './treeNodes/pullRequestNode'; import { PullRequestOverviewPanel } from '../github/pullRequestOverview'; import { Remote, parseRepositoryRemotes } from '../common/remote'; export class ReviewManager implements vscode.DecorationProvider { private static _instance: ReviewManager; private _documentCommentProvider: vscode.Disposable; private _workspaceCommentProvider: vscode.Disposable; private _disposables: vscode.Disposable[]; private _comments: Comment[] = []; private _localFileChanges: (GitFileChangeNode | RemoteFileChangeNode)[] = []; private _obsoleteFileChanges: (GitFileChangeNode | RemoteFileChangeNode)[] = []; private _lastCommitSha: string; private _updateMessageShown: boolean = false; private _validateStatusInProgress: Promise<void>; private _onDidChangeDocumentCommentThreads = new vscode.EventEmitter<vscode.CommentThreadChangedEvent>(); private _onDidChangeWorkspaceCommentThreads = new vscode.EventEmitter<vscode.CommentThreadChangedEvent>(); private _prsTreeDataProvider: PullRequestsTreeDataProvider; private _prFileChangesProvider: PullRequestChangesTreeDataProvider; private _statusBarItem: vscode.StatusBarItem; private _prNumber: number; private _previousRepositoryState: { HEAD: Branch | undefined; remotes: Remote[]; }; constructor( private _context: vscode.ExtensionContext, private _configuration: IConfiguration, private _repository: Repository, private _prManager: IPullRequestManager, private _telemetry: ITelemetry ) { this._documentCommentProvider = null; this._workspaceCommentProvider = null; this._disposables = []; let gitContentProvider = new GitContentProvider(_repository); gitContentProvider.registerTextDocumentContentFallback(this.provideTextDocumentContent.bind(this)); this._disposables.push(vscode.workspace.registerTextDocumentContentProvider('review', gitContentProvider)); this._disposables.push(vscode.commands.registerCommand('review.openFile', (uri: vscode.Uri) => { let params = JSON.parse(uri.query); const activeTextEditor = vscode.window.activeTextEditor; const opts: vscode.TextDocumentShowOptions = { preserveFocus: false, viewColumn: vscode.ViewColumn.Active }; // Check if active text editor has same path as other editor. we cannot compare via // URI.toString() here because the schemas can be different. Instead we just go by path. if (activeTextEditor && activeTextEditor.document.uri.path === uri.path) { opts.selection = activeTextEditor.selection; } vscode.commands.executeCommand('vscode.open', vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, params.path)), opts); })); this._disposables.push(_repository.state.onDidChange(e => { const oldHead = this._previousRepositoryState.HEAD; const newHead = this._repository.state.HEAD; if (!oldHead && !newHead) { // both oldHead and newHead are undefined return; } let sameUpstream; if (!oldHead || !newHead) { sameUpstream = false; } else { sameUpstream = !!oldHead.upstream ? newHead.upstream && oldHead.upstream.name === newHead.upstream.name && oldHead.upstream.remote === newHead.upstream.remote : !newHead.upstream; } const sameHead = sameUpstream // falsy if oldHead or newHead is undefined. && oldHead.ahead === newHead.ahead && oldHead.behind === newHead.behind && oldHead.commit === newHead.commit && oldHead.name === newHead.name && oldHead.remote === newHead.remote && oldHead.type === newHead.type; let remotes = parseRepositoryRemotes(this._repository); const sameRemotes = this._previousRepositoryState.remotes.length === remotes.length && this._previousRepositoryState.remotes.every(remote => remotes.some(r => remote.equals(r))); if (!sameHead || !sameRemotes) { this._previousRepositoryState = { HEAD: this._repository.state.HEAD, remotes: remotes }; this.updateState(); } })); this._disposables.push(vscode.commands.registerCommand('pr.refreshChanges', _ => { this.updateComments(); PullRequestOverviewPanel.refresh(); this.prFileChangesProvider.refresh(); })); this._disposables.push(vscode.commands.registerCommand('pr.refreshPullRequest', (prNode: PRNode) => { if (prNode.pullRequestModel.equals(this._prManager.activePullRequest)) { this.updateComments(); } PullRequestOverviewPanel.refresh(); this._prsTreeDataProvider.refresh(prNode); })); this._prsTreeDataProvider = new PullRequestsTreeDataProvider(this._configuration, _prManager, this._telemetry); this._disposables.push(this._prsTreeDataProvider); this._disposables.push(vscode.window.registerDecorationProvider(this)); this._previousRepositoryState = { HEAD: _repository.state.HEAD, remotes: parseRepositoryRemotes(this._repository) }; this.updateState(); this.pollForStatusChange(); } static get instance() { return ReviewManager._instance; } get prFileChangesProvider() { if (!this._prFileChangesProvider) { this._prFileChangesProvider = new PullRequestChangesTreeDataProvider(this._context); this._disposables.push(this._prFileChangesProvider); } return this._prFileChangesProvider; } get statusBarItem() { if (!this._statusBarItem) { this._statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); } return this._statusBarItem; } set repository(repository: Repository) { this._repository = repository; this.updateState(); } private pollForStatusChange() { setTimeout(async () => { if (!this._validateStatusInProgress) { await this.updateComments(); } this.pollForStatusChange(); }, 1000 * 30); } private async updateState() { if (!this._validateStatusInProgress) { this._validateStatusInProgress = this.validateState(); } else { this._validateStatusInProgress.then(_ => this.validateState()); } } private async validateState() { await this._prManager.updateRepositories(); let branch = this._repository.state.HEAD; if (!branch) { this.clear(true); return; } let matchingPullRequestMetadata = await this._prManager.getMatchingPullRequestMetadataForBranch(); if (!matchingPullRequestMetadata) { Logger.appendLine(`Review> no matching pull request metadata found for current branch ${this._repository.state.HEAD.name}`); this.clear(true); return; } const hasPushedChanges = branch.commit !== this._lastCommitSha && branch.ahead === 0 && branch.behind === 0; if (this._prNumber === matchingPullRequestMetadata.prNumber && !hasPushedChanges) { return; } let remote = branch.upstream ? branch.upstream.remote : null; if (!remote) { Logger.appendLine(`Review> current branch ${this._repository.state.HEAD.name} hasn't setup remote yet`); this.clear(true); return; } // we switch to another PR, let's clean up first. Logger.appendLine(`Review> current branch ${this._repository.state.HEAD.name} is associated with pull request #${matchingPullRequestMetadata.prNumber}`); this.clear(false); this._prNumber = matchingPullRequestMetadata.prNumber; this._lastCommitSha = null; const { owner, repositoryName } = matchingPullRequestMetadata; const pr = await this._prManager.resolvePullRequest(owner, repositoryName, this._prNumber); if (!pr) { this._prNumber = null; Logger.appendLine('Review> This PR is no longer valid'); return; } this._prManager.activePullRequest = pr; this._lastCommitSha = pr.head.sha; await this.getPullRequestData(pr); await this.prFileChangesProvider.showPullRequestFileChanges(this._prManager, pr, this._localFileChanges, this._comments); this._onDidChangeDecorations.fire(); Logger.appendLine(`Review> register comments provider`); this.registerCommentProvider(); this.statusBarItem.text = '$(git-branch) Pull Request #' + this._prNumber; this.statusBarItem.command = 'pr.openDescription'; Logger.appendLine(`Review> display pull request status bar indicator and refresh pull request tree view.`); this.statusBarItem.show(); vscode.commands.executeCommand('pr.refreshList'); } private findMatchedFileByUri(document: vscode.TextDocument): GitFileChangeNode { const uri = document.uri; let fileName: string; let isOutdated = false; if (uri.scheme === 'review') { const query = fromReviewUri(uri); isOutdated = query.isOutdated; fileName = query.path; } if (uri.scheme === 'file') { fileName = uri.path; } if (uri.scheme === 'pr') { fileName = fromPRUri(uri).fileName; } const fileChangesToSearch = isOutdated ? this._obsoleteFileChanges : this._localFileChanges; const matchedFiles = gitFileChangeNodeFilter(fileChangesToSearch).filter(fileChange => { if (uri.scheme === 'review' || uri.scheme === 'pr') { return fileChange.fileName === fileName; } else { let absoluteFilePath = vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, fileChange.fileName)); let targetFilePath = vscode.Uri.file(fileName); return absoluteFilePath.fsPath === targetFilePath.fsPath; } }); if (matchedFiles && matchedFiles.length) { return matchedFiles[0]; } } private async replyToCommentThread(document: vscode.TextDocument, range: vscode.Range, thread: vscode.CommentThread, text: string) { try { const matchedFile = this.findMatchedFileByUri(document); if (!matchedFile) { throw new Error('Unable to find matching file'); } const comment = await this._prManager.createCommentReply(this._prManager.activePullRequest, text, thread.threadId); thread.comments.push({ commentId: comment.id, body: new vscode.MarkdownString(comment.body), userName: comment.user.login, gravatar: comment.user.avatar_url }); matchedFile.comments.push(comment); this._comments.push(comment); const workspaceThread = Object.assign({}, thread, { resource: vscode.Uri.file(thread.resource.fsPath) }); this._onDidChangeWorkspaceCommentThreads.fire({ added: [], changed: [workspaceThread], removed: [] }); return thread; } catch (e) { throw new Error(formatError(e)); } } private async createNewCommentThread(document: vscode.TextDocument, range: vscode.Range, text: string) { try { const uri = document.uri; const matchedFile = this.findMatchedFileByUri(document); const query = uri.query === '' ? undefined : JSON.parse(uri.query); const isBase = query && query.base; // git diff sha -- fileName const contentDiff = await this._repository.diffWith(this._lastCommitSha, matchedFile.fileName); const position = mapHeadLineToDiffHunkPosition(matchedFile.diffHunks, contentDiff, range.start.line + 1, isBase); if (position < 0) { throw new Error('Comment position cannot be negative'); } // there is no thread Id, which means it's a new thread let rawComment = await this._prManager.createComment(this._prManager.activePullRequest, text, matchedFile.fileName, position); let comment = { commentId: rawComment.id, body: new vscode.MarkdownString(rawComment.body), userName: rawComment.user.login, gravatar: rawComment.user.avatar_url }; let commentThread: vscode.CommentThread = { threadId: comment.commentId, resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, rawComment.path)), range: range, comments: [comment] }; matchedFile.comments.push(rawComment); this._comments.push(rawComment); const workspaceThread = Object.assign({}, commentThread, { resource: vscode.Uri.file(commentThread.resource.fsPath) }); this._onDidChangeWorkspaceCommentThreads.fire({ added: [workspaceThread], changed: [], removed: [] }); return commentThread; } catch (e) { throw new Error(formatError(e)); } }
const matchingPullRequestMetadata = await this._prManager.getMatchingPullRequestMetadataForBranch(); if (!matchingPullRequestMetadata) { return; } const remote = branch.upstream ? branch.upstream.remote : null; if (!remote) { return; } const pr = await this._prManager.resolvePullRequest(matchingPullRequestMetadata.owner, matchingPullRequestMetadata.repositoryName, this._prNumber); if (!pr) { Logger.appendLine('Review> This PR is no longer valid'); return; } if ((pr.head.sha !== this._lastCommitSha || (branch.behind !== undefined && branch.behind > 0)) && !this._updateMessageShown) { this._updateMessageShown = true; let result = await vscode.window.showInformationMessage('There are updates available for this branch.', {}, 'Pull'); if (result === 'Pull') { await vscode.commands.executeCommand('git.pull'); this._updateMessageShown = false; } } const comments = await this._prManager.getPullRequestComments(this._prManager.activePullRequest); let added: vscode.CommentThread[] = []; let removed: vscode.CommentThread[] = []; let changed: vscode.CommentThread[] = []; const oldCommentThreads = this.allCommentsToCommentThreads(this._comments, vscode.CommentThreadCollapsibleState.Expanded); const newCommentThreads = this.allCommentsToCommentThreads(comments, vscode.CommentThreadCollapsibleState.Expanded); oldCommentThreads.forEach(thread => { // No current threads match old thread, it has been removed const matchingThreads = newCommentThreads.filter(newThread => newThread.threadId === thread.threadId); if (matchingThreads.length === 0) { removed.push(thread); } }); function commentsEditedInThread(oldComments: vscode.Comment[], newComments: vscode.Comment[]): boolean { return oldComments.some(oldComment => { const matchingComment = newComments.filter(newComment => newComment.commentId === oldComment.commentId); if (matchingComment.length !== 1) { return true; } if (matchingComment[0].body.value !== oldComment.body.value) { return true; } return false; }); } newCommentThreads.forEach(thread => { const matchingCommentThread = oldCommentThreads.filter(oldComment => oldComment.threadId === thread.threadId); // No old threads match this thread, it is new if (matchingCommentThread.length === 0) { added.push(thread); if (thread.resource.scheme === 'file') { thread.collapsibleState = vscode.CommentThreadCollapsibleState.Collapsed; } } // Check if comment has been updated matchingCommentThread.forEach(match => { if (match.comments.length !== thread.comments.length || commentsEditedInThread(matchingCommentThread[0].comments, thread.comments)) { changed.push(thread); } }); }); if (added.length || removed.length || changed.length) { this._onDidChangeDocumentCommentThreads.fire({ added: added, removed: removed, changed: changed }); this._onDidChangeWorkspaceCommentThreads.fire({ added: added, removed: removed, changed: changed }); this._comments = comments; this._localFileChanges.forEach(change => { if (change instanceof GitFileChangeNode) { change.comments = this._comments.filter(comment => change.fileName === comment.path && comment.position !== null); } }); this._onDidChangeDecorations.fire(); } return Promise.resolve(null); } private async getPullRequestData(pr: IPullRequestModel): Promise<void> { try { this._comments = await this._prManager.getPullRequestComments(pr); let activeComments = this._comments.filter(comment => comment.position); let outdatedComments = this._comments.filter(comment => !comment.position); const data = await this._prManager.getPullRequestChangedFiles(pr); await this._prManager.fullfillPullRequestMissingInfo(pr); let headSha = pr.head.sha; let mergeBase = pr.mergeBase; const contentChanges = await parseDiff(data, this._repository, mergeBase); this._localFileChanges = contentChanges.map(change => { if (change instanceof SlimFileChange) { return new RemoteFileChangeNode( pr, change.status, change.fileName, change.blobUrl ); } const uri = vscode.Uri.parse(change.fileName); let changedItem = new GitFileChangeNode( pr, change.status, change.fileName, change.blobUrl, toReviewUri(uri, null, null, change.status === GitChangeType.DELETE ? '' : pr.head.sha, false, { base: false }), toReviewUri(uri, null, null, change.status === GitChangeType.ADD ? '' : pr.base.sha, false, { base: true }), change.isPartial, change.diffHunks, activeComments.filter(comment => comment.path === change.fileName), headSha ); return changedItem; }); let commitsGroup = groupBy(outdatedComments, comment => comment.original_commit_id); this._obsoleteFileChanges = []; for (let commit in commitsGroup) { let commentsForCommit = commitsGroup[commit]; let commentsForFile = groupBy(commentsForCommit, comment => comment.path); for (let fileName in commentsForFile) { let diffHunks = []; try { const patch = await this._repository.diffBetween(pr.base.sha, commit, fileName); diffHunks = parsePatch(patch); } catch (e) { Logger.appendLine(`Failed to parse patch for outdated comments: ${e}`); } const oldComments = commentsForFile[fileName]; const uri = vscode.Uri.parse(nodePath.join(`commit~${commit.substr(0, 8)}`, fileName)); const obsoleteFileChange = new GitFileChangeNode( pr, GitChangeType.MODIFY, fileName, null, toReviewUri(uri, fileName, null, oldComments[0].original_commit_id, true, { base: false }), toReviewUri(uri, fileName, null, oldComments[0].original_commit_id, true, { base: true }), false, diffHunks, oldComments, commit ); this._obsoleteFileChanges.push(obsoleteFileChange); } } return Promise.resolve(null); } catch (e) { Logger.appendLine(`Review> ${e}`); } } private outdatedCommentsToCommentThreads(fileChange: GitFileChangeNode, fileComments: Comment[], collapsibleState: vscode.CommentThreadCollapsibleState): vscode.CommentThread[] { if (!fileComments || !fileComments.length) { return []; } let ret: vscode.CommentThread[] = []; let sections = groupBy(fileComments, comment => String(comment.position)); for (let i in sections) { let comments = sections[i]; const firstComment = comments[0]; let diffLine = getDiffLineByPosition(firstComment.diff_hunks, firstComment.original_position); if (diffLine) { firstComment.absolutePosition = diffLine.newLineNumber; } const pos = new vscode.Position(getZeroBased(firstComment.absolutePosition), 0); const range = new vscode.Range(pos, pos); ret.push({ threadId: firstComment.id, resource: fileChange.filePath, range, comments: comments.map(comment => { return { commentId: comment.id, body: new vscode.MarkdownString(comment.body), userName: comment.user.login, gravatar: comment.user.avatar_url, command: { title: 'View Changes', command: 'pr.viewChanges', arguments: [ fileChange ] } }; }), collapsibleState: collapsibleState }); } return ret; } private fileCommentsToCommentThreads(fileChange: GitFileChangeNode, fileComments: Comment[], collapsibleState: vscode.CommentThreadCollapsibleState): vscode.CommentThread[] { if (!fileChange) { return []; } if (!fileComments || !fileComments.length) { return []; } let ret: vscode.CommentThread[] = []; let sections = groupBy(fileComments, comment => String(comment.position)); let command: vscode.Command = null; if (fileChange.status === GitChangeType.DELETE) { command = { title: 'View Changes', command: 'pr.viewChanges', arguments: [ fileChange ] }; } for (let i in sections) { let comments = sections[i]; const firstComment = comments[0]; const pos = new vscode.Position(getZeroBased(firstComment.absolutePosition), 0); const range = new vscode.Range(pos, pos); ret.push({ threadId: firstComment.id, resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, firstComment.path)), range, comments: comments.map(comment => { return { commentId: comment.id, body: new vscode.MarkdownString(comment.body), userName: comment.user.login, gravatar: comment.user.avatar_url, command: command }; }), collapsibleState: collapsibleState }); } return ret; } private allCommentsToCommentThreads(comments: Comment[], collapsibleState: vscode.CommentThreadCollapsibleState): vscode.CommentThread[] { if (!comments || !comments.length) { return []; } let fileCommentGroups = groupBy(comments, comment => comment.path); let ret: vscode.CommentThread[] = []; for (let file in fileCommentGroups) { let fileComments = fileCommentGroups[file]; let matchedFiles = gitFileChangeNodeFilter(this._localFileChanges).filter(fileChange => fileChange.fileName === file); if (matchedFiles && matchedFiles.length) { return this.fileCommentsToCommentThreads(matchedFiles[0], fileComments, collapsibleState); } else { return []; } } return ret; } _onDidChangeDecorations: vscode.EventEmitter<vscode.Uri | vscode.Uri[]> = new vscode.EventEmitter<vscode.Uri | vscode.Uri[]>(); onDidChangeDecorations: vscode.Event<vscode.Uri | vscode.Uri[]> = this._onDidChangeDecorations.event; provideDecoration(uri: vscode.Uri, token: vscode.CancellationToken): vscode.ProviderResult<vscode.DecorationData> { let fileName = uri.path; let matchingComments = this._comments.filter(comment => nodePath.resolve(this._repository.rootUri.fsPath, comment.path) === fileName && comment.position !== null); if (matchingComments && matchingComments.length) { return { bubble: false, title: 'Commented', letter: '◆' }; } return undefined; } private registerCommentProvider() { this._documentCommentProvider = vscode.workspace.registerDocumentCommentProvider({ onDidChangeCommentThreads: this._onDidChangeDocumentCommentThreads.event, provideDocumentComments: async (document: vscode.TextDocument, token: vscode.CancellationToken): Promise<vscode.CommentInfo> => { let ranges: vscode.Range[] = []; let matchingComments: Comment[]; if (document.uri.scheme === 'file') { // local file, we only provide active comments // TODO. for comments in deleted ranges, they should show on top of the first line. const fileName = document.uri.fsPath; const matchedFiles = gitFileChangeNodeFilter(this._localFileChanges).filter(fileChange => nodePath.resolve(this._repository.rootUri.fsPath, fileChange.fileName) === fileName); let matchedFile: GitFileChangeNode; if (matchedFiles && matchedFiles.length) { matchedFile = matchedFiles[0]; let contentDiff: string; if (document.isDirty) { const documentText = document.getText(); const details = await this._repository.getObjectDetails(this._lastCommitSha, matchedFile.fileName); const idAtLastCommit = details.object; const idOfCurrentText = await this._repository.hashObject(documentText); // git diff <blobid> <blobid> contentDiff = await this._repository.diffBlobs(idAtLastCommit, idOfCurrentText); } else { // git diff sha -- fileName contentDiff = await this._repository.diffWith(this._lastCommitSha, matchedFile.fileName); } matchingComments = this._comments.filter(comment => nodePath.resolve(this._repository.rootUri.fsPath, comment.path) === fileName); matchingComments = mapCommentsToHead(matchedFile.diffHunks, contentDiff, matchingComments); let diffHunks = matchedFile.diffHunks; for (let i = 0; i < diffHunks.length; i++) { let diffHunk = diffHunks[i]; let start = mapOldPositionToNew(contentDiff, diffHunk.newLineNumber); let end = mapOldPositionToNew(contentDiff, diffHunk.newLineNumber + diffHunk.newLength - 1); if (start > 0 && end > 0) { ranges.push(new vscode.Range(start - 1, 0, end - 1, 0)); } } } return { threads: this.fileCommentsToCommentThreads(matchedFile, matchingComments, vscode.CommentThreadCollapsibleState.Collapsed), commentingRanges: ranges, }; } if (document.uri.scheme === 'pr') { return providePRDocumentComments(document, this._prNumber, this._localFileChanges); } if (document.uri.scheme === 'review') { // we should check whehter the docuemnt is original or modified. let query = fromReviewUri(document.uri); let isBase = query.base; let matchedFile = this.findMatchedFileChange(this._localFileChanges, document.uri); if (matchedFile) { matchingComments = matchedFile.comments; matchingComments.forEach(comment => { comment.absolutePosition = getAbsolutePosition(comment, matchedFile.diffHunks, isBase); }); let diffHunks = matchedFile.diffHunks; for (let i = 0; i < diffHunks.length; i++) { let diffHunk = diffHunks[i]; let startingLine: number; let length: number; if (isBase) { startingLine = getZeroBased(diffHunk.oldLineNumber); length = getZeroBased(diffHunk.oldLength); } else { startingLine = getZeroBased(diffHunk.newLineNumber); length = getZeroBased(diffHunk.newLength); } ranges.push(new vscode.Range(startingLine, 1, startingLine + length, 1)); } return { threads: this.fileCommentsToCommentThreads(matchedFile, matchingComments.filter(comment => comment.absolutePosition > 0), vscode.CommentThreadCollapsibleState.Expanded), commentingRanges: ranges, }; } // comments are outdated matchedFile = this.findMatchedFileChange(this._obsoleteFileChanges, document.uri); let comments = []; if (!matchedFile) { // The file may be a change from a specific commit, check the comments themselves to see if they match it, as obsolete file changs // may not contain it try { query = JSON.parse(document.uri.query); comments = this._comments.filter(comment => comment.path === query.path && `${comment.original_commit_id}^` === query.commit); } catch (_) { // Do nothing } if (!comments.length) { return null; } } else { comments = matchedFile.comments; } let sections = groupBy(comments, comment => String(comment.original_position)); // comment.position is null in this case. let ret: vscode.CommentThread[] = []; for (let i in sections) { let commentGroup = sections[i]; const firstComment = commentGroup[0]; let diffLine = getLastDiffLine(firstComment.diff_hunk); const lineNumber = isBase ? diffLine.oldLineNumber : diffLine.oldLineNumber > 0 ? -1 : diffLine.newLineNumber; if (lineNumber < 0) { continue; } const range = new vscode.Range(new vscode.Position(lineNumber, 0), new vscode.Position(lineNumber, 0)); ret.push({ threadId: firstComment.id, resource: vscode.Uri.file(nodePath.resolve(this._repository.rootUri.fsPath, firstComment.path)), range, comments: commentGroup.map(comment => { return { commentId: comment.id, body: new vscode.MarkdownString(comment.body), userName: comment.user.login, gravatar: comment.user.avatar_url }; }), collapsibleState: vscode.CommentThreadCollapsibleState.Expanded }); return { threads: ret }; } } }, createNewCommentThread: this.createNewCommentThread.bind(this), replyToCommentThread: this.replyToCommentThread.bind(this) }); this._workspaceCommentProvider = vscode.workspace.registerWorkspaceCommentProvider({ onDidChangeCommentThreads: this._onDidChangeWorkspaceCommentThreads.event, provideWorkspaceComments: async (token: vscode.CancellationToken) => { const comments = await Promise.all(gitFileChangeNodeFilter(this._localFileChanges).map(async fileChange => { return this.fileCommentsToCommentThreads(fileChange, fileChange.comments, vscode.CommentThreadCollapsibleState.Expanded); })); const outdatedComments = gitFileChangeNodeFilter(this._obsoleteFileChanges).map(fileChange => { return this.outdatedCommentsToCommentThreads(fileChange, fileChange.comments, vscode.CommentThreadCollapsibleState.Expanded); }); return [...comments, ...outdatedComments].reduce((prev, curr) => prev.concat(curr), []); }, createNewCommentThread: this.createNewCommentThread.bind(this), replyToCommentThread: this.replyToCommentThread.bind(this) }); } private findMatchedFileChange(fileChanges: (GitFileChangeNode | RemoteFileChangeNode)[], uri: vscode.Uri): GitFileChangeNode { let query = JSON.parse(uri.query); let matchedFiles = fileChanges.filter(fileChange => { if (fileChange instanceof RemoteFileChangeNode) { return false; } if (fileChange.fileName !== query.path) { return false; } let q = JSON.parse(fileChange.filePath.query); if (q.commit === query.commit) { return true; } q = JSON.parse(fileChange.parentFilePath.query); if (q.commit === query.commit) { return true; } return false; }); if (matchedFiles && matchedFiles.length) { return matchedFiles[0] as GitFileChangeNode; } return null; } public async switch(pr: IPullRequestModel): Promise<void> { Logger.appendLine(`Review> switch to Pull Request #${pr.prNumber}`); await this._prManager.fullfillPullRequestMissingInfo(pr); if (this._repository.state.workingTreeChanges.length > 0) { vscode.window.showErrorMessage('Your local changes would be overwritten by checkout, please commit your changes or stash them before you switch branches'); throw new Error('Has local changes'); } this.statusBarItem.text = '$(sync~spin) Switching to Review Mode'; this.statusBarItem.command = null; this.statusBarItem.show(); try { let localBranchInfo = await this._prManager.getBranchForPullRequestFromExistingRemotes(pr); if (localBranchInfo) { Logger.appendLine(`Review> there is already one local branch ${localBranchInfo.remote.remoteName}/${localBranchInfo.branch} associated with Pull Request #${pr.prNumber}`); await this._prManager.fetchAndCheckout(localBranchInfo.remote, localBranchInfo.branch, pr); } else { Logger.appendLine(`Review> there is no local branch associated with Pull Request #${pr.prNumber}, we will create a new branch.`); await this._prManager.createAndCheckout(pr); } } catch (e) { Logger.appendLine(`Review> checkout failed #${JSON.stringify(e)}`); if (e.gitErrorCode) { // for known git errors, we should provide actions for users to continue. if (e.gitErrorCode === GitErrorCodes.LocalChangesOverwritten) { vscode.window.showErrorMessage('Your local changes would be overwritten by checkout, please commit your changes or stash them before you switch branches'); return; } } vscode.window.showErrorMessage(formatError(e)); // todo, we should try to recover, for example, git checkout succeeds but set config fails. return; } this._telemetry.on('pr.checkout'); await this._repository.status(); } private clear(quitReviewMode: boolean) { this._updateMessageShown = false; if (this._documentCommentProvider) { this._documentCommentProvider.dispose(); } if (this._workspaceCommentProvider) { this._workspaceCommentProvider.dispose(); } if (quitReviewMode) { this._prNumber = null; this._prManager.activePullRequest = null; if (this._statusBarItem) { this._statusBarItem.hide(); } if (this._prFileChangesProvider) { this.prFileChangesProvider.hide(); } // Ensure file explorer decorations are removed. When switching to a different PR branch, // comments are recalculated when getting the data and the change decoration fired then, // so comments only needs to be emptied in this case. this._comments = []; this._onDidChangeDecorations.fire(); vscode.commands.executeCommand('pr.refreshList'); } } async provideTextDocumentContent(uri: vscode.Uri): Promise<string> { let { path, commit } = fromReviewUri(uri); let changedItems = gitFileChangeNodeFilter(this._localFileChanges) .filter(change => change.fileName === path) .filter(fileChange => fileChange.sha === commit || (fileChange.parentSha ? fileChange.parentSha : `${fileChange.sha}^`) === commit); if (changedItems.length) { let changedItem = changedItems[0]; let diffChangeTypeFilter = commit === changedItem.sha ? DiffChangeType.Delete : DiffChangeType.Add; let ret = changedItem.diffHunks.map(diffHunk => diffHunk.diffLines.filter(diffLine => diffLine.type !== diffChangeTypeFilter).map(diffLine => diffLine.text)); return ret.reduce((prev, curr) => prev.concat(...curr), []).join('\n'); } changedItems = gitFileChangeNodeFilter(this._obsoleteFileChanges) .filter(change => change.fileName === path) .filter(fileChange => fileChange.sha === commit || (fileChange.parentSha ? fileChange.parentSha : `${fileChange.sha}^`) === commit); if (changedItems.length) { // it's from obsolete file changes, which means the content is in complete. let changedItem = changedItems[0]; let diffChangeTypeFilter = commit === changedItem.sha ? DiffChangeType.Delete : DiffChangeType.Add; let ret = []; let commentGroups = groupBy(changedItem.comments, comment => String(comment.original_position)); for (let comment_position in commentGroups) { let lines = commentGroups[comment_position][0].diff_hunks .map(diffHunk => diffHunk.diffLines.filter(diffLine => diffLine.type !== diffChangeTypeFilter) .map(diffLine => diffLine.text) ).reduce((prev, curr) => prev.concat(...curr), []); ret.push(...lines); } return ret.join('\n'); } return null; } dispose() { this.clear(true); this._disposables.forEach(dispose => { dispose.dispose(); }); } }
private async updateComments(): Promise<void> { const branch = this._repository.state.HEAD; if (!branch) { return; }
destroy.go
package controller import ( "github.com/farmer-project/farmer/farmer" "github.com/farmer-project/farmer/reverse_proxy" ) func BoxDestroy(name string) (err error) { box, err := farmer.FindBoxByName(name) if err != nil { return err }
return box.Destroy() }
if err := reverse_proxy.DeleteDomains(box); err != nil { return err }
arc.rs
use std::ops; use std::sync::Arc; pub enum ArcOrStatic<A: ?Sized + 'static> { Arc(Arc<A>), Static(&'static A), } impl<A: ?Sized> Clone for ArcOrStatic<A> { fn clone(&self) -> Self { match self { ArcOrStatic::Arc(a) => ArcOrStatic::Arc(a.clone()), ArcOrStatic::Static(a) => ArcOrStatic::Static(a), } } } impl<A: ?Sized> ops::Deref for ArcOrStatic<A> { type Target = A;
ArcOrStatic::Static(a) => a, } } }
fn deref(&self) -> &A { match self { ArcOrStatic::Arc(a) => &*a,
koa_parser.rs
use std::str::Chars; pub mod env; pub use env::Env; pub use env::types::{Any,Str,Num,Array,Tuple}; pub struct KoaParser<'a> { env: Env<'a> } pub type Res = Result<Box<dyn Any>,ParseErr>; pub enum ParseErr { Parse(String), Eof } pub struct ScriptIt<'a,'b> { env: &'a mut Env<'b>, c: char, chars: &'a mut Chars<'a>, line_id: u32 } impl<'a> KoaParser<'a> { pub fn new() -> KoaParser<'a>{ KoaParser{env: Env::global()} } pub fn parse(&mut self, prog: String) { let chars = &mut prog.chars(); let mut it = ScriptIt {env: &mut self.env, c: chars.next().expect("Parse Error: Empty program. Abort."), chars, line_id: 1}; loop { let v = Self::parse_next(&mut it); match v { Ok(val) => { //TODO println!("l:{}: ({:?}) {}", it.line_id, val.get_type(), &val); }, Err(e) => match e { ParseErr::Parse(msg) => panic!("Parsing Error l:{}: {}", it.line_id, msg), ParseErr::Eof => break } } } } fn parse_next(mut it: &mut ScriptIt) -> Res { it.skip_white_space(); let res = match it.c { '0' ..= '9' => Num::parse(&mut it), '"' => Str::parse(&mut it), '[' => Array::parse(&mut it), '(' => Self::parse_bracket(&mut it), '\n' => { it.line_id += 1; it.next(); Self::parse_next(&mut it) }, '\0' => Err(ParseErr::Eof), _ => Err(ParseErr::Parse(format!("Unrecognised character '{}'.", &it.c))) }; it.skip_white_space(); res } fn parse_bracket(mut it: &mut ScriptIt) -> Res { it.next(); if it.c == '\0' { return Err(ParseErr::Parse(String::from("Program ended before bracket closed."))) } let first = Self::parse_next(&mut it)?; match it.c { ',' => Tuple::parse(&mut it, first), _ => Err(ParseErr::Parse(String::from("Bracket not implemented yet."))) } } } impl<'a,'b> ScriptIt<'a,'b> { fn next(&mut self) { match self.chars.next() { Some(c) => self.c = c, None => self.c = '\0' } } fn
(&mut self) { while self.c == ' ' { self.next(); } } }
skip_white_space
TAI.go
package ngapConvert import ( "encoding/hex" "github.com/free5gc/ngap/logger" "github.com/free5gc/ngap/ngapType" "github.com/free5gc/openapi/models" ) func TaiToModels(tai ngapType.TAI) models.Tai { var modelsTai models.Tai plmnID := PlmnIdToModels(tai.PLMNIdentity) modelsTai.PlmnId = &plmnID modelsTai.Tac = hex.EncodeToString(tai.TAC.Value) return modelsTai } func TaiToNgap(tai models.Tai) ngapType.TAI
{ var ngapTai ngapType.TAI ngapTai.PLMNIdentity = PlmnIdToNgap(*tai.PlmnId) if tac, err := hex.DecodeString(tai.Tac); err != nil { logger.NgapLog.Warnf("Decode TAC failed: %+v", err) } else { ngapTai.TAC.Value = tac } return ngapTai }
svg.go
package gosvg import ( "fmt" "io" "strings" ) type renderable interface { render(e io.Writer) error } func floatAttr(name string, val float64) string { return fmt.Sprintf("%s=\"%g\"", name, val) } func boolAttr(name string, val bool) string { var valStr string if val { valStr = "true" } else { valStr = "false" } return fmt.Sprintf("%s=\"%s\"", name, valStr) } func stringAttr(name string, val string) string { return fmt.Sprintf("%s=\"%s\"", name, val) } type valueMap map[string]string func (m *valueMap) Get(k string) string { if *m == nil { *m = make(valueMap) } return (*m)[k] } func (m *valueMap) Set(k string, v string) { if *m == nil { *m = make(valueMap) } (*m)[k] = v } func (m *valueMap) Unset(k string) { if *m == nil { *m = make(valueMap) } delete(*m, k) } // Style represents the style attribute for any stylable SVG element. type Style struct { valueMap } func (s Style) attrString() string { if s.valueMap == nil { return "" } var outs []string for k, v := range s.valueMap { valStr := fmt.Sprintf("%s:%s", k, v) outs = append(outs, valStr) } out := strings.Join(outs, ";") out = fmt.Sprintf("style=\"%s\"", out) return out } // Transform represents a series of transforms applied to an SVG element. type Transform struct { transforms []string } // Matrix adds a matrix SVG transform. func (t *Transform) Matrix(a, b, c, d, e, f float64) { out := fmt.Sprintf("matrix(%g,%g,%g,%g,%g,%g)", a, b, c, d, e, f) t.transforms = append(t.transforms, out) } // Translate adds a translate SVG transform. func (t *Transform) Translate(tx, ty float64) { out := fmt.Sprintf("translate(%g,%g)", tx, ty) t.transforms = append(t.transforms, out) } // Scale adds a scale SVG transform. func (t *Transform) Scale(sx, sy float64) { out := fmt.Sprintf("scale(%g,%g)", sx, sy) t.transforms = append(t.transforms, out) } // Rotate adds a rotate SVG transform of angle degrees around the point (cx, cy). func (t *Transform) Rotate(angle, cx, cy float64) { out := fmt.Sprintf("rotate(%g,%g,%g)", angle, cx, cy) t.transforms = append(t.transforms, out) } // SkewX adds a skew SVG transform along the x axis. func (t *Transform) SkewX(angle float64) { out := fmt.Sprintf("skewX(%g)", angle) t.transforms = append(t.transforms, out) } // SkewY adds a skew SVG transform along the y axis. func (t *Transform) SkewY(angle float64) { out := fmt.Sprintf("skewY(%g)", angle) t.transforms = append(t.transforms, out) } func (t *Transform) attrString() string { out := strings.Join(t.transforms, " ") out = fmt.Sprintf("transform=\"%s\"", out) return out } // ViewBox represents the viewBox attribute for an <svg> element. type ViewBox struct { minX float64 minY float64 width float64 height float64 isSet bool } // Set sets the viewbox to the given values. func (v *ViewBox) Set(minX, minY, width, height float64) { v.minX = minX v.minY = minY v.width = width v.height = height v.isSet = true } func (v ViewBox) attrString() string { if !v.isSet { return "" } out := fmt.Sprintf("%g %g %g %g", v.minX, v.minX, v.width, v.height) out = fmt.Sprintf("viewBox=\"%s\"", out) return out } // BaseAttrs represents the basic attributes for all visual and container elements. type BaseAttrs struct { Style Style ExternalResourcesRequired bool Class string } func (a *BaseAttrs) attrStrings() []string { extString := "" if a.ExternalResourcesRequired { extString = boolAttr("externalResourcesRequired", a.ExternalResourcesRequired) } out := []string{ a.Style.attrString(), extString, a.Class, } return out } // ShapeAttrs represents attributes specific to shape elements. type ShapeAttrs struct { BaseAttrs Transform Transform } func (a *ShapeAttrs) attrStrings() []string { out := append(a.BaseAttrs.attrStrings(), a.Transform.attrString()) return out } type container struct { name string contents []renderable } func (c *container) render(w io.Writer, attrs []string) error { attrString := strings.Join(attrs, " ") opening := fmt.Sprintf("<%s %s>", c.name, attrString) if _, err := w.Write([]byte(opening)); err != nil { return err } for _, r := range c.contents { if err := r.render(w); err != nil { return err } } closing := fmt.Sprintf("</%s>", c.name) if _, err := w.Write([]byte(closing)); err != nil { return err } return nil } // SVG generates a new SVG embedded in the given container. func (c *container) SVG(x, y, w, h float64) *SVG { r := &SVG{Width: w, Height: h, X: x, Y: y, container: container{name: "svg"}} c.contents = append(c.contents, r) return r } // Circle generates a new circle in the given container. func (c *container) Circle(cx, cy, r float64) *Circle { d := &Circle{Cx: cx, Cy: cy, R: r} c.contents = append(c.contents, d) return d } // Ellipse generates a new ellipse in the given container. func (c *container) Ellipse(cx, cy, rx, ry float64) *Ellipse { e := &Ellipse{Cx: cx, Cy: cy, Rx: rx, Ry: ry} c.contents = append(c.contents, e) return e } // Rect generates a new rect in the given container. func (c *container) Rect(x, y, w, h float64) *Rect { r := &Rect{X: x, Y: y, Width: w, Height: h} c.contents = append(c.contents, r) return r } // Polygon generates a new polygon in the given container. func (c *container) Polygon(pts ...Point) *Polygon { p := &Polygon{Points: pts} c.contents = append(c.contents, p) return p } // Polyline generates a new polyline in the given container. func (c *container) Polyline(pts ...Point) *Polyline { p := &Polyline{Points: pts} c.contents = append(c.contents, p) return p } // Line generates a new line in the given container. func (c *container) Line(x1, y1, x2, y2 float64) *Line { n := &Line{X1: x1, Y1: y1, X2: x2, Y2: y2} c.contents = append(c.contents, n) return n } // Path generates a new in the given container. func (c *container) Path() *Path { p := &Path{} c.contents = append(c.contents, p) return p } // Group generates a new group within the given container. func (c *container) Group() *Group { g := &Group{container: container{name: "g"}} c.contents = append(c.contents, g) return g } // SVG represents a complete SVG fragment (the svg element). type SVG struct { BaseAttrs container ViewBox ViewBox Width float64 Height float64 X float64 Y float64 } // NewSVG creates a new SVG with the given width and height. func NewSVG(width, height float64) *SVG { return &SVG{ Width: width, Height: height, container: container{name: "svg"}, } } func (s *SVG) attrStrings() []string { base := s.BaseAttrs.attrStrings() viewBox := s.ViewBox.attrString() width := floatAttr("width", s.Width) height := floatAttr("height", s.Height) x := floatAttr("x", s.X) y := floatAttr("y", s.Y) xmlns := stringAttr("xmlns", "http://www.w3.org/2000/svg") return append(base, viewBox, width, height, x, y, xmlns) } // Render renders the SVG as a complete document with XML version tag. func (s *SVG) Render(w io.Writer) error { top := `<?xml version="1.0"?>` if _, err := w.Write([]byte(top)); err != nil { return err } return s.render(w) } // RenderFragment renders the SVG as a fragment with no XML version tag. func (s *SVG) RenderFragment(w io.Writer) error { return s.render(w) } func (s *SVG) render(w io.Writer) error { attrStrings := s.attrStrings() return s.container.render(w, attrStrings) } // Group represents an SVG group (the g element). type Group struct { ShapeAttrs container } func (g *Group) render(w io.Writer) error { attrStrings := g.attrStrings() return g.container.render(w, attrStrings) } // Circle represents a circle (the cirlc element). type Circle struct { ShapeAttrs Cx float64 `xml:"cx,attr"` Cy float64 `xml:"cy,attr"` R float64 `xml:"r,attr"` } func (c *Circle) attrStrings() []string { cx := floatAttr("cx", c.Cx) cy := floatAttr("cy", c.Cy) r := floatAttr("r", c.R) attrs := c.ShapeAttrs.attrStrings() attrs = append(attrs, cx, cy, r) return attrs } func (c *Circle) render(w io.Writer) error { attrStrings := c.attrStrings() attrString := strings.Join(attrStrings, " ") out := fmt.Sprintf("<circle %s/>", attrString) _, err := w.Write([]byte(out)) return err } // Ellipse represents an ellipse (the ellipse element). type Ellipse struct { ShapeAttrs Cx float64 Cy float64 Rx float64 Ry float64 } func (e *Ellipse) attrStrings() []string { cx := floatAttr("cx", e.Cx) cy := floatAttr("cy", e.Cy) rx := floatAttr("rx", e.Rx) ry := floatAttr("ry", e.Ry) attrs := e.ShapeAttrs.attrStrings() attrs = append(attrs, cx, cy, rx, ry) return attrs } func (e *Ellipse) render(w io.Writer) error { attrStrings := e.attrStrings() attrString := strings.Join(attrStrings, " ") out := fmt.Sprintf("<ellipse %s/>", attrString) _, err := w.Write([]byte(out)) return err } // Rect represents a rectangle (the rect element). type Rect struct { ShapeAttrs Width float64 Height float64 X float64 Y float64 } func (r *Rect) attrStrings() []string { w := floatAttr("width", r.Width) h := floatAttr("height", r.Height) x := floatAttr("x", r.X) y := floatAttr("y", r.Y) return append(r.ShapeAttrs.attrStrings(), w, h, x, y) } func (r *Rect) render(w io.Writer) error { attrStrings := r.attrStrings() attrString := strings.Join(attrStrings, " ") out := fmt.Sprintf("<rect %s/>", attrString) _, err := w.Write([]byte(out)) return err } // Point represents a Cartesian point. type Point struct { X float64 Y float64 } func (p Point) coordString() string { return fmt.Sprintf("%g,%g", p.X, p.Y) } // Polygon represents a closed, filled polygon (the polygon element). type Polygon struct { ShapeAttrs Points []Point } func (p *Polygon) attrStrings() []string { var pointStrs []string for _, pt := range p.Points { pointStrs = append(pointStrs, pt.coordString()) } pointStr := strings.Join(pointStrs, " ")
attrs := p.ShapeAttrs.attrStrings() pointAttr := stringAttr("points", pointStr) return append(attrs, pointAttr) } func (p *Polygon) render(w io.Writer) error { attrStrings := p.attrStrings() attrString := strings.Join(attrStrings, " ") tag := "polygon" out := fmt.Sprintf("<%s %s/>", tag, attrString) _, err := w.Write([]byte(out)) return err } // Polyline represents an open polygon rendered as line (the polyline element). type Polyline struct { ShapeAttrs Points []Point } func (p *Polyline) attrStrings() []string { var pointStrs []string for _, pt := range p.Points { pointStrs = append(pointStrs, pt.coordString()) } pointStr := strings.Join(pointStrs, " ") attrs := p.ShapeAttrs.attrStrings() pointAttr := stringAttr("points", pointStr) return append(attrs, pointAttr) } func (p *Polyline) render(w io.Writer) error { attrStrings := p.attrStrings() attrString := strings.Join(attrStrings, " ") tag := "polyline" out := fmt.Sprintf("<%s %s/>", tag, attrString) _, err := w.Write([]byte(out)) return err } // Line represents a straight line (the line element). type Line struct { ShapeAttrs X1 float64 X2 float64 Y1 float64 Y2 float64 } func (n *Line) attrStrings() []string { x1 := floatAttr("x1", n.X1) y1 := floatAttr("y1", n.Y1) x2 := floatAttr("x2", n.X2) y2 := floatAttr("y2", n.Y2) return append(n.ShapeAttrs.attrStrings(), x1, y1, x2, y2) } func (n *Line) render(w io.Writer) error { attrStrings := n.attrStrings() attrString := strings.Join(attrStrings, " ") tag := "line" out := fmt.Sprintf("<%s %s/>", tag, attrString) _, err := w.Write([]byte(out)) return err } // Path command declarations type cmdBody interface { strings() []string } type cmd struct { name string body cmdBody } type mCmd struct { pts []Point } func (m mCmd) strings() []string { var out []string for _, p := range m.pts { out = append(out, fmt.Sprintf("%g", p.X), fmt.Sprintf("%g", p.Y)) } return out } type zCmd struct { } func (z zCmd) strings() []string { return nil } // Don't want to use just lowercase L here type elCmd struct { pts []Point isAbs bool } func (e elCmd) strings() []string { var out []string for _, p := range e.pts { out = append(out, fmt.Sprintf("%g", p.X), fmt.Sprintf("%g", p.Y)) } return out } type hCmd struct { xs []float64 isAbs bool } func (h hCmd) strings() []string { var out []string for _, x := range h.xs { out = append(out, fmt.Sprintf("%g", x)) } return out } type vCmd struct { ys []float64 isAbs bool } func (v vCmd) strings() []string { var out []string for _, y := range v.ys { out = append(out, fmt.Sprintf("%g", y)) } return out } // CCurve represents a cubic Bezier curve. type CCurve struct { X1 float64 Y1 float64 X2 float64 Y2 float64 X float64 Y float64 } // SCurve represents a shorthand cubic Bezier curve. type SCurve struct { X2 float64 Y2 float64 X float64 Y float64 } // QCurve represents a quadratic Bezier curve. type QCurve struct { X1 float64 Y1 float64 X float64 Y float64 } type cCmd struct { cvs []CCurve isAbs bool } func (c cCmd) strings() []string { var out []string for _, cv := range c.cvs { out = append(out, fmt.Sprintf("%g", cv.X1), fmt.Sprintf("%g", cv.Y1), fmt.Sprintf("%g", cv.X2), fmt.Sprintf("%g", cv.Y2), fmt.Sprintf("%g", cv.X), fmt.Sprintf("%g", cv.Y)) } return out } type sCmd struct { cvs []SCurve isAbs bool } func (c sCmd) strings() []string { var out []string for _, cv := range c.cvs { out = append(out, fmt.Sprintf("%g", cv.X2), fmt.Sprintf("%g", cv.Y2), fmt.Sprintf("%g", cv.X), fmt.Sprintf("%g", cv.Y)) } return out } type qCmd struct { cvs []QCurve isAbs bool } func (c qCmd) strings() []string { var out []string for _, cv := range c.cvs { out = append(out, fmt.Sprintf("%g", cv.X1), fmt.Sprintf("%g", cv.Y1), fmt.Sprintf("%g", cv.X), fmt.Sprintf("%g", cv.Y)) } return out } type tCmd struct { pts []Point isAbs bool } func (c tCmd) strings() []string { var out []string for _, pt := range c.pts { out = append(out, fmt.Sprintf("%g", pt.X), fmt.Sprintf("%g", pt.Y)) } return out } // Path represents a path through a given coordinate system (the path element). type Path struct { ShapeAttrs d []cmd PathLength float64 } func (p *Path) addCmd(name string, body cmdBody) *Path { p.d = append(p.d, cmd{name: name, body: body}) return p } // Ma appends an absolute moveto command to the path. func (p *Path) Ma(pts ...Point) *Path { return p.addCmd("M", mCmd{pts: pts}) } // Mr appends a relative moveto command to the path. func (p *Path) Mr(pts ...Point) *Path { return p.addCmd("m", mCmd{pts: pts}) } // Z adds a closepath command to the path. func (p *Path) Z() *Path { return p.addCmd("z", zCmd{}) } // La appends an absolute lineto command to the path. func (p *Path) La(pts ...Point) *Path { return p.addCmd("L", elCmd{pts: pts}) } // Lr appends a relative lineto command to the path. func (p *Path) Lr(pts ...Point) *Path { return p.addCmd("l", elCmd{pts: pts}) } // Ha appends an absolute horizontal lineto command to the path. func (p *Path) Ha(xs ...float64) *Path { return p.addCmd("H", hCmd{xs: xs}) } // Hr appends a relative horizontal lineto command to the path. func (p *Path) Hr(xs ...float64) *Path { return p.addCmd("h", hCmd{xs: xs}) } // Va appends an absolute vertical lineto command to the path. func (p *Path) Va(ys ...float64) *Path { return p.addCmd("V", vCmd{ys: ys}) } // Vr appends a relative vertical lineto command to the path. func (p *Path) Vr(ys ...float64) *Path { return p.addCmd("v", vCmd{ys: ys}) } // Ca appends an absolute curveto command to the path. func (p *Path) Ca(cvs ...CCurve) *Path { return p.addCmd("C", cCmd{cvs: cvs}) } // Cr appends a relative curveto command to the path. func (p *Path) Cr(cvs ...CCurve) *Path { return p.addCmd("c", cCmd{cvs: cvs}) } // Sa appends an absolute shorthand/smooth curveto command to the path. func (p *Path) Sa(cvs ...SCurve) *Path { return p.addCmd("S", sCmd{cvs: cvs}) } // Sr appends a relative shorthand/smooth curveto command to the path. func (p *Path) Sr(cvs ...SCurve) *Path { return p.addCmd("s", sCmd{cvs: cvs}) } // Qa appends an absolute quadratic Bezier curveto command to the path. func (p *Path) Qa(cvs ...QCurve) *Path { return p.addCmd("Q", qCmd{cvs: cvs}) } // Qr appends a relative quadratic Bezier curveto command to the path. func (p *Path) Qr(cvs ...QCurve) *Path { return p.addCmd("q", qCmd{cvs: cvs}) } // Ta appends an absolute shorthand/smooth quadratic Bezier curveto command to the path. func (p *Path) Ta(cvs ...Point) *Path { return p.addCmd("T", tCmd{pts: cvs}) } // Tr appends a relative shorthand/smooth quadratic Bezier curveto command to the path. func (p *Path) Tr(cvs ...Point) *Path { return p.addCmd("t", tCmd{pts: cvs}) } func (p *Path) pathStr() string { var outs []string accumLen := 0 for _, cmd := range p.d { accumLen++ if accumLen > 255 { outs = append(outs, "\n", cmd.name) accumLen = 0 } else { outs = append(outs, " ", cmd.name) } bodyStrs := cmd.body.strings() for _, s := range bodyStrs { accumLen += len(s) if accumLen > 255 { outs = append(outs, "\n", s) accumLen = 0 } else { outs = append(outs, " ", s) } } } if len(outs) > 0 { outs = outs[1:] } out := strings.Join(outs, "") return out } func (p *Path) attrStrings() []string { pathStr := p.pathStr() pathAttr := stringAttr("d", pathStr) attrs := p.ShapeAttrs.attrStrings() return append(attrs, pathAttr) } func (p *Path) render(w io.Writer) error { attrStrings := p.attrStrings() attrString := strings.Join(attrStrings, " ") tag := "path" out := fmt.Sprintf("<%s %s/>", tag, attrString) _, err := w.Write([]byte(out)) return err }
logger.go
package jarvisbase import ( "fmt" "os" "path" "path/filepath" "sync" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var logger *zap.Logger var onceLogger sync.Once var logPath string // var curtime int64 var panicFile *os.File var logSubName string func initLogger(level zapcore.Level, isConsole bool, logpath string, subName string) (*zap.Logger, error) { logSubName = subName // curtime = time.Now().Unix() logPath = logpath loglevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { return lvl >= level }) if isConsole
cfg := &zap.Config{} cfg.Level = zap.NewAtomicLevelAt(level) cfg.OutputPaths = []string{path.Join(logpath, BuildLogFilename("output", logSubName))} cfg.ErrorOutputPaths = []string{path.Join(logpath, BuildLogFilename("error", logSubName))} cfg.Encoding = "json" cfg.EncoderConfig = zapcore.EncoderConfig{ TimeKey: "T", LevelKey: "L", EncodeLevel: zapcore.CapitalLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, MessageKey: "msg", } cl, err := cfg.Build() if err != nil { return nil, err } err = initPanicFile() if err != nil { return nil, err } return cl, nil } // InitLogger - initializes a thread-safe singleton logger func InitLogger(level zapcore.Level, isConsole bool, logpath string, nodeType string) { // once ensures the singleton is initialized only once onceLogger.Do(func() { cl, err := initLogger(level, isConsole, logpath, nodeType) if err != nil { fmt.Printf("initLogger error! %v \n", err) os.Exit(-1) } logger = cl }) return } // // Log a message at the given level with given fields // func Log(level zap.Level, message string, fields ...zap.Field) { // singleton.Log(level, message, fields...) // } // Debug logs a debug message with the given fields func Debug(message string, fields ...zap.Field) { if logger == nil { return } logger.Debug(message, fields...) } // Info logs a debug message with the given fields func Info(message string, fields ...zap.Field) { if logger == nil { return } logger.Info(message, fields...) } // Warn logs a debug message with the given fields func Warn(message string, fields ...zap.Field) { if logger == nil { return } logger.Warn(message, fields...) } // Error logs a debug message with the given fields func Error(message string, fields ...zap.Field) { if logger == nil { return } logger.Error(message, fields...) } // Fatal logs a message than calls os.Exit(1) func Fatal(message string, fields ...zap.Field) { if logger == nil { return } logger.Fatal(message, fields...) } // SyncLogger - sync logger func SyncLogger() { logger.Sync() } // ClearLogs - clear logs func ClearLogs() error { if logPath != "" { fn := path.Join(logPath, "*.log") lst, err := filepath.Glob(fn) if err != nil { return err } panicfile := BuildLogFilename("panic", logSubName) outputfile := BuildLogFilename("output", logSubName) errorfile := BuildLogFilename("error", logSubName) for _, v := range lst { cfn := filepath.Base(v) if cfn != panicfile && cfn != outputfile && cfn != errorfile { os.Remove(v) } } } return nil }
{ consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()) consoleDebugging := zapcore.Lock(os.Stdout) core := zapcore.NewTee( zapcore.NewCore(consoleEncoder, consoleDebugging, loglevel), ) cl := zap.New(core) // defer cl.Sync() return cl, nil }
rate_test.go
package ros import ( "math/rand" "testing" "time" ) func TestNewRate(t *testing.T) { r := NewRate(100) if !r.actualCycleTime.IsZero() { t.Fail() } if r.expectedCycleTime.ToSec() != 0.01 { t.Fail() } } func TestCycleTime(t *testing.T) { const MeasureTolerance int64 = 1000000 var d Duration d.FromSec(0.01) r := CycleTime(d) if !r.actualCycleTime.IsZero() { t.Fail() } if r.expectedCycleTime.ToSec() != 0.01 { t.Fail() } start := time.Now().UnixNano() r.Sleep() end := time.Now().UnixNano() actual := r.CycleTime() elapsed := end - start delta := int64(actual.ToNSec()) - elapsed if delta < 0 { delta = -delta } if delta > MeasureTolerance { t.Error(delta) } } func TestRateReset(t *testing.T) { r := NewRate(100) r.Sleep() if r.actualCycleTime.IsZero() { t.Fail() } r.Reset() if !r.actualCycleTime.IsZero() { t.Fail() } } func TestRateSleep(t *testing.T)
{ // The jitter tolerance (5msec) doesn't have strong basis. const JitterTolerance int64 = 5000000 ct := NewDuration(0, 100000000) // 10msec r := CycleTime(ct) if ct.Cmp(r.ExpectedCycleTime()) != 0 { t.Fail() } for i := 0; i < 10; i++ { start := time.Now().UnixNano() time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond) r.Sleep() end := time.Now().UnixNano() elapsed := end - start delta := elapsed - int64(ct.ToNSec()) if delta < 0 { delta = -delta } if delta > JitterTolerance { actual := r.CycleTime() t.Errorf("expected: %d actual: %d measured: %d delta: %d", ct.ToNSec(), actual.ToNSec(), elapsed, delta) } } }
u256.rs
use std::cmp::Ordering; use std::ops::*; #[derive(Eq, PartialEq, Debug, Copy, Clone, Default)] struct U256 { h: u128, l: u128, } impl U256 { // pub fn pow(self, n: Self) -> Self { // let mut res = self; // while n > 0 { // res *= res; // } // res // } pub fn from_bytes(bytes: [u8; 32]) -> Self { let mut h = [0u8; 16]; let mut l = [0u8; 16]; h.copy_from_slice(&bytes[0..16]); l.copy_from_slice(&bytes[16..32]); U256 { h: u128::from_be_bytes(h), l: u128::from_be_bytes(l) } } pub fn into_be_bytes(self) -> [u8; 32] { let mut res = [0u8; 32]; res[0..16].copy_from_slice(dbg!(&self.h.to_be_bytes())); res[16..32].copy_from_slice(dbg!(&self.l.to_be_bytes())); res } pub fn to_be_bytes(&self) -> [u8; 32] { let mut res = [0u8; 32]; res[0..16].copy_from_slice(&self.h.to_be_bytes()); res[16..32].copy_from_slice(&self.l.to_be_bytes()); res } // pub fn mul_u64(mut self, other: u64) -> U256 { // let mut ret = U256::default(); // { // let (mut lower_h, mut lower_l) = split(self.l); // // lower_l *= other as u128; // lower_h *= other as u128; // self.h += split(lower_h).0; // ret += lower_l; // ret += lower_h << 64; // } // // let (mut higher_h, mut higher_l) = split(self.h); // // higher_l *= other as u128; // higher_h *= other as u128; // ret += higher_l; // ret += higher_h << 64; // ret // } } impl PartialOrd for U256 { fn partial_cmp(&self, other: &U256) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for U256 { fn cmp(&self, other: &U256) -> Ordering { let high_order = self.h.cmp(&other.h); match high_order { Ordering::Equal => self.l.cmp(&other.l), Ordering::Greater | Ordering::Less => high_order, } } } macro_rules! impl_from_less_than_128 { ($($t:ty),*) => {$( impl From<$t> for U256 { fn from(l: $t) -> Self { U256 { l: l as u128, h: 0, } } } )+} } macro_rules! ops_less_than_128 { ($($t:ty),*) => {$( impl Add<$t> for U256 { type Output = U256; #[inline(always)] fn add(self, other: $t) -> U256 { let a = &self; let b = &U256::from(other); a + b } } impl Add<U256> for $t { type Output = U256; #[inline(always)] fn add(self, other: U256) -> U256 { let a = &U256::from(self); let b = &other; a + b } } impl Add<&U256> for $t { type Output = U256; #[inline(always)] fn add(self, other: &U256) -> U256 { let a = U256::from(self); let b = other; a + b } } impl AddAssign<$t> for U256 { fn add_assign(&mut self, other: $t) { let me = *self; *self = me + other; } } impl AddAssign<&$t> for U256 { fn add_assign(&mut self, other: &$t) { let me = *self; *self = me + *other; } } )+} } impl_from_less_than_128! { u128, u64, u32, u16, u8 } ops_less_than_128! { u128, u64, u32, u16, u8 } macro_rules! reg_ops { ($Lhs:ty, $Rhs:ty) => { impl Add<$Rhs> for $Lhs { type Output = U256; #[inline(always)] fn add(self, other: $Rhs) -> U256 { let a = &self; let b = &other; let mut res = U256::default(); let (res0, is_overflown) = dbg!(a.l.overflowing_add(b.l)); res.l = res0; res.h += is_overflown as u128; res.h += a.h + b.h; res } } #[allow(clippy::suspicious_arithmetic_impl)] impl Mul<$Rhs> for $Lhs { type Output = U256; #[inline(always)] fn mul(self, other: $Rhs) -> U256 { let (ref a, ref b) = (self, other); let mut low: U256; // let mut high: U256 = U256::default(); low = mul_u128(a.l, b.l); let al_bh = mul_u128(a.l, b.h); let ah_bl = mul_u128(a.h, b.l); low.h += al_bh.l + ah_bl.l; // high.l += al_bh.h + ah_bl.h; // high = high + mul(a.h, b.h); low } } }; } macro_rules! assign_ops { ($Lhs:ty, $Rhs:ty) => { impl AddAssign<$Rhs> for $Lhs { fn add_assign(&mut self, other: $Rhs) { let me = *self; *self = me + other; } } impl MulAssign<$Rhs> for $Lhs { fn mul_assign(&mut self, other: $Rhs) { let me = *self; *self = me * other; } } }; } reg_ops! {U256, U256} reg_ops! {U256, &U256} reg_ops! {&U256, U256} reg_ops! {&U256, &U256} assign_ops! {U256, U256} assign_ops! {U256, &U256} fn mul_u128(a: u128, b: u128) -> U256 { let mut res = U256::default(); let (a_h, a_l) = dbg!(split(a)); let (b_h, b_l) = dbg!(split(b)); res.l = a_l * b_l; res += (a_l * b_h) << 64; res += (a_h * b_l) << 64; if a_h == 0 || b_h == 0 { res.h += a_h + b_h; } else { res.h += a_h * b_h; } res } fn split(input: u128) -> (u128, u128) { let l: u128 = input as u64 as u128; let h: u128 = (input >> 64) as u64 as u128; (h, l) } #[cfg(test)] mod tests { use super::*; use numext_fixed_uint::U256 as T_U256; use rand::{thread_rng, Rng}; #[test] fn test_from_to() { let mut rng = thread_rng(); for _ in 0..15 { let bytes: [u8; 32] = rng.gen(); let u256 = U256::from_bytes(bytes); assert_eq!(bytes, u256.into_be_bytes()); } } #[test] fn test_be() { let mut rng = thread_rng(); let num: u128 = rng.gen(); let (my, test) = get_uints(num); assert_eq!(test.to_be_bytes(), my.into_be_bytes()); } #[test] #[ignore] fn
() { let mut rng = thread_rng(); let a: u128 = rng.gen(); let b = u64::max_value() as u128; let (a_my, a_test) = get_uints(a); let (b_my, b_test) = get_uints(b); dbg!(a); dbg!(b); let my = a_my * b_my; let test = a_test * b_test; dbg!(&my); dbg!(&test); assert_eq!(test.to_be_bytes(), my.into_be_bytes()); } #[test] #[ignore] fn test_specific() { let real_be = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 187, 38, 228, 19, 155, 141, 172, 191, 166, 217, 27, 236, 100, 114, 83, 63, 158, ]; let a = 3452343528210635210850_u128; let b = 18446744073709551615_u128; let res = mul_u128(a, b); assert_eq!(res.into_be_bytes(), real_be); } #[test] #[ignore] fn test_other_specific() { let real_be = [ 0, 0, 0, 0, 0, 0, 0, 0, 205, 24, 175, 194, 81, 32, 160, 12, 252, 10, 19, 243, 165, 227, 59, 3, 54, 221, 60, 74, 8, 252, 36, 239, ]; let a = 272619919077564483872665775724761963281_u128; let b = 18446744073709551615_u128; let res = mul_u128(a, b); assert_eq!(res.into_be_bytes(), real_be); } fn slice_to_u128(s: &[u8]) -> u128 { let mut shit = [0u8; 16]; shit.copy_from_slice(s); u128::from_be_bytes(shit) } fn get_uints(num: u128) -> (U256, T_U256) { (U256::from(num), T_U256::from(num)) } }
test_be_mul
cloud_speech.pb.go
// Copyright 2019 Google LLC. // // 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 protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.12.2 // source: google/cloud/speech/v1/cloud_speech.proto package speech import ( context "context" reflect "reflect" sync "sync" _ "google.golang.org/genproto/googleapis/api/annotations" longrunning "google.golang.org/genproto/googleapis/longrunning" status "google.golang.org/genproto/googleapis/rpc/status" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status1 "google.golang.org/grpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" _ "google.golang.org/protobuf/types/known/anypb" durationpb "google.golang.org/protobuf/types/known/durationpb" timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // The encoding of the audio data sent in the request. // // All encodings support only 1 channel (mono) audio, unless the // `audio_channel_count` and `enable_separate_recognition_per_channel` fields // are set. // // For best results, the audio source should be captured and transmitted using // a lossless encoding (`FLAC` or `LINEAR16`). The accuracy of the speech // recognition can be reduced if lossy codecs are used to capture or transmit // audio, particularly if background noise is present. Lossy codecs include // `MULAW`, `AMR`, `AMR_WB`, `OGG_OPUS`, `SPEEX_WITH_HEADER_BYTE`, and `MP3`. // // The `FLAC` and `WAV` audio file formats include a header that describes the // included audio content. You can request recognition for `WAV` files that // contain either `LINEAR16` or `MULAW` encoded audio. // If you send `FLAC` or `WAV` audio file format in // your request, you do not need to specify an `AudioEncoding`; the audio // encoding format is determined from the file header. If you specify // an `AudioEncoding` when you send send `FLAC` or `WAV` audio, the // encoding configuration must match the encoding described in the audio // header; otherwise the request returns an // [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] error code. type RecognitionConfig_AudioEncoding int32 const ( // Not specified. RecognitionConfig_ENCODING_UNSPECIFIED RecognitionConfig_AudioEncoding = 0 // Uncompressed 16-bit signed little-endian samples (Linear PCM). RecognitionConfig_LINEAR16 RecognitionConfig_AudioEncoding = 1 // `FLAC` (Free Lossless Audio // Codec) is the recommended encoding because it is // lossless--therefore recognition is not compromised--and // requires only about half the bandwidth of `LINEAR16`. `FLAC` stream // encoding supports 16-bit and 24-bit samples, however, not all fields in // `STREAMINFO` are supported. RecognitionConfig_FLAC RecognitionConfig_AudioEncoding = 2 // 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. RecognitionConfig_MULAW RecognitionConfig_AudioEncoding = 3 // Adaptive Multi-Rate Narrowband codec. `sample_rate_hertz` must be 8000. RecognitionConfig_AMR RecognitionConfig_AudioEncoding = 4 // Adaptive Multi-Rate Wideband codec. `sample_rate_hertz` must be 16000. RecognitionConfig_AMR_WB RecognitionConfig_AudioEncoding = 5 // Opus encoded audio frames in Ogg container // ([OggOpus](https://wiki.xiph.org/OggOpus)). // `sample_rate_hertz` must be one of 8000, 12000, 16000, 24000, or 48000. RecognitionConfig_OGG_OPUS RecognitionConfig_AudioEncoding = 6 // Although the use of lossy encodings is not recommended, if a very low // bitrate encoding is required, `OGG_OPUS` is highly preferred over // Speex encoding. The [Speex](https://speex.org/) encoding supported by // Cloud Speech API has a header byte in each block, as in MIME type // `audio/x-speex-with-header-byte`. // It is a variant of the RTP Speex encoding defined in // [RFC 5574](https://tools.ietf.org/html/rfc5574). // The stream is a sequence of blocks, one block per RTP packet. Each block // starts with a byte containing the length of the block, in bytes, followed // by one or more frames of Speex data, padded to an integral number of // bytes (octets) as specified in RFC 5574. In other words, each RTP header // is replaced with a single byte containing the block length. Only Speex // wideband is supported. `sample_rate_hertz` must be 16000. RecognitionConfig_SPEEX_WITH_HEADER_BYTE RecognitionConfig_AudioEncoding = 7 ) // Enum value maps for RecognitionConfig_AudioEncoding. var ( RecognitionConfig_AudioEncoding_name = map[int32]string{ 0: "ENCODING_UNSPECIFIED", 1: "LINEAR16", 2: "FLAC", 3: "MULAW", 4: "AMR", 5: "AMR_WB", 6: "OGG_OPUS", 7: "SPEEX_WITH_HEADER_BYTE", } RecognitionConfig_AudioEncoding_value = map[string]int32{ "ENCODING_UNSPECIFIED": 0, "LINEAR16": 1, "FLAC": 2, "MULAW": 3, "AMR": 4, "AMR_WB": 5, "OGG_OPUS": 6, "SPEEX_WITH_HEADER_BYTE": 7, } ) func (x RecognitionConfig_AudioEncoding) Enum() *RecognitionConfig_AudioEncoding { p := new(RecognitionConfig_AudioEncoding) *p = x return p } func (x RecognitionConfig_AudioEncoding) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RecognitionConfig_AudioEncoding) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[0].Descriptor() } func (RecognitionConfig_AudioEncoding) Type() protoreflect.EnumType { return &file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[0] } func (x RecognitionConfig_AudioEncoding) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RecognitionConfig_AudioEncoding.Descriptor instead. func (RecognitionConfig_AudioEncoding) EnumDescriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{4, 0} } // Use case categories that the audio recognition request can be described // by. type RecognitionMetadata_InteractionType int32 const ( // Use case is either unknown or is something other than one of the other // values below. RecognitionMetadata_INTERACTION_TYPE_UNSPECIFIED RecognitionMetadata_InteractionType = 0 // Multiple people in a conversation or discussion. For example in a // meeting with two or more people actively participating. Typically // all the primary people speaking would be in the same room (if not, // see PHONE_CALL) RecognitionMetadata_DISCUSSION RecognitionMetadata_InteractionType = 1 // One or more persons lecturing or presenting to others, mostly // uninterrupted. RecognitionMetadata_PRESENTATION RecognitionMetadata_InteractionType = 2 // A phone-call or video-conference in which two or more people, who are // not in the same room, are actively participating. RecognitionMetadata_PHONE_CALL RecognitionMetadata_InteractionType = 3 // A recorded message intended for another person to listen to. RecognitionMetadata_VOICEMAIL RecognitionMetadata_InteractionType = 4 // Professionally produced audio (eg. TV Show, Podcast). RecognitionMetadata_PROFESSIONALLY_PRODUCED RecognitionMetadata_InteractionType = 5 // Transcribe spoken questions and queries into text. RecognitionMetadata_VOICE_SEARCH RecognitionMetadata_InteractionType = 6 // Transcribe voice commands, such as for controlling a device. RecognitionMetadata_VOICE_COMMAND RecognitionMetadata_InteractionType = 7 // Transcribe speech to text to create a written document, such as a // text-message, email or report. RecognitionMetadata_DICTATION RecognitionMetadata_InteractionType = 8 ) // Enum value maps for RecognitionMetadata_InteractionType. var ( RecognitionMetadata_InteractionType_name = map[int32]string{ 0: "INTERACTION_TYPE_UNSPECIFIED", 1: "DISCUSSION", 2: "PRESENTATION", 3: "PHONE_CALL", 4: "VOICEMAIL", 5: "PROFESSIONALLY_PRODUCED", 6: "VOICE_SEARCH", 7: "VOICE_COMMAND", 8: "DICTATION", } RecognitionMetadata_InteractionType_value = map[string]int32{ "INTERACTION_TYPE_UNSPECIFIED": 0, "DISCUSSION": 1, "PRESENTATION": 2, "PHONE_CALL": 3, "VOICEMAIL": 4, "PROFESSIONALLY_PRODUCED": 5, "VOICE_SEARCH": 6, "VOICE_COMMAND": 7, "DICTATION": 8, } ) func (x RecognitionMetadata_InteractionType) Enum() *RecognitionMetadata_InteractionType { p := new(RecognitionMetadata_InteractionType) *p = x return p } func (x RecognitionMetadata_InteractionType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RecognitionMetadata_InteractionType) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[1].Descriptor() } func (RecognitionMetadata_InteractionType) Type() protoreflect.EnumType { return &file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[1] } func (x RecognitionMetadata_InteractionType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RecognitionMetadata_InteractionType.Descriptor instead. func (RecognitionMetadata_InteractionType) EnumDescriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{6, 0} } // Enumerates the types of capture settings describing an audio file. type RecognitionMetadata_MicrophoneDistance int32 const ( // Audio type is not known. RecognitionMetadata_MICROPHONE_DISTANCE_UNSPECIFIED RecognitionMetadata_MicrophoneDistance = 0 // The audio was captured from a closely placed microphone. Eg. phone, // dictaphone, or handheld microphone. Generally if there speaker is within // 1 meter of the microphone. RecognitionMetadata_NEARFIELD RecognitionMetadata_MicrophoneDistance = 1 // The speaker if within 3 meters of the microphone. RecognitionMetadata_MIDFIELD RecognitionMetadata_MicrophoneDistance = 2 // The speaker is more than 3 meters away from the microphone. RecognitionMetadata_FARFIELD RecognitionMetadata_MicrophoneDistance = 3 ) // Enum value maps for RecognitionMetadata_MicrophoneDistance. var ( RecognitionMetadata_MicrophoneDistance_name = map[int32]string{ 0: "MICROPHONE_DISTANCE_UNSPECIFIED", 1: "NEARFIELD", 2: "MIDFIELD", 3: "FARFIELD", } RecognitionMetadata_MicrophoneDistance_value = map[string]int32{ "MICROPHONE_DISTANCE_UNSPECIFIED": 0, "NEARFIELD": 1, "MIDFIELD": 2, "FARFIELD": 3, } ) func (x RecognitionMetadata_MicrophoneDistance) Enum() *RecognitionMetadata_MicrophoneDistance { p := new(RecognitionMetadata_MicrophoneDistance) *p = x return p } func (x RecognitionMetadata_MicrophoneDistance) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RecognitionMetadata_MicrophoneDistance) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[2].Descriptor() } func (RecognitionMetadata_MicrophoneDistance) Type() protoreflect.EnumType { return &file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[2] } func (x RecognitionMetadata_MicrophoneDistance) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RecognitionMetadata_MicrophoneDistance.Descriptor instead. func (RecognitionMetadata_MicrophoneDistance) EnumDescriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{6, 1} } // The original media the speech was recorded on. type RecognitionMetadata_OriginalMediaType int32 const ( // Unknown original media type. RecognitionMetadata_ORIGINAL_MEDIA_TYPE_UNSPECIFIED RecognitionMetadata_OriginalMediaType = 0 // The speech data is an audio recording. RecognitionMetadata_AUDIO RecognitionMetadata_OriginalMediaType = 1 // The speech data originally recorded on a video. RecognitionMetadata_VIDEO RecognitionMetadata_OriginalMediaType = 2 ) // Enum value maps for RecognitionMetadata_OriginalMediaType. var ( RecognitionMetadata_OriginalMediaType_name = map[int32]string{ 0: "ORIGINAL_MEDIA_TYPE_UNSPECIFIED", 1: "AUDIO", 2: "VIDEO", } RecognitionMetadata_OriginalMediaType_value = map[string]int32{ "ORIGINAL_MEDIA_TYPE_UNSPECIFIED": 0, "AUDIO": 1, "VIDEO": 2, } ) func (x RecognitionMetadata_OriginalMediaType) Enum() *RecognitionMetadata_OriginalMediaType { p := new(RecognitionMetadata_OriginalMediaType) *p = x return p } func (x RecognitionMetadata_OriginalMediaType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RecognitionMetadata_OriginalMediaType) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[3].Descriptor() } func (RecognitionMetadata_OriginalMediaType) Type() protoreflect.EnumType { return &file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[3] } func (x RecognitionMetadata_OriginalMediaType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RecognitionMetadata_OriginalMediaType.Descriptor instead. func (RecognitionMetadata_OriginalMediaType) EnumDescriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{6, 2} } // The type of device the speech was recorded with. type RecognitionMetadata_RecordingDeviceType int32 const ( // The recording device is unknown. RecognitionMetadata_RECORDING_DEVICE_TYPE_UNSPECIFIED RecognitionMetadata_RecordingDeviceType = 0 // Speech was recorded on a smartphone. RecognitionMetadata_SMARTPHONE RecognitionMetadata_RecordingDeviceType = 1 // Speech was recorded using a personal computer or tablet. RecognitionMetadata_PC RecognitionMetadata_RecordingDeviceType = 2 // Speech was recorded over a phone line. RecognitionMetadata_PHONE_LINE RecognitionMetadata_RecordingDeviceType = 3 // Speech was recorded in a vehicle. RecognitionMetadata_VEHICLE RecognitionMetadata_RecordingDeviceType = 4 // Speech was recorded outdoors. RecognitionMetadata_OTHER_OUTDOOR_DEVICE RecognitionMetadata_RecordingDeviceType = 5 // Speech was recorded indoors. RecognitionMetadata_OTHER_INDOOR_DEVICE RecognitionMetadata_RecordingDeviceType = 6 ) // Enum value maps for RecognitionMetadata_RecordingDeviceType. var ( RecognitionMetadata_RecordingDeviceType_name = map[int32]string{ 0: "RECORDING_DEVICE_TYPE_UNSPECIFIED", 1: "SMARTPHONE", 2: "PC", 3: "PHONE_LINE", 4: "VEHICLE", 5: "OTHER_OUTDOOR_DEVICE", 6: "OTHER_INDOOR_DEVICE", } RecognitionMetadata_RecordingDeviceType_value = map[string]int32{ "RECORDING_DEVICE_TYPE_UNSPECIFIED": 0, "SMARTPHONE": 1, "PC": 2, "PHONE_LINE": 3, "VEHICLE": 4, "OTHER_OUTDOOR_DEVICE": 5, "OTHER_INDOOR_DEVICE": 6, } ) func (x RecognitionMetadata_RecordingDeviceType) Enum() *RecognitionMetadata_RecordingDeviceType { p := new(RecognitionMetadata_RecordingDeviceType) *p = x return p } func (x RecognitionMetadata_RecordingDeviceType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (RecognitionMetadata_RecordingDeviceType) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[4].Descriptor() } func (RecognitionMetadata_RecordingDeviceType) Type() protoreflect.EnumType { return &file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[4] } func (x RecognitionMetadata_RecordingDeviceType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use RecognitionMetadata_RecordingDeviceType.Descriptor instead. func (RecognitionMetadata_RecordingDeviceType) EnumDescriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{6, 3} } // Indicates the type of speech event. type StreamingRecognizeResponse_SpeechEventType int32 const ( // No speech event specified. StreamingRecognizeResponse_SPEECH_EVENT_UNSPECIFIED StreamingRecognizeResponse_SpeechEventType = 0 // This event indicates that the server has detected the end of the user's // speech utterance and expects no additional speech. Therefore, the server // will not process additional audio (although it may subsequently return // additional results). The client should stop sending additional audio // data, half-close the gRPC connection, and wait for any additional results // until the server closes the gRPC connection. This event is only sent if // `single_utterance` was set to `true`, and is not used otherwise. StreamingRecognizeResponse_END_OF_SINGLE_UTTERANCE StreamingRecognizeResponse_SpeechEventType = 1 ) // Enum value maps for StreamingRecognizeResponse_SpeechEventType. var ( StreamingRecognizeResponse_SpeechEventType_name = map[int32]string{ 0: "SPEECH_EVENT_UNSPECIFIED", 1: "END_OF_SINGLE_UTTERANCE", } StreamingRecognizeResponse_SpeechEventType_value = map[string]int32{ "SPEECH_EVENT_UNSPECIFIED": 0, "END_OF_SINGLE_UTTERANCE": 1, } ) func (x StreamingRecognizeResponse_SpeechEventType) Enum() *StreamingRecognizeResponse_SpeechEventType { p := new(StreamingRecognizeResponse_SpeechEventType) *p = x return p } func (x StreamingRecognizeResponse_SpeechEventType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (StreamingRecognizeResponse_SpeechEventType) Descriptor() protoreflect.EnumDescriptor { return file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[5].Descriptor() } func (StreamingRecognizeResponse_SpeechEventType) Type() protoreflect.EnumType { return &file_google_cloud_speech_v1_cloud_speech_proto_enumTypes[5] } func (x StreamingRecognizeResponse_SpeechEventType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use StreamingRecognizeResponse_SpeechEventType.Descriptor instead. func (StreamingRecognizeResponse_SpeechEventType) EnumDescriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{12, 0} } // The top-level message sent by the client for the `Recognize` method. type RecognizeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. Provides information to the recognizer that specifies how to // process the request. Config *RecognitionConfig `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` // Required. The audio data to be recognized. Audio *RecognitionAudio `protobuf:"bytes,2,opt,name=audio,proto3" json:"audio,omitempty"` } func (x *RecognizeRequest) Reset() { *x = RecognizeRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RecognizeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*RecognizeRequest) ProtoMessage() {} func (x *RecognizeRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RecognizeRequest.ProtoReflect.Descriptor instead. func (*RecognizeRequest) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{0} } func (x *RecognizeRequest) GetConfig() *RecognitionConfig { if x != nil { return x.Config } return nil } func (x *RecognizeRequest) GetAudio() *RecognitionAudio { if x != nil { return x.Audio } return nil } // The top-level message sent by the client for the `LongRunningRecognize` // method. type LongRunningRecognizeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. Provides information to the recognizer that specifies how to // process the request. Config *RecognitionConfig `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` // Required. The audio data to be recognized. Audio *RecognitionAudio `protobuf:"bytes,2,opt,name=audio,proto3" json:"audio,omitempty"` } func (x *LongRunningRecognizeRequest) Reset() { *x = LongRunningRecognizeRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *LongRunningRecognizeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*LongRunningRecognizeRequest) ProtoMessage() {} func (x *LongRunningRecognizeRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LongRunningRecognizeRequest.ProtoReflect.Descriptor instead. func (*LongRunningRecognizeRequest) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{1} } func (x *LongRunningRecognizeRequest) GetConfig() *RecognitionConfig { if x != nil { return x.Config } return nil } func (x *LongRunningRecognizeRequest) GetAudio() *RecognitionAudio { if x != nil { return x.Audio } return nil } // The top-level message sent by the client for the `StreamingRecognize` method. // Multiple `StreamingRecognizeRequest` messages are sent. The first message // must contain a `streaming_config` message and must not contain // `audio_content`. All subsequent messages must contain `audio_content` and // must not contain a `streaming_config` message. type StreamingRecognizeRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The streaming request, which is either a streaming config or audio content. // // Types that are assignable to StreamingRequest: // *StreamingRecognizeRequest_StreamingConfig // *StreamingRecognizeRequest_AudioContent StreamingRequest isStreamingRecognizeRequest_StreamingRequest `protobuf_oneof:"streaming_request"` } func (x *StreamingRecognizeRequest) Reset() { *x = StreamingRecognizeRequest{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *StreamingRecognizeRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*StreamingRecognizeRequest) ProtoMessage() {} func (x *StreamingRecognizeRequest) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StreamingRecognizeRequest.ProtoReflect.Descriptor instead. func (*StreamingRecognizeRequest) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{2} } func (m *StreamingRecognizeRequest) GetStreamingRequest() isStreamingRecognizeRequest_StreamingRequest { if m != nil { return m.StreamingRequest } return nil } func (x *StreamingRecognizeRequest) GetStreamingConfig() *StreamingRecognitionConfig { if x, ok := x.GetStreamingRequest().(*StreamingRecognizeRequest_StreamingConfig); ok { return x.StreamingConfig } return nil } func (x *StreamingRecognizeRequest) GetAudioContent() []byte { if x, ok := x.GetStreamingRequest().(*StreamingRecognizeRequest_AudioContent); ok { return x.AudioContent } return nil } type isStreamingRecognizeRequest_StreamingRequest interface { isStreamingRecognizeRequest_StreamingRequest() } type StreamingRecognizeRequest_StreamingConfig struct { // Provides information to the recognizer that specifies how to process the // request. The first `StreamingRecognizeRequest` message must contain a // `streaming_config` message. StreamingConfig *StreamingRecognitionConfig `protobuf:"bytes,1,opt,name=streaming_config,json=streamingConfig,proto3,oneof"` } type StreamingRecognizeRequest_AudioContent struct { // The audio data to be recognized. Sequential chunks of audio data are sent // in sequential `StreamingRecognizeRequest` messages. The first // `StreamingRecognizeRequest` message must not contain `audio_content` data // and all subsequent `StreamingRecognizeRequest` messages must contain // `audio_content` data. The audio bytes must be encoded as specified in // `RecognitionConfig`. Note: as with all bytes fields, proto buffers use a // pure binary representation (not base64). See // [content limits](https://cloud.google.com/speech-to-text/quotas#content). AudioContent []byte `protobuf:"bytes,2,opt,name=audio_content,json=audioContent,proto3,oneof"` } func (*StreamingRecognizeRequest_StreamingConfig) isStreamingRecognizeRequest_StreamingRequest() {} func (*StreamingRecognizeRequest_AudioContent) isStreamingRecognizeRequest_StreamingRequest() {} // Provides information to the recognizer that specifies how to process the // request. type StreamingRecognitionConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required. Provides information to the recognizer that specifies how to // process the request. Config *RecognitionConfig `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` // If `false` or omitted, the recognizer will perform continuous // recognition (continuing to wait for and process audio even if the user // pauses speaking) until the client closes the input stream (gRPC API) or // until the maximum time limit has been reached. May return multiple // `StreamingRecognitionResult`s with the `is_final` flag set to `true`. // // If `true`, the recognizer will detect a single spoken utterance. When it // detects that the user has paused or stopped speaking, it will return an // `END_OF_SINGLE_UTTERANCE` event and cease recognition. It will return no // more than one `StreamingRecognitionResult` with the `is_final` flag set to // `true`. SingleUtterance bool `protobuf:"varint,2,opt,name=single_utterance,json=singleUtterance,proto3" json:"single_utterance,omitempty"` // If `true`, interim results (tentative hypotheses) may be // returned as they become available (these interim results are indicated with // the `is_final=false` flag). // If `false` or omitted, only `is_final=true` result(s) are returned. InterimResults bool `protobuf:"varint,3,opt,name=interim_results,json=interimResults,proto3" json:"interim_results,omitempty"` } func (x *StreamingRecognitionConfig) Reset() { *x = StreamingRecognitionConfig{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *StreamingRecognitionConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*StreamingRecognitionConfig) ProtoMessage() {} func (x *StreamingRecognitionConfig) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StreamingRecognitionConfig.ProtoReflect.Descriptor instead. func (*StreamingRecognitionConfig) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{3} } func (x *StreamingRecognitionConfig) GetConfig() *RecognitionConfig { if x != nil { return x.Config } return nil } func (x *StreamingRecognitionConfig) GetSingleUtterance() bool { if x != nil { return x.SingleUtterance } return false } func (x *StreamingRecognitionConfig) GetInterimResults() bool { if x != nil { return x.InterimResults } return false } // Provides information to the recognizer that specifies how to process the // request. type RecognitionConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Encoding of audio data sent in all `RecognitionAudio` messages. // This field is optional for `FLAC` and `WAV` audio files and required // for all other audio formats. For details, see [AudioEncoding][google.cloud.speech.v1.RecognitionConfig.AudioEncoding]. Encoding RecognitionConfig_AudioEncoding `protobuf:"varint,1,opt,name=encoding,proto3,enum=google.cloud.speech.v1.RecognitionConfig_AudioEncoding" json:"encoding,omitempty"` // Sample rate in Hertz of the audio data sent in all // `RecognitionAudio` messages. Valid values are: 8000-48000. // 16000 is optimal. For best results, set the sampling rate of the audio // source to 16000 Hz. If that's not possible, use the native sample rate of // the audio source (instead of re-sampling). // This field is optional for FLAC and WAV audio files, but is // required for all other audio formats. For details, see [AudioEncoding][google.cloud.speech.v1.RecognitionConfig.AudioEncoding]. SampleRateHertz int32 `protobuf:"varint,2,opt,name=sample_rate_hertz,json=sampleRateHertz,proto3" json:"sample_rate_hertz,omitempty"` // The number of channels in the input audio data. // ONLY set this for MULTI-CHANNEL recognition. // Valid values for LINEAR16 and FLAC are `1`-`8`. // Valid values for OGG_OPUS are '1'-'254'. // Valid value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. // If `0` or omitted, defaults to one channel (mono). // Note: We only recognize the first channel by default. // To perform independent recognition on each channel set // `enable_separate_recognition_per_channel` to 'true'. AudioChannelCount int32 `protobuf:"varint,7,opt,name=audio_channel_count,json=audioChannelCount,proto3" json:"audio_channel_count,omitempty"` // This needs to be set to `true` explicitly and `audio_channel_count` > 1 // to get each channel recognized separately. The recognition result will // contain a `channel_tag` field to state which channel that result belongs // to. If this is not true, we will only recognize the first channel. The // request is billed cumulatively for all channels recognized: // `audio_channel_count` multiplied by the length of the audio. EnableSeparateRecognitionPerChannel bool `protobuf:"varint,12,opt,name=enable_separate_recognition_per_channel,json=enableSeparateRecognitionPerChannel,proto3" json:"enable_separate_recognition_per_channel,omitempty"` // Required. The language of the supplied audio as a // [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. // Example: "en-US". // See [Language // Support](https://cloud.google.com/speech-to-text/docs/languages) for a list // of the currently supported language codes. LanguageCode string `protobuf:"bytes,3,opt,name=language_code,json=languageCode,proto3" json:"language_code,omitempty"` // Maximum number of recognition hypotheses to be returned. // Specifically, the maximum number of `SpeechRecognitionAlternative` messages // within each `SpeechRecognitionResult`. // The server may return fewer than `max_alternatives`. // Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of // one. If omitted, will return a maximum of one. MaxAlternatives int32 `protobuf:"varint,4,opt,name=max_alternatives,json=maxAlternatives,proto3" json:"max_alternatives,omitempty"` // If set to `true`, the server will attempt to filter out // profanities, replacing all but the initial character in each filtered word // with asterisks, e.g. "f***". If set to `false` or omitted, profanities // won't be filtered out. ProfanityFilter bool `protobuf:"varint,5,opt,name=profanity_filter,json=profanityFilter,proto3" json:"profanity_filter,omitempty"` // Array of [SpeechContext][google.cloud.speech.v1.SpeechContext]. // A means to provide context to assist the speech recognition. For more // information, see // [speech // adaptation](https://cloud.google.com/speech-to-text/docs/context-strength). SpeechContexts []*SpeechContext `protobuf:"bytes,6,rep,name=speech_contexts,json=speechContexts,proto3" json:"speech_contexts,omitempty"` // If `true`, the top result includes a list of words and // the start and end time offsets (timestamps) for those words. If // `false`, no word-level time offset information is returned. The default is // `false`. EnableWordTimeOffsets bool `protobuf:"varint,8,opt,name=enable_word_time_offsets,json=enableWordTimeOffsets,proto3" json:"enable_word_time_offsets,omitempty"` // If 'true', adds punctuation to recognition result hypotheses. // This feature is only available in select languages. Setting this for // requests in other languages has no effect at all. // The default 'false' value does not add punctuation to result hypotheses. // Note: This is currently offered as an experimental service, complimentary // to all users. In the future this may be exclusively available as a // premium feature. EnableAutomaticPunctuation bool `protobuf:"varint,11,opt,name=enable_automatic_punctuation,json=enableAutomaticPunctuation,proto3" json:"enable_automatic_punctuation,omitempty"` // Config to enable speaker diarization and set additional // parameters to make diarization better suited for your application. // Note: When this is enabled, we send all the words from the beginning of the // audio for the top alternative in every consecutive STREAMING responses. // This is done in order to improve our speaker tags as our models learn to // identify the speakers in the conversation over time. // For non-streaming requests, the diarization results will be provided only // in the top alternative of the FINAL SpeechRecognitionResult. DiarizationConfig *SpeakerDiarizationConfig `protobuf:"bytes,19,opt,name=diarization_config,json=diarizationConfig,proto3" json:"diarization_config,omitempty"` // Metadata regarding this request. Metadata *RecognitionMetadata `protobuf:"bytes,9,opt,name=metadata,proto3" json:"metadata,omitempty"` // Which model to select for the given request. Select the model // best suited to your domain to get best results. If a model is not // explicitly specified, then we auto-select a model based on the parameters // in the RecognitionConfig. // <table> // <tr> // <td><b>Model</b></td> // <td><b>Description</b></td> // </tr> // <tr> // <td><code>command_and_search</code></td> // <td>Best for short queries such as voice commands or voice search.</td> // </tr> // <tr> // <td><code>phone_call</code></td> // <td>Best for audio that originated from a phone call (typically // recorded at an 8khz sampling rate).</td> // </tr> // <tr> // <td><code>video</code></td> // <td>Best for audio that originated from from video or includes multiple // speakers. Ideally the audio is recorded at a 16khz or greater // sampling rate. This is a premium model that costs more than the // standard rate.</td> // </tr> // <tr> // <td><code>default</code></td> // <td>Best for audio that is not one of the specific audio models. // For example, long-form audio. Ideally the audio is high-fidelity, // recorded at a 16khz or greater sampling rate.</td> // </tr> // </table> Model string `protobuf:"bytes,13,opt,name=model,proto3" json:"model,omitempty"` // Set to true to use an enhanced model for speech recognition. // If `use_enhanced` is set to true and the `model` field is not set, then // an appropriate enhanced model is chosen if an enhanced model exists for // the audio. // // If `use_enhanced` is true and an enhanced version of the specified model // does not exist, then the speech is recognized using the standard version // of the specified model. UseEnhanced bool `protobuf:"varint,14,opt,name=use_enhanced,json=useEnhanced,proto3" json:"use_enhanced,omitempty"` } func (x *RecognitionConfig) Reset() { *x = RecognitionConfig{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RecognitionConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*RecognitionConfig) ProtoMessage() {} func (x *RecognitionConfig) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RecognitionConfig.ProtoReflect.Descriptor instead. func (*RecognitionConfig) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{4} } func (x *RecognitionConfig) GetEncoding() RecognitionConfig_AudioEncoding { if x != nil { return x.Encoding } return RecognitionConfig_ENCODING_UNSPECIFIED } func (x *RecognitionConfig) GetSampleRateHertz() int32 { if x != nil { return x.SampleRateHertz } return 0 } func (x *RecognitionConfig) GetAudioChannelCount() int32 { if x != nil { return x.AudioChannelCount } return 0 } func (x *RecognitionConfig) GetEnableSeparateRecognitionPerChannel() bool { if x != nil { return x.EnableSeparateRecognitionPerChannel } return false } func (x *RecognitionConfig) GetLanguageCode() string { if x != nil { return x.LanguageCode } return "" } func (x *RecognitionConfig) GetMaxAlternatives() int32 { if x != nil { return x.MaxAlternatives } return 0 } func (x *RecognitionConfig) GetProfanityFilter() bool { if x != nil { return x.ProfanityFilter } return false } func (x *RecognitionConfig) GetSpeechContexts() []*SpeechContext { if x != nil { return x.SpeechContexts } return nil } func (x *RecognitionConfig) GetEnableWordTimeOffsets() bool { if x != nil { return x.EnableWordTimeOffsets } return false } func (x *RecognitionConfig) GetEnableAutomaticPunctuation() bool { if x != nil { return x.EnableAutomaticPunctuation } return false } func (x *RecognitionConfig) GetDiarizationConfig() *SpeakerDiarizationConfig { if x != nil { return x.DiarizationConfig } return nil } func (x *RecognitionConfig) GetMetadata() *RecognitionMetadata { if x != nil { return x.Metadata } return nil } func (x *RecognitionConfig) GetModel() string { if x != nil { return x.Model } return "" } func (x *RecognitionConfig) GetUseEnhanced() bool { if x != nil { return x.UseEnhanced } return false } // Config to enable speaker diarization. type SpeakerDiarizationConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // If 'true', enables speaker detection for each recognized word in // the top alternative of the recognition result using a speaker_tag provided // in the WordInfo. EnableSpeakerDiarization bool `protobuf:"varint,1,opt,name=enable_speaker_diarization,json=enableSpeakerDiarization,proto3" json:"enable_speaker_diarization,omitempty"` // Minimum number of speakers in the conversation. This range gives you more // flexibility by allowing the system to automatically determine the correct // number of speakers. If not set, the default value is 2. MinSpeakerCount int32 `protobuf:"varint,2,opt,name=min_speaker_count,json=minSpeakerCount,proto3" json:"min_speaker_count,omitempty"` // Maximum number of speakers in the conversation. This range gives you more // flexibility by allowing the system to automatically determine the correct // number of speakers. If not set, the default value is 6. MaxSpeakerCount int32 `protobuf:"varint,3,opt,name=max_speaker_count,json=maxSpeakerCount,proto3" json:"max_speaker_count,omitempty"` // Unused. // // Deprecated: Do not use. SpeakerTag int32 `protobuf:"varint,5,opt,name=speaker_tag,json=speakerTag,proto3" json:"speaker_tag,omitempty"` } func (x *SpeakerDiarizationConfig) Reset() { *x = SpeakerDiarizationConfig{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SpeakerDiarizationConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*SpeakerDiarizationConfig) ProtoMessage() {} func (x *SpeakerDiarizationConfig) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SpeakerDiarizationConfig.ProtoReflect.Descriptor instead. func (*SpeakerDiarizationConfig) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{5} } func (x *SpeakerDiarizationConfig) GetEnableSpeakerDiarization() bool { if x != nil { return x.EnableSpeakerDiarization } return false } func (x *SpeakerDiarizationConfig) GetMinSpeakerCount() int32 { if x != nil { return x.MinSpeakerCount } return 0 } func (x *SpeakerDiarizationConfig) GetMaxSpeakerCount() int32 { if x != nil { return x.MaxSpeakerCount } return 0 } // Deprecated: Do not use. func (x *SpeakerDiarizationConfig) GetSpeakerTag() int32 { if x != nil { return x.SpeakerTag } return 0 } // Description of audio data to be recognized. type RecognitionMetadata struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The use case most closely describing the audio content to be recognized. InteractionType RecognitionMetadata_InteractionType `protobuf:"varint,1,opt,name=interaction_type,json=interactionType,proto3,enum=google.cloud.speech.v1.RecognitionMetadata_InteractionType" json:"interaction_type,omitempty"` // The industry vertical to which this speech recognition request most // closely applies. This is most indicative of the topics contained // in the audio. Use the 6-digit NAICS code to identify the industry // vertical - see https://www.naics.com/search/. IndustryNaicsCodeOfAudio uint32 `protobuf:"varint,3,opt,name=industry_naics_code_of_audio,json=industryNaicsCodeOfAudio,proto3" json:"industry_naics_code_of_audio,omitempty"` // The audio type that most closely describes the audio being recognized. MicrophoneDistance RecognitionMetadata_MicrophoneDistance `protobuf:"varint,4,opt,name=microphone_distance,json=microphoneDistance,proto3,enum=google.cloud.speech.v1.RecognitionMetadata_MicrophoneDistance" json:"microphone_distance,omitempty"` // The original media the speech was recorded on. OriginalMediaType RecognitionMetadata_OriginalMediaType `protobuf:"varint,5,opt,name=original_media_type,json=originalMediaType,proto3,enum=google.cloud.speech.v1.RecognitionMetadata_OriginalMediaType" json:"original_media_type,omitempty"` // The type of device the speech was recorded with. RecordingDeviceType RecognitionMetadata_RecordingDeviceType `protobuf:"varint,6,opt,name=recording_device_type,json=recordingDeviceType,proto3,enum=google.cloud.speech.v1.RecognitionMetadata_RecordingDeviceType" json:"recording_device_type,omitempty"` // The device used to make the recording. Examples 'Nexus 5X' or // 'Polycom SoundStation IP 6000' or 'POTS' or 'VoIP' or // 'Cardioid Microphone'. RecordingDeviceName string `protobuf:"bytes,7,opt,name=recording_device_name,json=recordingDeviceName,proto3" json:"recording_device_name,omitempty"` // Mime type of the original audio file. For example `audio/m4a`, // `audio/x-alaw-basic`, `audio/mp3`, `audio/3gpp`. // A list of possible audio mime types is maintained at // http://www.iana.org/assignments/media-types/media-types.xhtml#audio OriginalMimeType string `protobuf:"bytes,8,opt,name=original_mime_type,json=originalMimeType,proto3" json:"original_mime_type,omitempty"` // Description of the content. Eg. "Recordings of federal supreme court // hearings from 2012". AudioTopic string `protobuf:"bytes,10,opt,name=audio_topic,json=audioTopic,proto3" json:"audio_topic,omitempty"` } func (x *RecognitionMetadata) Reset() { *x = RecognitionMetadata{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RecognitionMetadata) String() string { return protoimpl.X.MessageStringOf(x) } func (*RecognitionMetadata) ProtoMessage() {} func (x *RecognitionMetadata) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RecognitionMetadata.ProtoReflect.Descriptor instead. func (*RecognitionMetadata) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{6} } func (x *RecognitionMetadata) GetInteractionType() RecognitionMetadata_InteractionType { if x != nil { return x.InteractionType } return RecognitionMetadata_INTERACTION_TYPE_UNSPECIFIED } func (x *RecognitionMetadata) GetIndustryNaicsCodeOfAudio() uint32 { if x != nil { return x.IndustryNaicsCodeOfAudio } return 0 } func (x *RecognitionMetadata) GetMicrophoneDistance() RecognitionMetadata_MicrophoneDistance { if x != nil { return x.MicrophoneDistance } return RecognitionMetadata_MICROPHONE_DISTANCE_UNSPECIFIED } func (x *RecognitionMetadata) GetOriginalMediaType() RecognitionMetadata_OriginalMediaType { if x != nil { return x.OriginalMediaType } return RecognitionMetadata_ORIGINAL_MEDIA_TYPE_UNSPECIFIED } func (x *RecognitionMetadata) GetRecordingDeviceType() RecognitionMetadata_RecordingDeviceType { if x != nil { return x.RecordingDeviceType } return RecognitionMetadata_RECORDING_DEVICE_TYPE_UNSPECIFIED } func (x *RecognitionMetadata) GetRecordingDeviceName() string { if x != nil { return x.RecordingDeviceName } return "" } func (x *RecognitionMetadata) GetOriginalMimeType() string { if x != nil { return x.OriginalMimeType } return "" } func (x *RecognitionMetadata) GetAudioTopic() string { if x != nil { return x.AudioTopic } return "" } // Provides "hints" to the speech recognizer to favor specific words and phrases // in the results. type SpeechContext struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A list of strings containing words and phrases "hints" so that // the speech recognition is more likely to recognize them. This can be used // to improve the accuracy for specific words and phrases, for example, if // specific commands are typically spoken by the user. This can also be used // to add additional words to the vocabulary of the recognizer. See // [usage limits](https://cloud.google.com/speech-to-text/quotas#content). // // List items can also be set to classes for groups of words that represent // common concepts that occur in natural language. For example, rather than // providing phrase hints for every month of the year, using the $MONTH class // improves the likelihood of correctly transcribing audio that includes // months. Phrases []string `protobuf:"bytes,1,rep,name=phrases,proto3" json:"phrases,omitempty"` } func (x *SpeechContext) Reset() { *x = SpeechContext{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SpeechContext) String() string { return protoimpl.X.MessageStringOf(x) } func (*SpeechContext) ProtoMessage() {} func (x *SpeechContext) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SpeechContext.ProtoReflect.Descriptor instead. func (*SpeechContext) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{7} } func (x *SpeechContext) GetPhrases() []string { if x != nil { return x.Phrases } return nil } // Contains audio data in the encoding specified in the `RecognitionConfig`. // Either `content` or `uri` must be supplied. Supplying both or neither // returns [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]. See // [content limits](https://cloud.google.com/speech-to-text/quotas#content). type RecognitionAudio struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The audio source, which is either inline content or a Google Cloud // Storage uri. // // Types that are assignable to AudioSource: // *RecognitionAudio_Content // *RecognitionAudio_Uri AudioSource isRecognitionAudio_AudioSource `protobuf_oneof:"audio_source"` } func (x *RecognitionAudio) Reset() { *x = RecognitionAudio{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RecognitionAudio) String() string { return protoimpl.X.MessageStringOf(x) } func (*RecognitionAudio) ProtoMessage() {} func (x *RecognitionAudio) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RecognitionAudio.ProtoReflect.Descriptor instead. func (*RecognitionAudio) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{8} } func (m *RecognitionAudio) GetAudioSource() isRecognitionAudio_AudioSource { if m != nil { return m.AudioSource } return nil } func (x *RecognitionAudio) GetContent() []byte { if x, ok := x.GetAudioSource().(*RecognitionAudio_Content); ok { return x.Content } return nil } func (x *RecognitionAudio) GetUri() string { if x, ok := x.GetAudioSource().(*RecognitionAudio_Uri); ok { return x.Uri } return "" } type isRecognitionAudio_AudioSource interface { isRecognitionAudio_AudioSource() } type RecognitionAudio_Content struct { // The audio data bytes encoded as specified in // `RecognitionConfig`. Note: as with all bytes fields, proto buffers use a // pure binary representation, whereas JSON representations use base64. Content []byte `protobuf:"bytes,1,opt,name=content,proto3,oneof"` } type RecognitionAudio_Uri struct { // URI that points to a file that contains audio data bytes as specified in // `RecognitionConfig`. The file must not be compressed (for example, gzip). // Currently, only Google Cloud Storage URIs are // supported, which must be specified in the following format: // `gs://bucket_name/object_name` (other URI formats return // [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see // [Request URIs](https://cloud.google.com/storage/docs/reference-uris). Uri string `protobuf:"bytes,2,opt,name=uri,proto3,oneof"` } func (*RecognitionAudio_Content) isRecognitionAudio_AudioSource() {} func (*RecognitionAudio_Uri) isRecognitionAudio_AudioSource() {} // The only message returned to the client by the `Recognize` method. It // contains the result as zero or more sequential `SpeechRecognitionResult` // messages. type RecognizeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Sequential list of transcription results corresponding to // sequential portions of audio. Results []*SpeechRecognitionResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"` } func (x *RecognizeResponse) Reset() { *x = RecognizeResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *RecognizeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*RecognizeResponse) ProtoMessage() {} func (x *RecognizeResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RecognizeResponse.ProtoReflect.Descriptor instead. func (*RecognizeResponse) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{9} } func (x *RecognizeResponse) GetResults() []*SpeechRecognitionResult { if x != nil { return x.Results } return nil } // The only message returned to the client by the `LongRunningRecognize` method. // It contains the result as zero or more sequential `SpeechRecognitionResult` // messages. It is included in the `result.response` field of the `Operation` // returned by the `GetOperation` call of the `google::longrunning::Operations` // service. type LongRunningRecognizeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Sequential list of transcription results corresponding to // sequential portions of audio. Results []*SpeechRecognitionResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"` } func (x *LongRunningRecognizeResponse) Reset() { *x = LongRunningRecognizeResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *LongRunningRecognizeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*LongRunningRecognizeResponse) ProtoMessage() {} func (x *LongRunningRecognizeResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LongRunningRecognizeResponse.ProtoReflect.Descriptor instead. func (*LongRunningRecognizeResponse) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{10} } func (x *LongRunningRecognizeResponse) GetResults() []*SpeechRecognitionResult { if x != nil { return x.Results } return nil } // Describes the progress of a long-running `LongRunningRecognize` call. It is // included in the `metadata` field of the `Operation` returned by the // `GetOperation` call of the `google::longrunning::Operations` service. type LongRunningRecognizeMetadata struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Approximate percentage of audio processed thus far. Guaranteed to be 100 // when the audio is fully processed and the results are available. ProgressPercent int32 `protobuf:"varint,1,opt,name=progress_percent,json=progressPercent,proto3" json:"progress_percent,omitempty"` // Time when the request was received. StartTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` // Time of the most recent processing update. LastUpdateTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` } func (x *LongRunningRecognizeMetadata) Reset() { *x = LongRunningRecognizeMetadata{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *LongRunningRecognizeMetadata) String() string { return protoimpl.X.MessageStringOf(x) } func (*LongRunningRecognizeMetadata) ProtoMessage() {} func (x *LongRunningRecognizeMetadata) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use LongRunningRecognizeMetadata.ProtoReflect.Descriptor instead. func (*LongRunningRecognizeMetadata) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{11} } func (x *LongRunningRecognizeMetadata) GetProgressPercent() int32 { if x != nil { return x.ProgressPercent } return 0 } func (x *LongRunningRecognizeMetadata) GetStartTime() *timestamppb.Timestamp { if x != nil { return x.StartTime } return nil } func (x *LongRunningRecognizeMetadata) GetLastUpdateTime() *timestamppb.Timestamp { if x != nil { return x.LastUpdateTime } return nil } // `StreamingRecognizeResponse` is the only message returned to the client by // `StreamingRecognize`. A series of zero or more `StreamingRecognizeResponse` // messages are streamed back to the client. If there is no recognizable // audio, and `single_utterance` is set to false, then no messages are streamed // back to the client. // // Here's an example of a series of ten `StreamingRecognizeResponse`s that might // be returned while processing audio: // // 1. results { alternatives { transcript: "tube" } stability: 0.01 } // // 2. results { alternatives { transcript: "to be a" } stability: 0.01 } // // 3. results { alternatives { transcript: "to be" } stability: 0.9 } // results { alternatives { transcript: " or not to be" } stability: 0.01 } // // 4. results { alternatives { transcript: "to be or not to be" // confidence: 0.92 } // alternatives { transcript: "to bee or not to bee" } // is_final: true } // // 5. results { alternatives { transcript: " that's" } stability: 0.01 } // // 6. results { alternatives { transcript: " that is" } stability: 0.9 } // results { alternatives { transcript: " the question" } stability: 0.01 } // // 7. results { alternatives { transcript: " that is the question" // confidence: 0.98 } // alternatives { transcript: " that was the question" } // is_final: true } // // Notes: // // - Only two of the above responses #4 and #7 contain final results; they are // indicated by `is_final: true`. Concatenating these together generates the // full transcript: "to be or not to be that is the question". // // - The others contain interim `results`. #3 and #6 contain two interim // `results`: the first portion has a high stability and is less likely to // change; the second portion has a low stability and is very likely to // change. A UI designer might choose to show only high stability `results`. // // - The specific `stability` and `confidence` values shown above are only for // illustrative purposes. Actual values may vary. // // - In each response, only one of these fields will be set: // `error`, // `speech_event_type`, or // one or more (repeated) `results`. type StreamingRecognizeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // If set, returns a [google.rpc.Status][google.rpc.Status] message that // specifies the error for the operation. Error *status.Status `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` // This repeated list contains zero or more results that // correspond to consecutive portions of the audio currently being processed. // It contains zero or one `is_final=true` result (the newly settled portion), // followed by zero or more `is_final=false` results (the interim results). Results []*StreamingRecognitionResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"` // Indicates the type of speech event. SpeechEventType StreamingRecognizeResponse_SpeechEventType `protobuf:"varint,4,opt,name=speech_event_type,json=speechEventType,proto3,enum=google.cloud.speech.v1.StreamingRecognizeResponse_SpeechEventType" json:"speech_event_type,omitempty"` } func (x *StreamingRecognizeResponse) Reset() { *x = StreamingRecognizeResponse{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *StreamingRecognizeResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*StreamingRecognizeResponse) ProtoMessage() {} func (x *StreamingRecognizeResponse) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StreamingRecognizeResponse.ProtoReflect.Descriptor instead. func (*StreamingRecognizeResponse) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{12} } func (x *StreamingRecognizeResponse) GetError() *status.Status { if x != nil { return x.Error } return nil } func (x *StreamingRecognizeResponse) GetResults() []*StreamingRecognitionResult { if x != nil { return x.Results } return nil } func (x *StreamingRecognizeResponse) GetSpeechEventType() StreamingRecognizeResponse_SpeechEventType { if x != nil { return x.SpeechEventType } return StreamingRecognizeResponse_SPEECH_EVENT_UNSPECIFIED } // A streaming speech recognition result corresponding to a portion of the audio // that is currently being processed. type StreamingRecognitionResult struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // May contain one or more recognition hypotheses (up to the // maximum specified in `max_alternatives`). // These alternatives are ordered in terms of accuracy, with the top (first) // alternative being the most probable, as ranked by the recognizer. Alternatives []*SpeechRecognitionAlternative `protobuf:"bytes,1,rep,name=alternatives,proto3" json:"alternatives,omitempty"` // If `false`, this `StreamingRecognitionResult` represents an // interim result that may change. If `true`, this is the final time the // speech service will return this particular `StreamingRecognitionResult`, // the recognizer will not return any further hypotheses for this portion of // the transcript and corresponding audio. IsFinal bool `protobuf:"varint,2,opt,name=is_final,json=isFinal,proto3" json:"is_final,omitempty"` // An estimate of the likelihood that the recognizer will not // change its guess about this interim result. Values range from 0.0 // (completely unstable) to 1.0 (completely stable). // This field is only provided for interim results (`is_final=false`). // The default of 0.0 is a sentinel value indicating `stability` was not set. Stability float32 `protobuf:"fixed32,3,opt,name=stability,proto3" json:"stability,omitempty"` // Time offset of the end of this result relative to the // beginning of the audio. ResultEndTime *durationpb.Duration `protobuf:"bytes,4,opt,name=result_end_time,json=resultEndTime,proto3" json:"result_end_time,omitempty"` // For multi-channel audio, this is the channel number corresponding to the // recognized result for the audio from that channel. // For audio_channel_count = N, its output values can range from '1' to 'N'. ChannelTag int32 `protobuf:"varint,5,opt,name=channel_tag,json=channelTag,proto3" json:"channel_tag,omitempty"` // The [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag of // the language in this result. This language code was detected to have the // most likelihood of being spoken in the audio. LanguageCode string `protobuf:"bytes,6,opt,name=language_code,json=languageCode,proto3" json:"language_code,omitempty"` } func (x *StreamingRecognitionResult) Reset() { *x = StreamingRecognitionResult{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *StreamingRecognitionResult) String() string { return protoimpl.X.MessageStringOf(x) } func (*StreamingRecognitionResult) ProtoMessage() {} func (x *StreamingRecognitionResult) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[13] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StreamingRecognitionResult.ProtoReflect.Descriptor instead. func (*StreamingRecognitionResult) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{13} } func (x *StreamingRecognitionResult) GetAlternatives() []*SpeechRecognitionAlternative { if x != nil { return x.Alternatives } return nil } func (x *StreamingRecognitionResult) GetIsFinal() bool { if x != nil { return x.IsFinal } return false } func (x *StreamingRecognitionResult) GetStability() float32 { if x != nil { return x.Stability } return 0 } func (x *StreamingRecognitionResult) GetResultEndTime() *durationpb.Duration { if x != nil { return x.ResultEndTime } return nil } func (x *StreamingRecognitionResult) GetChannelTag() int32 { if x != nil { return x.ChannelTag } return 0 } func (x *StreamingRecognitionResult) GetLanguageCode() string { if x != nil { return x.LanguageCode } return "" } // A speech recognition result corresponding to a portion of the audio. type SpeechRecognitionResult struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // May contain one or more recognition hypotheses (up to the // maximum specified in `max_alternatives`). // These alternatives are ordered in terms of accuracy, with the top (first) // alternative being the most probable, as ranked by the recognizer. Alternatives []*SpeechRecognitionAlternative `protobuf:"bytes,1,rep,name=alternatives,proto3" json:"alternatives,omitempty"` // For multi-channel audio, this is the channel number corresponding to the // recognized result for the audio from that channel. // For audio_channel_count = N, its output values can range from '1' to 'N'. ChannelTag int32 `protobuf:"varint,2,opt,name=channel_tag,json=channelTag,proto3" json:"channel_tag,omitempty"` } func (x *SpeechRecognitionResult) Reset() { *x = SpeechRecognitionResult{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SpeechRecognitionResult) String() string { return protoimpl.X.MessageStringOf(x) } func (*SpeechRecognitionResult) ProtoMessage() {} func (x *SpeechRecognitionResult) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[14] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SpeechRecognitionResult.ProtoReflect.Descriptor instead. func (*SpeechRecognitionResult) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{14} } func (x *SpeechRecognitionResult) GetAlternatives() []*SpeechRecognitionAlternative { if x != nil { return x.Alternatives } return nil } func (x *SpeechRecognitionResult) GetChannelTag() int32 { if x != nil { return x.ChannelTag } return 0 } // Alternative hypotheses (a.k.a. n-best list). type SpeechRecognitionAlternative struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Transcript text representing the words that the user spoke. Transcript string `protobuf:"bytes,1,opt,name=transcript,proto3" json:"transcript,omitempty"` // The confidence estimate between 0.0 and 1.0. A higher number // indicates an estimated greater likelihood that the recognized words are // correct. This field is set only for the top alternative of a non-streaming // result or, of a streaming result where `is_final=true`. // This field is not guaranteed to be accurate and users should not rely on it // to be always provided. // The default of 0.0 is a sentinel value indicating `confidence` was not set. Confidence float32 `protobuf:"fixed32,2,opt,name=confidence,proto3" json:"confidence,omitempty"` // A list of word-specific information for each recognized word. // Note: When `enable_speaker_diarization` is true, you will see all the words // from the beginning of the audio. Words []*WordInfo `protobuf:"bytes,3,rep,name=words,proto3" json:"words,omitempty"` } func (x *SpeechRecognitionAlternative) Reset() { *x = SpeechRecognitionAlternative{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SpeechRecognitionAlternative) String() string { return protoimpl.X.MessageStringOf(x) } func (*SpeechRecognitionAlternative) ProtoMessage() {} func (x *SpeechRecognitionAlternative) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[15] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SpeechRecognitionAlternative.ProtoReflect.Descriptor instead. func (*SpeechRecognitionAlternative) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{15} } func (x *SpeechRecognitionAlternative) GetTranscript() string { if x != nil { return x.Transcript } return "" } func (x *SpeechRecognitionAlternative) GetConfidence() float32 { if x != nil { return x.Confidence } return 0 } func (x *SpeechRecognitionAlternative) GetWords() []*WordInfo { if x != nil { return x.Words } return nil } // Word-specific information for recognized words. type WordInfo struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Time offset relative to the beginning of the audio, // and corresponding to the start of the spoken word. // This field is only set if `enable_word_time_offsets=true` and only // in the top hypothesis. // This is an experimental feature and the accuracy of the time offset can // vary. StartTime *durationpb.Duration `protobuf:"bytes,1,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` // Time offset relative to the beginning of the audio, // and corresponding to the end of the spoken word. // This field is only set if `enable_word_time_offsets=true` and only // in the top hypothesis. // This is an experimental feature and the accuracy of the time offset can // vary. EndTime *durationpb.Duration `protobuf:"bytes,2,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` // The word corresponding to this set of information. Word string `protobuf:"bytes,3,opt,name=word,proto3" json:"word,omitempty"` // A distinct integer value is assigned for every speaker within // the audio. This field specifies which one of those speakers was detected to // have spoken this word. Value ranges from '1' to diarization_speaker_count. // speaker_tag is set if enable_speaker_diarization = 'true' and only in the // top alternative. SpeakerTag int32 `protobuf:"varint,5,opt,name=speaker_tag,json=speakerTag,proto3" json:"speaker_tag,omitempty"` } func (x *WordInfo) Reset() { *x = WordInfo{} if protoimpl.UnsafeEnabled { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *WordInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*WordInfo) ProtoMessage() {} func (x *WordInfo) ProtoReflect() protoreflect.Message { mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[16] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WordInfo.ProtoReflect.Descriptor instead. func (*WordInfo) Descriptor() ([]byte, []int) { return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{16} } func (x *WordInfo) GetStartTime() *durationpb.Duration { if x != nil { return x.StartTime } return nil } func (x *WordInfo) GetEndTime() *durationpb.Duration { if x != nil { return x.EndTime } return nil } func (x *WordInfo) GetWord() string { if x != nil { return x.Word } return "" } func (x *WordInfo) GetSpeakerTag() int32 { if x != nil { return x.SpeakerTag } return 0 } var File_google_cloud_speech_v1_cloud_speech_proto protoreflect.FileDescriptor var file_google_cloud_speech_v1_cloud_speech_proto_rawDesc = []byte{ 0x0a, 0x29, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x5f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x16, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x23, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2f, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9f, 0x01, 0x0a, 0x10, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x46, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x43, 0x0a, 0x05, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x05, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x22, 0xaa, 0x01, 0x0a, 0x1b, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x46, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x43, 0x0a, 0x05, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x05, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x22, 0xb8, 0x01, 0x0a, 0x19, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x5f, 0x0a, 0x10, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x48, 0x00, 0x52, 0x0f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x25, 0x0a, 0x0d, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x0c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x42, 0x13, 0x0a, 0x11, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xb8, 0x01, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x46, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x5f, 0x75, 0x74, 0x74, 0x65, 0x72, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x73, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x55, 0x74, 0x74, 0x65, 0x72, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x69, 0x6d, 0x5f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x69, 0x6d, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x22, 0xd6, 0x07, 0x0a, 0x11, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x53, 0x0a, 0x08, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x45, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x52, 0x08, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x2a, 0x0a, 0x11, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x5f, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x68, 0x65, 0x72, 0x74, 0x7a, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x61, 0x74, 0x65, 0x48, 0x65, 0x72, 0x74, 0x7a, 0x12, 0x2e, 0x0a, 0x13, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, 0x11, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x43, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x54, 0x0a, 0x27, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x73, 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x08, 0x52, 0x23, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x65, 0x72, 0x43, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x6d, 0x61, 0x78, 0x5f, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x66, 0x61, 0x6e, 0x69, 0x74, 0x79, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x66, 0x61, 0x6e, 0x69, 0x74, 0x79, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x4e, 0x0a, 0x0f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x52, 0x0e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x73, 0x12, 0x37, 0x0a, 0x18, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x15, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x57, 0x6f, 0x72, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x4f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x73, 0x12, 0x40, 0x0a, 0x1c, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x61, 0x75, 0x74, 0x6f, 0x6d, 0x61, 0x74, 0x69, 0x63, 0x5f, 0x70, 0x75, 0x6e, 0x63, 0x74, 0x75, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1a, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x41, 0x75, 0x74, 0x6f, 0x6d, 0x61, 0x74, 0x69, 0x63, 0x50, 0x75, 0x6e, 0x63, 0x74, 0x75, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x5f, 0x0a, 0x12, 0x64, 0x69, 0x61, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x13, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x44, 0x69, 0x61, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x11, 0x64, 0x69, 0x61, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x47, 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x52, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x12, 0x21, 0x0a, 0x0c, 0x75, 0x73, 0x65, 0x5f, 0x65, 0x6e, 0x68, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0b, 0x75, 0x73, 0x65, 0x45, 0x6e, 0x68, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x22, 0x8b, 0x01, 0x0a, 0x0d, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x45, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x18, 0x0a, 0x14, 0x45, 0x4e, 0x43, 0x4f, 0x44, 0x49, 0x4e, 0x47, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x4c, 0x49, 0x4e, 0x45, 0x41, 0x52, 0x31, 0x36, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x4c, 0x41, 0x43, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x4d, 0x55, 0x4c, 0x41, 0x57, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x4d, 0x52, 0x10, 0x04, 0x12, 0x0a, 0x0a, 0x06, 0x41, 0x4d, 0x52, 0x5f, 0x57, 0x42, 0x10, 0x05, 0x12, 0x0c, 0x0a, 0x08, 0x4f, 0x47, 0x47, 0x5f, 0x4f, 0x50, 0x55, 0x53, 0x10, 0x06, 0x12, 0x1a, 0x0a, 0x16, 0x53, 0x50, 0x45, 0x45, 0x58, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x48, 0x45, 0x41, 0x44, 0x45, 0x52, 0x5f, 0x42, 0x59, 0x54, 0x45, 0x10, 0x07, 0x22, 0xd8, 0x01, 0x0a, 0x18, 0x53, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x44, 0x69, 0x61, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x3c, 0x0a, 0x1a, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x64, 0x69, 0x61, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x18, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x44, 0x69, 0x61, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x11, 0x6d, 0x69, 0x6e, 0x5f, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x6d, 0x69, 0x6e, 0x53, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x6d, 0x61, 0x78, 0x5f, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x6d, 0x61, 0x78, 0x53, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x26, 0x0a, 0x0b, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x42, 0x05, 0x18, 0x01, 0xe0, 0x41, 0x03, 0x52, 0x0a, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x54, 0x61, 0x67, 0x22, 0xba, 0x09, 0x0a, 0x13, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x66, 0x0a, 0x10, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x3e, 0x0a, 0x1c, 0x69, 0x6e, 0x64, 0x75, 0x73, 0x74, 0x72, 0x79, 0x5f, 0x6e, 0x61, 0x69, 0x63, 0x73, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x5f, 0x6f, 0x66, 0x5f, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x18, 0x69, 0x6e, 0x64, 0x75, 0x73, 0x74, 0x72, 0x79, 0x4e, 0x61, 0x69, 0x63, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x4f, 0x66, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x12, 0x6f, 0x0a, 0x13, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x5f, 0x64, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x52, 0x12, 0x6d, 0x69, 0x63, 0x72, 0x6f, 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x6d, 0x0a, 0x13, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x6d, 0x65, 0x64, 0x69, 0x61, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x54, 0x79, 0x70, 0x65, 0x52, 0x11, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x54, 0x79, 0x70, 0x65, 0x12, 0x73, 0x0a, 0x15, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x13, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x32, 0x0a, 0x15, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x13, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2c, 0x0a, 0x12, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x6d, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x4d, 0x69, 0x6d, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x74, 0x6f, 0x70, 0x69, 0x63, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x54, 0x6f, 0x70, 0x69, 0x63, 0x22, 0xc5, 0x01, 0x0a, 0x0f, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x20, 0x0a, 0x1c, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x44, 0x49, 0x53, 0x43, 0x55, 0x53, 0x53, 0x49, 0x4f, 0x4e, 0x10, 0x01, 0x12, 0x10, 0x0a, 0x0c, 0x50, 0x52, 0x45, 0x53, 0x45, 0x4e, 0x54, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x02, 0x12, 0x0e, 0x0a, 0x0a, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x5f, 0x43, 0x41, 0x4c, 0x4c, 0x10, 0x03, 0x12, 0x0d, 0x0a, 0x09, 0x56, 0x4f, 0x49, 0x43, 0x45, 0x4d, 0x41, 0x49, 0x4c, 0x10, 0x04, 0x12, 0x1b, 0x0a, 0x17, 0x50, 0x52, 0x4f, 0x46, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x4c, 0x59, 0x5f, 0x50, 0x52, 0x4f, 0x44, 0x55, 0x43, 0x45, 0x44, 0x10, 0x05, 0x12, 0x10, 0x0a, 0x0c, 0x56, 0x4f, 0x49, 0x43, 0x45, 0x5f, 0x53, 0x45, 0x41, 0x52, 0x43, 0x48, 0x10, 0x06, 0x12, 0x11, 0x0a, 0x0d, 0x56, 0x4f, 0x49, 0x43, 0x45, 0x5f, 0x43, 0x4f, 0x4d, 0x4d, 0x41, 0x4e, 0x44, 0x10, 0x07, 0x12, 0x0d, 0x0a, 0x09, 0x44, 0x49, 0x43, 0x54, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x08, 0x22, 0x64, 0x0a, 0x12, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x12, 0x23, 0x0a, 0x1f, 0x4d, 0x49, 0x43, 0x52, 0x4f, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x5f, 0x44, 0x49, 0x53, 0x54, 0x41, 0x4e, 0x43, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x4e, 0x45, 0x41, 0x52, 0x46, 0x49, 0x45, 0x4c, 0x44, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x4d, 0x49, 0x44, 0x46, 0x49, 0x45, 0x4c, 0x44, 0x10, 0x02, 0x12, 0x0c, 0x0a, 0x08, 0x46, 0x41, 0x52, 0x46, 0x49, 0x45, 0x4c, 0x44, 0x10, 0x03, 0x22, 0x4e, 0x0a, 0x11, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x54, 0x79, 0x70, 0x65, 0x12, 0x23, 0x0a, 0x1f, 0x4f, 0x52, 0x49, 0x47, 0x49, 0x4e, 0x41, 0x4c, 0x5f, 0x4d, 0x45, 0x44, 0x49, 0x41, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x41, 0x55, 0x44, 0x49, 0x4f, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x56, 0x49, 0x44, 0x45, 0x4f, 0x10, 0x02, 0x22, 0xa4, 0x01, 0x0a, 0x13, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x25, 0x0a, 0x21, 0x52, 0x45, 0x43, 0x4f, 0x52, 0x44, 0x49, 0x4e, 0x47, 0x5f, 0x44, 0x45, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x53, 0x4d, 0x41, 0x52, 0x54, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x10, 0x01, 0x12, 0x06, 0x0a, 0x02, 0x50, 0x43, 0x10, 0x02, 0x12, 0x0e, 0x0a, 0x0a, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x5f, 0x4c, 0x49, 0x4e, 0x45, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x56, 0x45, 0x48, 0x49, 0x43, 0x4c, 0x45, 0x10, 0x04, 0x12, 0x18, 0x0a, 0x14, 0x4f, 0x54, 0x48, 0x45, 0x52, 0x5f, 0x4f, 0x55, 0x54, 0x44, 0x4f, 0x4f, 0x52, 0x5f, 0x44, 0x45, 0x56, 0x49, 0x43, 0x45, 0x10, 0x05, 0x12, 0x17, 0x0a, 0x13, 0x4f, 0x54, 0x48, 0x45, 0x52, 0x5f, 0x49, 0x4e, 0x44, 0x4f, 0x4f, 0x52, 0x5f, 0x44, 0x45, 0x56, 0x49, 0x43, 0x45, 0x10, 0x06, 0x22, 0x29, 0x0a, 0x0d, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x68, 0x72, 0x61, 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x70, 0x68, 0x72, 0x61, 0x73, 0x65, 0x73, 0x22, 0x52, 0x0a, 0x10, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x75, 0x64, 0x69, 0x6f, 0x12, 0x1a, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x03, 0x75, 0x72, 0x69, 0x42, 0x0e, 0x0a, 0x0c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x22, 0x5e, 0x0a, 0x11, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x22, 0x69, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x22, 0xca, 0x01, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x44, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x22, 0xd2, 0x02, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x4c, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, 0x6e, 0x0a, 0x11, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x42, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x22, 0x4c, 0x0a, 0x0f, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x18, 0x53, 0x50, 0x45, 0x45, 0x43, 0x48, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x45, 0x4e, 0x44, 0x5f, 0x4f, 0x46, 0x5f, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x5f, 0x55, 0x54, 0x54, 0x45, 0x52, 0x41, 0x4e, 0x43, 0x45, 0x10, 0x01, 0x22, 0xbd, 0x02, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x58, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x69, 0x73, 0x5f, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x73, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x02, 0x52, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x12, 0x41, 0x0a, 0x0f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x94, 0x01, 0x0a, 0x17, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x58, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x22, 0x96, 0x01, 0x0a, 0x1c, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x36, 0x0a, 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x57, 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0xb4, 0x01, 0x0a, 0x08, 0x57, 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x38, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x34, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x24, 0x0a, 0x0b, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0a, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x54, 0x61, 0x67, 0x32, 0xd1, 0x04, 0x0a, 0x06, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x12, 0x90, 0x01, 0x0a, 0x09, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x2e, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x19, 0x22, 0x14, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x12, 0xe4, 0x01, 0x0a, 0x14, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x78, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x24, 0x22, 0x1f, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0xca, 0x41, 0x3c, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x81, 0x01, 0x0a, 0x12, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x31, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x1a, 0x49, 0xca, 0x41, 0x15, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0x72, 0x0a, 0x1a, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2f, 0x76, 0x31, 0x3b, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x43, 0x53, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_cloud_speech_v1_cloud_speech_proto_rawDescOnce sync.Once file_google_cloud_speech_v1_cloud_speech_proto_rawDescData = file_google_cloud_speech_v1_cloud_speech_proto_rawDesc ) func file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP() []byte { file_google_cloud_speech_v1_cloud_speech_proto_rawDescOnce.Do(func() { file_google_cloud_speech_v1_cloud_speech_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_cloud_speech_v1_cloud_speech_proto_rawDescData) }) return file_google_cloud_speech_v1_cloud_speech_proto_rawDescData } var file_google_cloud_speech_v1_cloud_speech_proto_enumTypes = make([]protoimpl.EnumInfo, 6) var file_google_cloud_speech_v1_cloud_speech_proto_msgTypes = make([]protoimpl.MessageInfo, 17) var file_google_cloud_speech_v1_cloud_speech_proto_goTypes = []interface{}{ (RecognitionConfig_AudioEncoding)(0), // 0: google.cloud.speech.v1.RecognitionConfig.AudioEncoding (RecognitionMetadata_InteractionType)(0), // 1: google.cloud.speech.v1.RecognitionMetadata.InteractionType (RecognitionMetadata_MicrophoneDistance)(0), // 2: google.cloud.speech.v1.RecognitionMetadata.MicrophoneDistance (RecognitionMetadata_OriginalMediaType)(0), // 3: google.cloud.speech.v1.RecognitionMetadata.OriginalMediaType (RecognitionMetadata_RecordingDeviceType)(0), // 4: google.cloud.speech.v1.RecognitionMetadata.RecordingDeviceType (StreamingRecognizeResponse_SpeechEventType)(0), // 5: google.cloud.speech.v1.StreamingRecognizeResponse.SpeechEventType (*RecognizeRequest)(nil), // 6: google.cloud.speech.v1.RecognizeRequest (*LongRunningRecognizeRequest)(nil), // 7: google.cloud.speech.v1.LongRunningRecognizeRequest (*StreamingRecognizeRequest)(nil), // 8: google.cloud.speech.v1.StreamingRecognizeRequest (*StreamingRecognitionConfig)(nil), // 9: google.cloud.speech.v1.StreamingRecognitionConfig (*RecognitionConfig)(nil), // 10: google.cloud.speech.v1.RecognitionConfig (*SpeakerDiarizationConfig)(nil), // 11: google.cloud.speech.v1.SpeakerDiarizationConfig (*RecognitionMetadata)(nil), // 12: google.cloud.speech.v1.RecognitionMetadata (*SpeechContext)(nil), // 13: google.cloud.speech.v1.SpeechContext (*RecognitionAudio)(nil), // 14: google.cloud.speech.v1.RecognitionAudio (*RecognizeResponse)(nil), // 15: google.cloud.speech.v1.RecognizeResponse (*LongRunningRecognizeResponse)(nil), // 16: google.cloud.speech.v1.LongRunningRecognizeResponse (*LongRunningRecognizeMetadata)(nil), // 17: google.cloud.speech.v1.LongRunningRecognizeMetadata (*StreamingRecognizeResponse)(nil), // 18: google.cloud.speech.v1.StreamingRecognizeResponse (*StreamingRecognitionResult)(nil), // 19: google.cloud.speech.v1.StreamingRecognitionResult (*SpeechRecognitionResult)(nil), // 20: google.cloud.speech.v1.SpeechRecognitionResult (*SpeechRecognitionAlternative)(nil), // 21: google.cloud.speech.v1.SpeechRecognitionAlternative (*WordInfo)(nil), // 22: google.cloud.speech.v1.WordInfo (*timestamppb.Timestamp)(nil), // 23: google.protobuf.Timestamp (*status.Status)(nil), // 24: google.rpc.Status (*durationpb.Duration)(nil), // 25: google.protobuf.Duration (*longrunning.Operation)(nil), // 26: google.longrunning.Operation } var file_google_cloud_speech_v1_cloud_speech_proto_depIdxs = []int32{ 10, // 0: google.cloud.speech.v1.RecognizeRequest.config:type_name -> google.cloud.speech.v1.RecognitionConfig 14, // 1: google.cloud.speech.v1.RecognizeRequest.audio:type_name -> google.cloud.speech.v1.RecognitionAudio 10, // 2: google.cloud.speech.v1.LongRunningRecognizeRequest.config:type_name -> google.cloud.speech.v1.RecognitionConfig 14, // 3: google.cloud.speech.v1.LongRunningRecognizeRequest.audio:type_name -> google.cloud.speech.v1.RecognitionAudio 9, // 4: google.cloud.speech.v1.StreamingRecognizeRequest.streaming_config:type_name -> google.cloud.speech.v1.StreamingRecognitionConfig 10, // 5: google.cloud.speech.v1.StreamingRecognitionConfig.config:type_name -> google.cloud.speech.v1.RecognitionConfig 0, // 6: google.cloud.speech.v1.RecognitionConfig.encoding:type_name -> google.cloud.speech.v1.RecognitionConfig.AudioEncoding 13, // 7: google.cloud.speech.v1.RecognitionConfig.speech_contexts:type_name -> google.cloud.speech.v1.SpeechContext 11, // 8: google.cloud.speech.v1.RecognitionConfig.diarization_config:type_name -> google.cloud.speech.v1.SpeakerDiarizationConfig 12, // 9: google.cloud.speech.v1.RecognitionConfig.metadata:type_name -> google.cloud.speech.v1.RecognitionMetadata 1, // 10: google.cloud.speech.v1.RecognitionMetadata.interaction_type:type_name -> google.cloud.speech.v1.RecognitionMetadata.InteractionType 2, // 11: google.cloud.speech.v1.RecognitionMetadata.microphone_distance:type_name -> google.cloud.speech.v1.RecognitionMetadata.MicrophoneDistance 3, // 12: google.cloud.speech.v1.RecognitionMetadata.original_media_type:type_name -> google.cloud.speech.v1.RecognitionMetadata.OriginalMediaType 4, // 13: google.cloud.speech.v1.RecognitionMetadata.recording_device_type:type_name -> google.cloud.speech.v1.RecognitionMetadata.RecordingDeviceType 20, // 14: google.cloud.speech.v1.RecognizeResponse.results:type_name -> google.cloud.speech.v1.SpeechRecognitionResult 20, // 15: google.cloud.speech.v1.LongRunningRecognizeResponse.results:type_name -> google.cloud.speech.v1.SpeechRecognitionResult 23, // 16: google.cloud.speech.v1.LongRunningRecognizeMetadata.start_time:type_name -> google.protobuf.Timestamp 23, // 17: google.cloud.speech.v1.LongRunningRecognizeMetadata.last_update_time:type_name -> google.protobuf.Timestamp 24, // 18: google.cloud.speech.v1.StreamingRecognizeResponse.error:type_name -> google.rpc.Status 19, // 19: google.cloud.speech.v1.StreamingRecognizeResponse.results:type_name -> google.cloud.speech.v1.StreamingRecognitionResult 5, // 20: google.cloud.speech.v1.StreamingRecognizeResponse.speech_event_type:type_name -> google.cloud.speech.v1.StreamingRecognizeResponse.SpeechEventType 21, // 21: google.cloud.speech.v1.StreamingRecognitionResult.alternatives:type_name -> google.cloud.speech.v1.SpeechRecognitionAlternative 25, // 22: google.cloud.speech.v1.StreamingRecognitionResult.result_end_time:type_name -> google.protobuf.Duration 21, // 23: google.cloud.speech.v1.SpeechRecognitionResult.alternatives:type_name -> google.cloud.speech.v1.SpeechRecognitionAlternative 22, // 24: google.cloud.speech.v1.SpeechRecognitionAlternative.words:type_name -> google.cloud.speech.v1.WordInfo 25, // 25: google.cloud.speech.v1.WordInfo.start_time:type_name -> google.protobuf.Duration 25, // 26: google.cloud.speech.v1.WordInfo.end_time:type_name -> google.protobuf.Duration 6, // 27: google.cloud.speech.v1.Speech.Recognize:input_type -> google.cloud.speech.v1.RecognizeRequest 7, // 28: google.cloud.speech.v1.Speech.LongRunningRecognize:input_type -> google.cloud.speech.v1.LongRunningRecognizeRequest 8, // 29: google.cloud.speech.v1.Speech.StreamingRecognize:input_type -> google.cloud.speech.v1.StreamingRecognizeRequest 15, // 30: google.cloud.speech.v1.Speech.Recognize:output_type -> google.cloud.speech.v1.RecognizeResponse 26, // 31: google.cloud.speech.v1.Speech.LongRunningRecognize:output_type -> google.longrunning.Operation 18, // 32: google.cloud.speech.v1.Speech.StreamingRecognize:output_type -> google.cloud.speech.v1.StreamingRecognizeResponse 30, // [30:33] is the sub-list for method output_type 27, // [27:30] is the sub-list for method input_type 27, // [27:27] is the sub-list for extension type_name 27, // [27:27] is the sub-list for extension extendee 0, // [0:27] is the sub-list for field type_name } func init() { file_google_cloud_speech_v1_cloud_speech_proto_init() } func file_google_cloud_speech_v1_cloud_speech_proto_init() { if File_google_cloud_speech_v1_cloud_speech_proto != nil { return } if !protoimpl.UnsafeEnabled { file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RecognizeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*LongRunningRecognizeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StreamingRecognizeRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StreamingRecognitionConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RecognitionConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SpeakerDiarizationConfig); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RecognitionMetadata); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SpeechContext); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RecognitionAudio); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RecognizeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*LongRunningRecognizeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*LongRunningRecognizeMetadata); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StreamingRecognizeResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StreamingRecognitionResult); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SpeechRecognitionResult); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SpeechRecognitionAlternative); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*WordInfo); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[2].OneofWrappers = []interface{}{ (*StreamingRecognizeRequest_StreamingConfig)(nil), (*StreamingRecognizeRequest_AudioContent)(nil), } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[8].OneofWrappers = []interface{}{ (*RecognitionAudio_Content)(nil), (*RecognitionAudio_Uri)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_speech_v1_cloud_speech_proto_rawDesc, NumEnums: 6, NumMessages: 17, NumExtensions: 0, NumServices: 1, }, GoTypes: file_google_cloud_speech_v1_cloud_speech_proto_goTypes, DependencyIndexes: file_google_cloud_speech_v1_cloud_speech_proto_depIdxs, EnumInfos: file_google_cloud_speech_v1_cloud_speech_proto_enumTypes, MessageInfos: file_google_cloud_speech_v1_cloud_speech_proto_msgTypes, }.Build() File_google_cloud_speech_v1_cloud_speech_proto = out.File file_google_cloud_speech_v1_cloud_speech_proto_rawDesc = nil file_google_cloud_speech_v1_cloud_speech_proto_goTypes = nil file_google_cloud_speech_v1_cloud_speech_proto_depIdxs = nil } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // SpeechClient is the client API for Speech service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type SpeechClient interface { // Performs synchronous speech recognition: receive results after all audio // has been sent and processed. Recognize(ctx context.Context, in *RecognizeRequest, opts ...grpc.CallOption) (*RecognizeResponse, error) // Performs asynchronous speech recognition: receive results via the // google.longrunning.Operations interface. Returns either an // `Operation.error` or an `Operation.response` which contains // a `LongRunningRecognizeResponse` message. // For more information on asynchronous speech recognition, see the // [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). LongRunningRecognize(ctx context.Context, in *LongRunningRecognizeRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Performs bidirectional streaming speech recognition: receive results while // sending audio. This method is only available via the gRPC API (not REST). StreamingRecognize(ctx context.Context, opts ...grpc.CallOption) (Speech_StreamingRecognizeClient, error) } type speechClient struct { cc grpc.ClientConnInterface } func NewSpeechClient(cc grpc.ClientConnInterface) SpeechClient { return &speechClient{cc} } func (c *speechClient) Recognize(ctx context.Context, in *RecognizeRequest, opts ...grpc.CallOption) (*RecognizeResponse, error) { out := new(RecognizeResponse) err := c.cc.Invoke(ctx, "/google.cloud.speech.v1.Speech/Recognize", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *speechClient) LongRunningRecognize(ctx context.Context, in *LongRunningRecognizeRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) { out := new(longrunning.Operation) err := c.cc.Invoke(ctx, "/google.cloud.speech.v1.Speech/LongRunningRecognize", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *speechClient) StreamingRecognize(ctx context.Context, opts ...grpc.CallOption) (Speech_StreamingRecognizeClient, error) { stream, err := c.cc.NewStream(ctx, &_Speech_serviceDesc.Streams[0], "/google.cloud.speech.v1.Speech/StreamingRecognize", opts...) if err != nil { return nil, err } x := &speechStreamingRecognizeClient{stream} return x, nil } type Speech_StreamingRecognizeClient interface { Send(*StreamingRecognizeRequest) error Recv() (*StreamingRecognizeResponse, error) grpc.ClientStream } type speechStreamingRecognizeClient struct { grpc.ClientStream } func (x *speechStreamingRecognizeClient) Send(m *StreamingRecognizeRequest) error { return x.ClientStream.SendMsg(m) } func (x *speechStreamingRecognizeClient) Recv() (*StreamingRecognizeResponse, error) { m := new(StreamingRecognizeResponse) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // SpeechServer is the server API for Speech service. type SpeechServer interface { // Performs synchronous speech recognition: receive results after all audio // has been sent and processed. Recognize(context.Context, *RecognizeRequest) (*RecognizeResponse, error) // Performs asynchronous speech recognition: receive results via the // google.longrunning.Operations interface. Returns either an // `Operation.error` or an `Operation.response` which contains // a `LongRunningRecognizeResponse` message. // For more information on asynchronous speech recognition, see the // [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). LongRunningRecognize(context.Context, *LongRunningRecognizeRequest) (*longrunning.Operation, error) // Performs bidirectional streaming speech recognition: receive results while // sending audio. This method is only available via the gRPC API (not REST). StreamingRecognize(Speech_StreamingRecognizeServer) error } // UnimplementedSpeechServer can be embedded to have forward compatible implementations. type UnimplementedSpeechServer struct { } func (*UnimplementedSpeechServer) Recognize(context.Context, *RecognizeRequest) (*RecognizeResponse, error) { return nil, status1.Errorf(codes.Unimplemented, "method Recognize not implemented") } func (*UnimplementedSpeechServer) LongRunningRecognize(context.Context, *LongRunningRecognizeRequest) (*longrunning.Operation, error) { return nil, status1.Errorf(codes.Unimplemented, "method LongRunningRecognize not implemented") } func (*UnimplementedSpeechServer) StreamingRecognize(Speech_StreamingRecognizeServer) error { return status1.Errorf(codes.Unimplemented, "method StreamingRecognize not implemented") } func
(s *grpc.Server, srv SpeechServer) { s.RegisterService(&_Speech_serviceDesc, srv) } func _Speech_Recognize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RecognizeRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(SpeechServer).Recognize(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.speech.v1.Speech/Recognize", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SpeechServer).Recognize(ctx, req.(*RecognizeRequest)) } return interceptor(ctx, in, info, handler) } func _Speech_LongRunningRecognize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(LongRunningRecognizeRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(SpeechServer).LongRunningRecognize(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/google.cloud.speech.v1.Speech/LongRunningRecognize", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SpeechServer).LongRunningRecognize(ctx, req.(*LongRunningRecognizeRequest)) } return interceptor(ctx, in, info, handler) } func _Speech_StreamingRecognize_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(SpeechServer).StreamingRecognize(&speechStreamingRecognizeServer{stream}) } type Speech_StreamingRecognizeServer interface { Send(*StreamingRecognizeResponse) error Recv() (*StreamingRecognizeRequest, error) grpc.ServerStream } type speechStreamingRecognizeServer struct { grpc.ServerStream } func (x *speechStreamingRecognizeServer) Send(m *StreamingRecognizeResponse) error { return x.ServerStream.SendMsg(m) } func (x *speechStreamingRecognizeServer) Recv() (*StreamingRecognizeRequest, error) { m := new(StreamingRecognizeRequest) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } var _Speech_serviceDesc = grpc.ServiceDesc{ ServiceName: "google.cloud.speech.v1.Speech", HandlerType: (*SpeechServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Recognize", Handler: _Speech_Recognize_Handler, }, { MethodName: "LongRunningRecognize", Handler: _Speech_LongRunningRecognize_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "StreamingRecognize", Handler: _Speech_StreamingRecognize_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "google/cloud/speech/v1/cloud_speech.proto", }
RegisterSpeechServer
test_benchmark_trpo.py
''' This script creates a regression test over garage-TRPO and baselines-TRPO. Unlike garage, baselines doesn't set max_path_length. It keeps steps the action until it's done. So we introduced tests.wrappers.AutoStopEnv wrapper to set done=True when it reaches max_path_length. We also need to change the garage.tf.samplers.BatchSampler to smooth the reward curve. ''' import datetime import os.path as osp import random from baselines import logger as baselines_logger from baselines.bench import benchmarks from baselines.common.tf_util import _PLACEHOLDER_CACHE from baselines.ppo1.mlp_policy import MlpPolicy from baselines.trpo_mpi import trpo_mpi import dowel from dowel import logger as dowel_logger import gym import pytest import tensorflow as tf from garage.envs import normalize from garage.experiment import deterministic from garage.tf.algos import TRPO from garage.tf.baselines import GaussianMLPBaseline from garage.tf.envs import TfEnv from garage.tf.experiment import LocalTFRunner from garage.tf.policies import GaussianMLPPolicy import tests.helpers as Rh from tests.wrappers import AutoStopEnv class TestBenchmarkPPO: '''Compare benchmarks between garage and baselines.''' @pytest.mark.huge def test_benchmark_trpo(self): ''' Compare benchmarks between garage and baselines. :return: ''' mujoco1m = benchmarks.get_benchmark('Mujoco1M') timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f') benchmark_dir = './data/local/benchmarks/trpo/%s/' % timestamp result_json = {} for task in mujoco1m['tasks']: env_id = task['env_id'] env = gym.make(env_id) baseline_env = AutoStopEnv(env_name=env_id, max_path_length=100) seeds = random.sample(range(100), task['trials']) task_dir = osp.join(benchmark_dir, env_id) plt_file = osp.join(benchmark_dir, '{}_benchmark.png'.format(env_id)) baselines_csvs = [] garage_csvs = [] for trial in range(task['trials']): _PLACEHOLDER_CACHE.clear() seed = seeds[trial] trial_dir = task_dir + '/trial_%d_seed_%d' % (trial + 1, seed) garage_dir = trial_dir + '/garage' baselines_dir = trial_dir + '/baselines' with tf.Graph().as_default(): # Run garage algorithms env.reset() garage_csv = run_garage(env, seed, garage_dir) # Run baseline algorithms baseline_env.reset() baselines_csv = run_baselines(baseline_env, seed, baselines_dir) garage_csvs.append(garage_csv) baselines_csvs.append(baselines_csv) Rh.plot( b_csvs=baselines_csvs, g_csvs=garage_csvs, g_x='Iteration', g_y='AverageReturn', b_x='EpThisIter', b_y='EpRewMean', trials=task['trials'], seeds=seeds, plt_file=plt_file, env_id=env_id, x_label='Iteration', y_label='AverageReturn') result_json[env_id] = Rh.create_json( b_csvs=baselines_csvs, g_csvs=garage_csvs, seeds=seeds, trails=task['trials'], g_x='Iteration', g_y='AverageReturn', b_x='TimestepsSoFar', b_y='EpRewMean', factor_g=1024, factor_b=1) env.close() Rh.write_file(result_json, 'TRPO') def run_garage(env, seed, log_dir): ''' Create garage model and training. Replace the trpo with the algorithm you want to run. :param env: Environment of the task. :param seed: Random seed for the trial. :param log_dir: Log dir path. :return:import baselines.common.tf_util as U ''' deterministic.set_seed(seed) with LocalTFRunner() as runner: env = TfEnv(normalize(env)) policy = GaussianMLPPolicy( env_spec=env.spec, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, output_nonlinearity=None, ) baseline = GaussianMLPBaseline( env_spec=env.spec, regressor_args=dict( hidden_sizes=(32, 32), use_trust_region=True, ), ) algo = TRPO( env_spec=env.spec, policy=policy, baseline=baseline, max_path_length=100, discount=0.99, gae_lambda=0.98, max_kl_step=0.01, policy_ent_coeff=0.0, ) # Set up logger since we are not using run_experiment tabular_log_file = osp.join(log_dir, 'progress.csv') dowel_logger.add_output(dowel.CsvOutput(tabular_log_file)) dowel_logger.add_output(dowel.StdOutput()) dowel_logger.add_output(dowel.TensorBoardOutput(log_dir)) runner.setup(algo, env) runner.train(n_epochs=976, batch_size=1024) dowel_logger.remove_all() return tabular_log_file def run_baselines(env, seed, log_dir): ''' Create baselines model and training. Replace the trpo and its training with the algorithm you want to run. :param env: Environment of the task. :param seed: Random seed for the trial. :param log_dir: Log dir path. :return ''' with tf.compat.v1.Session().as_default(): baselines_logger.configure(log_dir) def policy_fn(name, ob_space, ac_space): return MlpPolicy( name=name, ob_space=ob_space, ac_space=ac_space, hid_size=32, num_hid_layers=2)
trpo_mpi.learn( env, policy_fn, timesteps_per_batch=1024, max_kl=0.01, cg_iters=10, cg_damping=0.1, max_timesteps=int(1e6), gamma=0.99, lam=0.98, vf_iters=5, vf_stepsize=1e-3) env.close() return osp.join(log_dir, 'progress.csv')
parser.js
define([ '../less-error', '../tree/index', '../visitors/index', './parser-input', '../utils', '../functions/function-registry' ], function (__module__0, __module__1, __module__2, __module__3, __module__4, __module__5) { 'use strict'; var exports = {}; var module = { exports: {} }; var LessError = __module__0, tree = __module__1, visitors = __module__2, getParserInput = __module__3, utils = __module__4, functionRegistry = __module__5; var Parser = function Parser(context, imports, fileInfo) { var parsers, parserInput = getParserInput(); function error(msg, type) { throw new LessError({ index: parserInput.i, filename: fileInfo.filename, type: type || 'Syntax', message: msg }, imports); } function expect(arg, msg) { var result = arg instanceof Function ? arg.call(parsers) : parserInput.$re(arg); if (result) { return result; } error(msg || (typeof arg === 'string' ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'" : 'unexpected token')); } function expectChar(arg, msg) { if (parserInput.$char(arg)) { return arg; } error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'"); } function getDebugInfo(index) { var filename = fileInfo.filename; return { lineNumber: utils.getLocation(index, parserInput.getInput()).line + 1, fileName: filename }; } function parseNode(str, parseList, currentIndex, fileInfo, callback) { var result, returnNodes = []; var parser = parserInput; try { parser.start(str, false, function fail(msg, index) { callback({ message: msg, index: index + currentIndex }); }); for (var x = 0, p, i; p = parseList[x]; x++) { i = parser.i; result = parsers[p](); if (result) { result._index = i + currentIndex; result._fileInfo = fileInfo; returnNodes.push(result); } else { returnNodes.push(null); } } var endInfo = parser.end(); if (endInfo.isFinished) { callback(null, returnNodes); } else { callback(true, null); } } catch (e) { throw new LessError({ index: e.index + currentIndex, message: e.message }, imports, fileInfo.filename); } } return { parserInput: parserInput, imports: imports, fileInfo: fileInfo, parseNode: parseNode, parse: function (str, callback, additionalData) { var root, error = null, globalVars, modifyVars, ignored, preText = ''; globalVars = additionalData && additionalData.globalVars ? Parser.serializeVars(additionalData.globalVars) + '\n' : ''; modifyVars = additionalData && additionalData.modifyVars ? '\n' + Parser.serializeVars(additionalData.modifyVars) : ''; if (context.pluginManager) { var preProcessors = context.pluginManager.getPreProcessors(); for (var i = 0; i < preProcessors.length; i++) { str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo }); } } if (globalVars || additionalData && additionalData.banner) { preText = (additionalData && additionalData.banner ? additionalData.banner : '') + globalVars; ignored = imports.contentsIgnoredChars; ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0; ignored[fileInfo.filename] += preText.length; } str = str.replace(/\r\n?/g, '\n'); str = preText + str.replace(/^\uFEFF/, '') + modifyVars; imports.contents[fileInfo.filename] = str; try { parserInput.start(str, context.chunkInput, function fail(msg, index) { throw new LessError({ index: index, type: 'Parse', message: msg, filename: fileInfo.filename }, imports); }); tree.Node.prototype.parse = this; root = new tree.Ruleset(null, this.parsers.primary()); tree.Node.prototype.rootNode = root; root.root = true; root.firstRoot = true; root.functionRegistry = functionRegistry.inherit(); } catch (e) { return callback(new LessError(e, imports, fileInfo.filename)); } var endInfo = parserInput.end(); if (!endInfo.isFinished) { var message = endInfo.furthestPossibleErrorMessage; if (!message) { message = 'Unrecognised input'; if (endInfo.furthestChar === '}') { message += ". Possibly missing opening '{'"; } else if (endInfo.furthestChar === ')') { message += ". Possibly missing opening '('"; } else if (endInfo.furthestReachedEnd) { message += '. Possibly missing something'; } } error = new LessError({ type: 'Parse', message: message, index: endInfo.furthest, filename: fileInfo.filename }, imports); } var finish = function (e) { e = error || e || imports.error; if (e) { if (!(e instanceof LessError)) { e = new LessError(e, imports, fileInfo.filename); } return callback(e); } else { return callback(null, root); } }; if (context.processImports !== false) { new visitors.ImportVisitor(imports, finish).run(root); } else { return finish(); } }, parsers: parsers = { primary: function () { var mixin = this.mixin, root = [], node; while (true) { while (true) { node = this.comment(); if (!node) { break; } root.push(node); } if (parserInput.finished) { break; } if (parserInput.peek('}')) { break; } node = this.extendRule(); if (node) { root = root.concat(node); continue; } node = mixin.definition() || this.declaration() || this.ruleset() || mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule(); if (node) { root.push(node); } else { var foundSemiColon = false; while (parserInput.$char(';')) { foundSemiColon = true; } if (!foundSemiColon) { break; } } } return root; }, comment: function () { if (parserInput.commentStore.length) { var comment = parserInput.commentStore.shift(); return new tree.Comment(comment.text, comment.isLineComment, comment.index, fileInfo); } }, entities: { mixinLookup: function () { return parsers.mixin.call(true, true); }, quoted: function (forceEscaped) { var str, index = parserInput.i, isEscaped = false; parserInput.save(); if (parserInput.$char('~')) { isEscaped = true; } else if (forceEscaped) { parserInput.restore(); return; } str = parserInput.$quoted(); if (!str) { parserInput.restore(); return; } parserInput.forget(); return new tree.Quoted(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo); }, keyword: function () { var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/); if (k) { return tree.Color.fromKeyword(k) || new tree.Keyword(k); } }, call: function () { var name, args, func, index = parserInput.i; if (parserInput.peek(/^url\(/i)) { return; } parserInput.save(); name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/); if (!name) { parserInput.forget(); return; } name = name[1]; func = this.customFuncCall(name); if (func) { args = func.parse(); if (args && func.stop) { parserInput.forget(); return args; } } args = this.arguments(args); if (!parserInput.$char(')')) { parserInput.restore("Could not parse call arguments or missing ')'"); return; } parserInput.forget(); return new tree.Call(name, args, index, fileInfo); }, customFuncCall: function (name) { return { alpha: f(parsers.ieAlpha, true), boolean: f(condition), 'if': f(condition) }[name.toLowerCase()]; function
(parse, stop) { return { parse: parse, stop: stop }; } function condition() { return [expect(parsers.condition, 'expected condition')]; } }, arguments: function (prevArgs) { var argsComma = prevArgs || [], argsSemiColon = [], isSemiColonSeparated, value; parserInput.save(); while (true) { if (prevArgs) { prevArgs = false; } else { value = parsers.detachedRuleset() || this.assignment() || parsers.expression(); if (!value) { break; } if (value.value && value.value.length == 1) { value = value.value[0]; } argsComma.push(value); } if (parserInput.$char(',')) { continue; } if (parserInput.$char(';') || isSemiColonSeparated) { isSemiColonSeparated = true; value = argsComma.length < 1 ? argsComma[0] : new tree.Value(argsComma); argsSemiColon.push(value); argsComma = []; } } parserInput.forget(); return isSemiColonSeparated ? argsSemiColon : argsComma; }, literal: function () { return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor(); }, assignment: function () { var key, value; parserInput.save(); key = parserInput.$re(/^\w+(?=\s?=)/i); if (!key) { parserInput.restore(); return; } if (!parserInput.$char('=')) { parserInput.restore(); return; } value = parsers.entity(); if (value) { parserInput.forget(); return new tree.Assignment(key, value); } else { parserInput.restore(); } }, url: function () { var value, index = parserInput.i; parserInput.autoCommentAbsorb = false; if (!parserInput.$str('url(')) { parserInput.autoCommentAbsorb = true; return; } value = this.quoted() || this.variable() || this.property() || parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ''; parserInput.autoCommentAbsorb = true; expectChar(')'); return new tree.URL(value.value != null || value instanceof tree.Variable || value instanceof tree.Property ? value : new tree.Anonymous(value, index), index, fileInfo); }, variable: function () { var ch, name, index = parserInput.i; parserInput.save(); if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) { ch = parserInput.currentChar(); if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) { var result = parsers.variableCall(name); if (result) { parserInput.forget(); return result; } } parserInput.forget(); return new tree.Variable(name, index, fileInfo); } parserInput.restore(); }, variableCurly: function () { var curly, index = parserInput.i; if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) { return new tree.Variable('@' + curly[1], index, fileInfo); } }, property: function () { var name, index = parserInput.i; if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) { return new tree.Property(name, index, fileInfo); } }, propertyCurly: function () { var curly, index = parserInput.i; if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) { return new tree.Property('$' + curly[1], index, fileInfo); } }, color: function () { var rgb; if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})/))) { return new tree.Color(rgb[1], undefined, rgb[0]); } }, colorKeyword: function () { parserInput.save(); var autoCommentAbsorb = parserInput.autoCommentAbsorb; parserInput.autoCommentAbsorb = false; var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/); parserInput.autoCommentAbsorb = autoCommentAbsorb; if (!k) { parserInput.forget(); return; } parserInput.restore(); var color = tree.Color.fromKeyword(k); if (color) { parserInput.$str(k); return color; } }, dimension: function () { if (parserInput.peekNotNumeric()) { return; } var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i); if (value) { return new tree.Dimension(value[1], value[2]); } }, unicodeDescriptor: function () { var ud; ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); if (ud) { return new tree.UnicodeDescriptor(ud[0]); } }, javascript: function () { var js, index = parserInput.i; parserInput.save(); var escape = parserInput.$char('~'); var jsQuote = parserInput.$char('`'); if (!jsQuote) { parserInput.restore(); return; } js = parserInput.$re(/^[^`]*`/); if (js) { parserInput.forget(); return new tree.JavaScript(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo); } parserInput.restore('invalid javascript definition'); } }, variable: function () { var name; if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; } }, variableCall: function (parsedName) { var lookups, important, i = parserInput.i, inValue = !!parsedName, name = parsedName; parserInput.save(); if (name || parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/))) { lookups = this.mixin.ruleLookups(); if (!lookups && (inValue && parserInput.$str('()') !== '()' || name[2] !== '()')) { parserInput.restore("Missing '[...]' lookup in variable call"); return; } if (!inValue) { name = name[1]; } if (lookups && parsers.important()) { important = true; } var call = new tree.VariableCall(name, i, fileInfo); if (!inValue && parsers.end()) { parserInput.forget(); return call; } else { parserInput.forget(); return new tree.NamespaceValue(call, lookups, important, i, fileInfo); } } parserInput.restore(); }, extend: function (isRule) { var elements, e, index = parserInput.i, option, extendList, extend; if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) { return; } do { option = null; elements = null; while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) { e = this.element(); if (!e) { break; } if (elements) { elements.push(e); } else { elements = [e]; } } option = option && option[1]; if (!elements) { error('Missing target selector for :extend().'); } extend = new tree.Extend(new tree.Selector(elements), option, index, fileInfo); if (extendList) { extendList.push(extend); } else { extendList = [extend]; } } while (parserInput.$char(',')); expect(/^\)/); if (isRule) { expect(/^;/); } return extendList; }, extendRule: function () { return this.extend(true); }, mixin: { call: function (inValue, getLookup) { var s = parserInput.currentChar(), important = false, lookups, index = parserInput.i, elements, args, hasParens; if (s !== '.' && s !== '#') { return; } parserInput.save(); elements = this.elements(); if (elements) { if (parserInput.$char('(')) { args = this.args(true).args; expectChar(')'); hasParens = true; } if (getLookup !== false) { lookups = this.ruleLookups(); } if (getLookup === true && !lookups) { parserInput.restore(); return; } if (inValue && !lookups && !hasParens) { parserInput.restore(); return; } if (!inValue && parsers.important()) { important = true; } if (inValue || parsers.end()) { parserInput.forget(); var mixin = new tree.mixin.Call(elements, args, index, fileInfo, !lookups && important); if (lookups) { return new tree.NamespaceValue(mixin, lookups, important); } else { return mixin; } } } parserInput.restore(); }, elements: function () { var elements, e, c, elem, elemIndex, re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/; while (true) { elemIndex = parserInput.i; e = parserInput.$re(re); if (!e) { break; } elem = new tree.Element(c, e, false, elemIndex, fileInfo); if (elements) { elements.push(elem); } else { elements = [elem]; } c = parserInput.$char('>'); } return elements; }, args: function (isCall) { var entities = parsers.entities, returner = { args: null, variadic: false }, expressions = [], argsSemiColon = [], argsComma = [], isSemiColonSeparated, expressionContainsNamed, name, nameLoop, value, arg, expand, hasSep = true; parserInput.save(); while (true) { if (isCall) { arg = parsers.detachedRuleset() || parsers.expression(); } else { parserInput.commentStore.length = 0; if (parserInput.$str('...')) { returner.variadic = true; if (parserInput.$char(';') && !isSemiColonSeparated) { isSemiColonSeparated = true; } (isSemiColonSeparated ? argsSemiColon : argsComma).push({ variadic: true }); break; } arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true); } if (!arg || !hasSep) { break; } nameLoop = null; if (arg.throwAwayComments) { arg.throwAwayComments(); } value = arg; var val = null; if (isCall) { if (arg.value && arg.value.length == 1) { val = arg.value[0]; } } else { val = arg; } if (val && (val instanceof tree.Variable || val instanceof tree.Property)) { if (parserInput.$char(':')) { if (expressions.length > 0) { if (isSemiColonSeparated) { error('Cannot mix ; and , as delimiter types'); } expressionContainsNamed = true; } value = parsers.detachedRuleset() || parsers.expression(); if (!value) { if (isCall) { error('could not understand value for named argument'); } else { parserInput.restore(); returner.args = []; return returner; } } nameLoop = name = val.name; } else if (parserInput.$str('...')) { if (!isCall) { returner.variadic = true; if (parserInput.$char(';') && !isSemiColonSeparated) { isSemiColonSeparated = true; } (isSemiColonSeparated ? argsSemiColon : argsComma).push({ name: arg.name, variadic: true }); break; } else { expand = true; } } else if (!isCall) { name = nameLoop = val.name; value = null; } } if (value) { expressions.push(value); } argsComma.push({ name: nameLoop, value: value, expand: expand }); if (parserInput.$char(',')) { hasSep = true; continue; } hasSep = parserInput.$char(';') === ';'; if (hasSep || isSemiColonSeparated) { if (expressionContainsNamed) { error('Cannot mix ; and , as delimiter types'); } isSemiColonSeparated = true; if (expressions.length > 1) { value = new tree.Value(expressions); } argsSemiColon.push({ name: name, value: value, expand: expand }); name = null; expressions = []; expressionContainsNamed = false; } } parserInput.forget(); returner.args = isSemiColonSeparated ? argsSemiColon : argsComma; return returner; }, definition: function () { var name, params = [], match, ruleset, cond, variadic = false; if (parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#' || parserInput.peek(/^[^{]*\}/)) { return; } parserInput.save(); match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); if (match) { name = match[1]; var argInfo = this.args(false); params = argInfo.args; variadic = argInfo.variadic; if (!parserInput.$char(')')) { parserInput.restore("Missing closing ')'"); return; } parserInput.commentStore.length = 0; if (parserInput.$str('when')) { cond = expect(parsers.conditions, 'expected condition'); } ruleset = parsers.block(); if (ruleset) { parserInput.forget(); return new tree.mixin.Definition(name, params, ruleset, cond, variadic); } else { parserInput.restore(); } } else { parserInput.forget(); } }, ruleLookups: function () { var rule, args, lookups = []; if (parserInput.currentChar() !== '[') { return; } while (true) { parserInput.save(); args = null; rule = this.lookupValue(); if (!rule && rule !== '') { parserInput.restore(); break; } lookups.push(rule); parserInput.forget(); } if (lookups.length > 0) { return lookups; } }, lookupValue: function () { parserInput.save(); if (!parserInput.$char('[')) { parserInput.restore(); return; } var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/); if (!parserInput.$char(']')) { parserInput.restore(); return; } if (name || name === '') { parserInput.forget(); return name; } parserInput.restore(); } }, entity: function () { var entities = this.entities; return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript(); }, end: function () { return parserInput.$char(';') || parserInput.peek('}'); }, ieAlpha: function () { var value; if (!parserInput.$re(/^opacity=/i)) { return; } value = parserInput.$re(/^\d+/); if (!value) { value = expect(parsers.entities.variable, 'Could not parse alpha'); value = '@{' + value.name.slice(1) + '}'; } expectChar(')'); return new tree.Quoted('', 'alpha(opacity=' + value + ')'); }, element: function () { var e, c, v, index = parserInput.i; c = this.combinator(); e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) || this.entities.variableCurly(); if (!e) { parserInput.save(); if (parserInput.$char('(')) { if ((v = this.selector(false)) && parserInput.$char(')')) { e = new tree.Paren(v); parserInput.forget(); } else { parserInput.restore("Missing closing ')'"); } } else { parserInput.forget(); } } if (e) { return new tree.Element(c, e, e instanceof tree.Variable, index, fileInfo); } }, combinator: function () { var c = parserInput.currentChar(); if (c === '/') { parserInput.save(); var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i); if (slashedCombinator) { parserInput.forget(); return new tree.Combinator(slashedCombinator); } parserInput.restore(); } if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { parserInput.i++; if (c === '^' && parserInput.currentChar() === '^') { c = '^^'; parserInput.i++; } while (parserInput.isWhitespace()) { parserInput.i++; } return new tree.Combinator(c); } else if (parserInput.isWhitespace(-1)) { return new tree.Combinator(' '); } else { return new tree.Combinator(null); } }, selector: function (isLess) { var index = parserInput.i, elements, extendList, c, e, allExtends, when, condition; isLess = isLess !== false; while (isLess && (extendList = this.extend()) || isLess && (when = parserInput.$str('when')) || (e = this.element())) { if (when) { condition = expect(this.conditions, 'expected condition'); } else if (condition) { error('CSS guard can only be used at the end of selector'); } else if (extendList) { if (allExtends) { allExtends = allExtends.concat(extendList); } else { allExtends = extendList; } } else { if (allExtends) { error('Extend can only be used at the end of selector'); } c = parserInput.currentChar(); if (elements) { elements.push(e); } else { elements = [e]; } e = null; } if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break; } } if (elements) { return new tree.Selector(elements, allExtends, condition, index, fileInfo); } if (allExtends) { error('Extend must be used to extend a selector, it cannot be used on its own'); } }, selectors: function () { var s, selectors; while (true) { s = this.selector(); if (!s) { break; } if (selectors) { selectors.push(s); } else { selectors = [s]; } parserInput.commentStore.length = 0; if (s.condition && selectors.length > 1) { error('Guards are only currently allowed on a single selector.'); } if (!parserInput.$char(',')) { break; } if (s.condition) { error('Guards are only currently allowed on a single selector.'); } parserInput.commentStore.length = 0; } return selectors; }, attribute: function () { if (!parserInput.$char('[')) { return; } var entities = this.entities, key, val, op; if (!(key = entities.variableCurly())) { key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); } op = parserInput.$re(/^[|~*$^]?=/); if (op) { val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly(); } expectChar(']'); return new tree.Attribute(key, op, val); }, block: function () { var content; if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) { return content; } }, blockRuleset: function () { var block = this.block(); if (block) { block = new tree.Ruleset(null, block); } return block; }, detachedRuleset: function () { var argInfo, params, variadic; parserInput.save(); if (parserInput.$re(/^[.#]\(/)) { argInfo = this.mixin.args(false); params = argInfo.args; variadic = argInfo.variadic; if (!parserInput.$char(')')) { parserInput.restore(); return; } } var blockRuleset = this.blockRuleset(); if (blockRuleset) { parserInput.forget(); if (params) { return new tree.mixin.Definition(null, params, blockRuleset, null, variadic); } return new tree.DetachedRuleset(blockRuleset); } parserInput.restore(); }, ruleset: function () { var selectors, rules, debugInfo; parserInput.save(); if (context.dumpLineNumbers) { debugInfo = getDebugInfo(parserInput.i); } selectors = this.selectors(); if (selectors && (rules = this.block())) { parserInput.forget(); var ruleset = new tree.Ruleset(selectors, rules, context.strictImports); if (context.dumpLineNumbers) { ruleset.debugInfo = debugInfo; } return ruleset; } else { parserInput.restore(); } }, declaration: function () { var name, value, index = parserInput.i, hasDR, c = parserInput.currentChar(), important, merge, isVariable; if (c === '.' || c === '#' || c === '&' || c === ':') { return; } parserInput.save(); name = this.variable() || this.ruleProperty(); if (name) { isVariable = typeof name === 'string'; if (isVariable) { value = this.detachedRuleset(); if (value) { hasDR = true; } } parserInput.commentStore.length = 0; if (!value) { merge = !isVariable && name.length > 1 && name.pop().value; if (name[0].value && name[0].value.slice(0, 2) === '--') { value = this.permissiveValue(); } else { value = this.anonymousValue(); } if (value) { parserInput.forget(); return new tree.Declaration(name, value, false, merge, index, fileInfo); } if (!value) { value = this.value(); } if (value) { important = this.important(); } else if (isVariable) { value = this.permissiveValue(); } } if (value && (this.end() || hasDR)) { parserInput.forget(); return new tree.Declaration(name, value, important, merge, index, fileInfo); } else { parserInput.restore(); } } else { parserInput.restore(); } }, anonymousValue: function () { var index = parserInput.i; var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/); if (match) { return new tree.Anonymous(match[1], index); } }, permissiveValue: function (untilTokens) { var i, e, done, value, tok = untilTokens || ';', index = parserInput.i, result = []; function testCurrentChar() { var char = parserInput.currentChar(); if (typeof tok === 'string') { return char === tok; } else { return tok.test(char); } } if (testCurrentChar()) { return; } value = []; do { e = this.comment(); if (e) { value.push(e); continue; } e = this.entity(); if (e) { value.push(e); } } while (e); done = testCurrentChar(); if (value.length > 0) { value = new tree.Expression(value); if (done) { return value; } else { result.push(value); } if (parserInput.prevChar() === ' ') { result.push(new tree.Anonymous(' ', index)); } } parserInput.save(); value = parserInput.$parseUntil(tok); if (value) { if (typeof value === 'string') { error("Expected '" + value + "'", 'Parse'); } if (value.length === 1 && value[0] === ' ') { parserInput.forget(); return new tree.Anonymous('', index); } var item; for (i = 0; i < value.length; i++) { item = value[i]; if (Array.isArray(item)) { result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo)); } else { if (i === value.length - 1) { item = item.trim(); } var quote = new tree.Quoted("'", item, true, index, fileInfo); quote.variableRegex = /@([\w-]+)/g; quote.propRegex = /\$([\w-]+)/g; result.push(quote); } } parserInput.forget(); return new tree.Expression(result, true); } parserInput.restore(); }, 'import': function () { var path, features, index = parserInput.i; var dir = parserInput.$re(/^@import?\s+/); if (dir) { var options = (dir ? this.importOptions() : null) || {}; if (path = this.entities.quoted() || this.entities.url()) { features = this.mediaFeatures(); if (!parserInput.$char(';')) { parserInput.i = index; error('missing semi-colon or unrecognised media features on import'); } features = features && new tree.Value(features); return new tree.Import(path, features, options, index, fileInfo); } else { parserInput.i = index; error('malformed import statement'); } } }, importOptions: function () { var o, options = {}, optionName, value; if (!parserInput.$char('(')) { return null; } do { o = this.importOption(); if (o) { optionName = o; value = true; switch (optionName) { case 'css': optionName = 'less'; value = false; break; case 'once': optionName = 'multiple'; value = false; break; } options[optionName] = value; if (!parserInput.$char(',')) { break; } } } while (o); expectChar(')'); return options; }, importOption: function () { var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/); if (opt) { return opt[1]; } }, mediaFeature: function () { var entities = this.entities, nodes = [], e, p; parserInput.save(); do { e = entities.keyword() || entities.variable() || entities.mixinLookup(); if (e) { nodes.push(e); } else if (parserInput.$char('(')) { p = this.property(); e = this.value(); if (parserInput.$char(')')) { if (p && e) { nodes.push(new tree.Paren(new tree.Declaration(p, e, null, null, parserInput.i, fileInfo, true))); } else if (e) { nodes.push(new tree.Paren(e)); } else { error('badly formed media feature definition'); } } else { error("Missing closing ')'", 'Parse'); } } } while (e); parserInput.forget(); if (nodes.length > 0) { return new tree.Expression(nodes); } }, mediaFeatures: function () { var entities = this.entities, features = [], e; do { e = this.mediaFeature(); if (e) { features.push(e); if (!parserInput.$char(',')) { break; } } else { e = entities.variable() || entities.mixinLookup(); if (e) { features.push(e); if (!parserInput.$char(',')) { break; } } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules, media, debugInfo, index = parserInput.i; if (context.dumpLineNumbers) { debugInfo = getDebugInfo(index); } parserInput.save(); if (parserInput.$str('@media')) { features = this.mediaFeatures(); rules = this.block(); if (!rules) { error('media definitions require block statements after any features'); } parserInput.forget(); media = new tree.Media(rules, features, index, fileInfo); if (context.dumpLineNumbers) { media.debugInfo = debugInfo; } return media; } parserInput.restore(); }, plugin: function () { var path, args, options, index = parserInput.i, dir = parserInput.$re(/^@plugin?\s+/); if (dir) { args = this.pluginArgs(); if (args) { options = { pluginArgs: args, isPlugin: true }; } else { options = { isPlugin: true }; } if (path = this.entities.quoted() || this.entities.url()) { if (!parserInput.$char(';')) { parserInput.i = index; error('missing semi-colon on @plugin'); } return new tree.Import(path, null, options, index, fileInfo); } else { parserInput.i = index; error('malformed @plugin statement'); } } }, pluginArgs: function () { parserInput.save(); if (!parserInput.$char('(')) { parserInput.restore(); return null; } var args = parserInput.$re(/^\s*([^\);]+)\)\s*/); if (args[1]) { parserInput.forget(); return args[1].trim(); } else { parserInput.restore(); return null; } }, atrule: function () { var index = parserInput.i, name, value, rules, nonVendorSpecificName, hasIdentifier, hasExpression, hasUnknown, hasBlock = true, isRooted = true; if (parserInput.currentChar() !== '@') { return; } value = this['import']() || this.plugin() || this.media(); if (value) { return value; } parserInput.save(); name = parserInput.$re(/^@[a-z-]+/); if (!name) { return; } nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = '@' + name.slice(name.indexOf('-', 2) + 1); } switch (nonVendorSpecificName) { case '@charset': hasIdentifier = true; hasBlock = false; break; case '@namespace': hasExpression = true; hasBlock = false; break; case '@keyframes': case '@counter-style': hasIdentifier = true; break; case '@document': case '@supports': hasUnknown = true; isRooted = false; break; default: hasUnknown = true; break; } parserInput.commentStore.length = 0; if (hasIdentifier) { value = this.entity(); if (!value) { error('expected ' + name + ' identifier'); } } else if (hasExpression) { value = this.expression(); if (!value) { error('expected ' + name + ' expression'); } } else if (hasUnknown) { value = this.permissiveValue(/^[{;]/); hasBlock = parserInput.currentChar() === '{'; if (!value) { if (!hasBlock && parserInput.currentChar() !== ';') { error(name + ' rule is missing block or ending semi-colon'); } } else if (!value.value) { value = null; } } if (hasBlock) { rules = this.blockRuleset(); } if (rules || !hasBlock && value && parserInput.$char(';')) { parserInput.forget(); return new tree.AtRule(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted); } parserInput.restore('at-rule options not recognised'); }, value: function () { var e, expressions = [], index = parserInput.i; do { e = this.expression(); if (e) { expressions.push(e); if (!parserInput.$char(',')) { break; } } } while (e); if (expressions.length > 0) { return new tree.Value(expressions, index); } }, important: function () { if (parserInput.currentChar() === '!') { return parserInput.$re(/^! *important/); } }, sub: function () { var a, e; parserInput.save(); if (parserInput.$char('(')) { a = this.addition(); if (a && parserInput.$char(')')) { parserInput.forget(); e = new tree.Expression([a]); e.parens = true; return e; } parserInput.restore("Expected ')'"); return; } parserInput.restore(); }, multiplication: function () { var m, a, op, operation, isSpaced; m = this.operand(); if (m) { isSpaced = parserInput.isWhitespace(-1); while (true) { if (parserInput.peek(/^\/[*\/]/)) { break; } parserInput.save(); op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./'); if (!op) { parserInput.forget(); break; } a = this.operand(); if (!a) { parserInput.restore(); break; } parserInput.forget(); m.parensInOp = true; a.parensInOp = true; operation = new tree.Operation(op, [ operation || m, a ], isSpaced); isSpaced = parserInput.isWhitespace(-1); } return operation || m; } }, addition: function () { var m, a, op, operation, isSpaced; m = this.multiplication(); if (m) { isSpaced = parserInput.isWhitespace(-1); while (true) { op = parserInput.$re(/^[-+]\s+/) || !isSpaced && (parserInput.$char('+') || parserInput.$char('-')); if (!op) { break; } a = this.multiplication(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new tree.Operation(op, [ operation || m, a ], isSpaced); isSpaced = parserInput.isWhitespace(-1); } return operation || m; } }, conditions: function () { var a, b, index = parserInput.i, condition; a = this.condition(true); if (a) { while (true) { if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) { break; } b = this.condition(true); if (!b) { break; } condition = new tree.Condition('or', condition || a, b, index); } return condition || a; } }, condition: function (needsParens) { var result, logical, next; function or() { return parserInput.$str('or'); } result = this.conditionAnd(needsParens); if (!result) { return; } logical = or(); if (logical) { next = this.condition(needsParens); if (next) { result = new tree.Condition(logical, result, next); } else { return; } } return result; }, conditionAnd: function (needsParens) { var result, logical, next, self = this; function insideCondition() { var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens); if (!cond && !needsParens) { return self.atomicCondition(needsParens); } return cond; } function and() { return parserInput.$str('and'); } result = insideCondition(); if (!result) { return; } logical = and(); if (logical) { next = this.conditionAnd(needsParens); if (next) { result = new tree.Condition(logical, result, next); } else { return; } } return result; }, negatedCondition: function (needsParens) { if (parserInput.$str('not')) { var result = this.parenthesisCondition(needsParens); if (result) { result.negate = !result.negate; } return result; } }, parenthesisCondition: function (needsParens) { function tryConditionFollowedByParenthesis(me) { var body; parserInput.save(); body = me.condition(needsParens); if (!body) { parserInput.restore(); return; } if (!parserInput.$char(')')) { parserInput.restore(); return; } parserInput.forget(); return body; } var body; parserInput.save(); if (!parserInput.$str('(')) { parserInput.restore(); return; } body = tryConditionFollowedByParenthesis(this); if (body) { parserInput.forget(); return body; } body = this.atomicCondition(needsParens); if (!body) { parserInput.restore(); return; } if (!parserInput.$char(')')) { parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'"); return; } parserInput.forget(); return body; }, atomicCondition: function (needsParens) { var entities = this.entities, index = parserInput.i, a, b, c, op; function cond() { return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup(); } cond = cond.bind(this); a = cond(); if (a) { if (parserInput.$char('>')) { if (parserInput.$char('=')) { op = '>='; } else { op = '>'; } } else if (parserInput.$char('<')) { if (parserInput.$char('=')) { op = '<='; } else { op = '<'; } } else if (parserInput.$char('=')) { if (parserInput.$char('>')) { op = '=>'; } else if (parserInput.$char('<')) { op = '=<'; } else { op = '='; } } if (op) { b = cond(); if (b) { c = new tree.Condition(op, a, b, index, false); } else { error('expected expression'); } } else { c = new tree.Condition('=', a, new tree.Keyword('true'), index, false); } return c; } }, operand: function () { var entities = this.entities, negate; if (parserInput.peek(/^-[@\$\(]/)) { negate = parserInput.$char('-'); } var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup(); if (negate) { o.parensInOp = true; o = new tree.Negative(o); } return o; }, expression: function () { var entities = [], e, delim, index = parserInput.i; do { e = this.comment(); if (e) { entities.push(e); continue; } e = this.addition() || this.entity(); if (e) { entities.push(e); if (!parserInput.peek(/^\/[\/*]/)) { delim = parserInput.$char('/'); if (delim) { entities.push(new tree.Anonymous(delim, index)); } } } } while (e); if (entities.length > 0) { return new tree.Expression(entities); } }, property: function () { var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); if (name) { return name[1]; } }, ruleProperty: function () { var name = [], index = [], s, k; parserInput.save(); var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/); if (simpleProperty) { name = [new tree.Keyword(simpleProperty[1])]; parserInput.forget(); return name; } function match(re) { var i = parserInput.i, chunk = parserInput.$re(re); if (chunk) { index.push(i); return name.push(chunk[1]); } } match(/^(\*?)/); while (true) { if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) { break; } } if (name.length > 1 && match(/^((?:\+_|\+)?)\s*:/)) { parserInput.forget(); if (name[0] === '') { name.shift(); index.shift(); } for (k = 0; k < name.length; k++) { s = name[k]; name[k] = s.charAt(0) !== '@' && s.charAt(0) !== '$' ? new tree.Keyword(s) : s.charAt(0) === '@' ? new tree.Variable('@' + s.slice(2, -1), index[k], fileInfo) : new tree.Property('$' + s.slice(2, -1), index[k], fileInfo); } return name; } parserInput.restore(); } } }; }; Parser.serializeVars = function (vars) { var s = ''; for (var name in vars) { if (Object.hasOwnProperty.call(vars, name)) { var value = vars[name]; s += (name[0] === '@' ? '' : '@') + name + ': ' + value + (String(value).slice(-1) === ';' ? '' : ';'); } } return s; }; module.exports = Parser; function __isEmptyObject(obj) { var attr; for (attr in obj) return !1; return !0; } function __isValidToReturn(obj) { return typeof obj != 'object' || Array.isArray(obj) || !__isEmptyObject(obj); } if (__isValidToReturn(module.exports)) return module.exports; else if (__isValidToReturn(exports)) return exports; });
f
book-service.module.ts
import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { BookServicePage } from './book-service'; @NgModule({ declarations: [ BookServicePage, ], imports: [ IonicPageModule.forChild(BookServicePage), ], }) export class
{}
BookServicePageModule
file_test.go
package fs import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestIsFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) defer os.RemoveAll(dir1) file1, err := ioutil.TempFile("", "file") assert.Nil(err) file1.Close() defer os.Remove(file1.Name()) type args struct { filename string } tests := []struct { name string args args want bool wantErr bool }{ { "non-existing file", args{ "", }, false, true, }, { "directory is not a regular file", args{ dir1, }, false, false, }, { "regular file", args{ file1.Name(), }, true, false, }, } for _, tt := range tests { got, gotErr := IsFile(tt.args.filename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) assert.Equal(tt.want, got, tt.name) } } func TestAssertFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) defer os.RemoveAll(dir1) file1, err := ioutil.TempFile("", "file") assert.Nil(err) file1.Close() defer os.Remove(file1.Name()) type args struct { filename string } tests := []struct { name string args args wantErr bool }{ { "non-existing file", args{ "", }, true, }, { "directory is not a regular file", args{ dir1, }, true, }, { "regular file", args{ file1.Name(), }, false, }, } for _, tt := range tests { gotErr := AssertFile(tt.args.filename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) } } func TestReadFileInfo(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) defer os.RemoveAll(dir1) file1, err := ioutil.TempFile("", "file*.txt") assert.Nil(err) file1.Close() defer os.Remove(file1.Name()) type args struct { filename string } tests := []struct { name string args args want *FileInfo wantErr bool }{ { "non-existing file", args{ "", }, nil, true, }, { "directory is not a regular file", args{ dir1, }, nil, true, }, { "regular file", args{ file1.Name(), }, &FileInfo{ Name: filepath.Base(file1.Name()), Ext: filepath.Ext(file1.Name()), Dir: filepath.Dir(file1.Name()), Path: file1.Name(), Size: 0, }, false, }, } for _, tt := range tests { got, gotErr := ReadFileInfo(tt.args.filename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) assert.Equal(tt.want, got, tt.name) } } func TestCreateFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) defer os.RemoveAll(dir1) file1, err := ioutil.TempFile("", "file*.txt") assert.Nil(err) file1.Close() defer os.Remove(file1.Name()) type args struct { filename string } tests := []struct { name string args args wantFile bool wantErr bool }{ { "directory already exists", args{ dir1, }, false, true, }, { "file already exists", args{ file1.Name(), }, false, true, }, { "filename is available", args{ filepath.Join(dir1, "file"), }, true, false, }, { "empty filename", args{ "", }, false, true, }, } for _, tt := range tests { got, gotErr := CreateFile(tt.args.filename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) assert.Equal(tt.wantFile, got != nil, tt.name) if gotErr != nil { got.Close() } } } func TestRemoveFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) file1, err := ioutil.TempFile(dir1, "file*.txt") assert.Nil(err) file1.Close() defer os.RemoveAll(dir1) file2, err := ioutil.TempFile("", "file*.txt") assert.Nil(err) file2.Close() defer os.Remove(file2.Name()) type args struct { filename string } tests := []struct { name string args args wantErr bool }{ { "invalid file", args{ "", }, true, }, { "non-empty directory", args{ dir1, }, true, }, { "removable file", args{ file2.Name(), }, false, }, } for _, tt := range tests { gotErr := RemoveFile(tt.args.filename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) } } func TestCreateNextFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) file1, err := ioutil.TempFile(dir1, "file*.txt") assert.Nil(err) file1.Close() file2, err := ioutil.TempFile(dir1, "file*") assert.Nil(err) file2.Close() file3, err := ioutil.TempFile(dir1, "file*.json.txt") assert.Nil(err) file3.Close() defer os.RemoveAll(dir1) type args struct { filename string maxTries int } tests := []struct { name string args args want string wantErr bool }{ { "existing file with extension, zero tries", args{ file1.Name(), 0, }, "", true, }, { "existing file with extension, one try", args{ file1.Name(), 1, }, strings.TrimSuffix(file1.Name(), ".txt") + "(1)" + ".txt", false, }, { "existing file without extension, zero tries", args{ file2.Name(), 0, }, "", true, }, { "existing file without extension, one try", args{ file2.Name(), 1, }, file2.Name() + "(1)", false, }, { "existing file with extension and other dot, zero tries", args{ file3.Name(), 0, }, "", true, }, { "existing file with extension and other dot, one try", args{ file3.Name(), 1, }, strings.TrimSuffix(file3.Name(), ".txt") + "(1)" + ".txt", false, }, } for _, tt := range tests { got, gotErr := CreateNextFile(tt.args.filename, tt.args.maxTries) assert.Equal(tt.wantErr, gotErr != nil, tt.name) if got != nil { assert.Equal(tt.want, got.Name(), tt.name) } } } func TestCopyFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) file1Name := filepath.Join(dir1, "file1.txt") err = ioutil.WriteFile( file1Name, []byte("hello world"), defaultFilePermissions, ) assert.Nil(err) file2, err := ioutil.TempFile(dir1, "file") assert.Nil(err) file2.Close() file3, err := ioutil.TempFile(dir1, "file") assert.Nil(err) defer file3.Close() file4, err := CreateFile(filepath.Join(dir1, "file4")) assert.Nil(err) defer file4.Close() defer os.RemoveAll(dir1) type args struct { filename string destFilename string } tests := []struct { name string args args wantErr bool }{ { "invalid filename", args{ "", file2.Name(), }, true, }, { "invalid copy from directory", args{ dir1, file2.Name(), }, true, }, { "invalid copy to directory", args{ file1Name, dir1, }, true, }, { "invalid copy to same file", args{ file1Name, file1Name, }, true, }, { "invalid copy to invalid file", args{ file1Name, "", }, true, }, { "copy to another file", args{ file1Name, file2.Name(), }, false, }, { "copy to open file", args{ file1Name, file3.Name(), }, false, }, { "copy to exclusive file", args{ file1Name, file4.Name(), }, false, }, } for _, tt := range tests { gotErr := CopyFile(tt.args.filename, tt.args.destFilename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) } } func TestMoveFile(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) file1Name := filepath.Join(dir1, "file1.txt") err = ioutil.WriteFile( file1Name, []byte("hello world"), defaultFilePermissions, ) assert.Nil(err) file2, err := ioutil.TempFile(dir1, "file") assert.Nil(err) file2.Close() file3, err := ioutil.TempFile(dir1, "file") assert.Nil(err) defer file3.Close() file4, err := CreateFile(filepath.Join(dir1, "file4")) assert.Nil(err) defer file4.Close() defer os.RemoveAll(dir1) type args struct { filename string destFilename string } tests := []struct { name string args args wantErr bool }{ { "invalid filename", args{ "", file2.Name(), }, true, }, { "invalid move from directory", args{ dir1, file2.Name(), }, true, }, { "invalid move to directory", args{ file1Name, dir1, }, true, }, { "invalid move to same file", args{ file1Name, file1Name, }, true, }, { "invalid move to invalid file", args{ file1Name, "", }, true, }, { "move to another file", args{ file1Name, file2.Name(), }, false, }, { "move to open file", args{ file2.Name(), file3.Name(), }, false, }, { "move to exclusive file", args{ file3.Name(), file4.Name(), }, false, }, } for _, tt := range tests { gotErr := MoveFile(tt.args.filename, tt.args.destFilename) if tt.wantErr != (gotErr != nil) { fmt.Println() fmt.Println(tt.args.filename) fmt.Println(tt.args.destFilename) fmt.Println(gotErr) fmt.Println() } assert.Equal(tt.wantErr, gotErr != nil, tt.name) } } func TestCopyFileSafe(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) file1Name := filepath.Join(dir1, "file1.txt") err = ioutil.WriteFile( file1Name, []byte("hello world"), defaultFilePermissions, ) assert.Nil(err) file2, err := ioutil.TempFile(dir1, "file") assert.Nil(err) file2.Close() file3, err := ioutil.TempFile(dir1, "file") assert.Nil(err) defer file3.Close() file4, err := CreateFile(filepath.Join(dir1, "file4")) assert.Nil(err) defer file4.Close() defer os.RemoveAll(dir1) type args struct { filename string destFilename string maxTries int } tests := []struct { name string args args want string wantErr bool }{ { "invalid filename", args{ "", file1Name, 1, }, "", true, }, { "invalid copy from directory", args{ dir1, file2.Name(), 1, }, "", true, }, { "invalid copy to dir", args{ file1Name, dir1, 1, }, "", true, }, { "invalid copy to same file", args{ file1Name, file1Name, 1, }, "", true, }, { "invalid copy to invalid file", args{ file1Name, "", 1, }, "", true, }, { "existing destination, zero maxTries", args{ file1Name, file2.Name(), 0, }, "", true, }, { "existing destination, one maxTries", args{ file1Name, file2.Name(), 1, }, file2.Name() + "(1)", false, }, { "copy to open file", args{ file1Name, file3.Name(), 1, }, file3.Name() + "(1)", false, }, { "copy to exclusive file", args{ file1Name, file4.Name(), 1, }, file4.Name() + "(1)", false, }, } for _, tt := range tests { got, gotErr := CopyFileSafe(tt.args.filename, tt.args.destFilename, tt.args.maxTries) assert.Equal(tt.wantErr, gotErr != nil, tt.name) assert.Equal(tt.want, got, tt.name) } } func TestMoveFileSafe(t *testing.T) { assert := assert.New(t) dir1, err := ioutil.TempDir("", "dir") assert.Nil(err) file1Name := filepath.Join(dir1, "file1.txt") err = ioutil.WriteFile( file1Name, []byte("hello world"), defaultFilePermissions, ) assert.Nil(err) file2, err := ioutil.TempFile(dir1, "file") assert.Nil(err) file2.Close() file3, err := ioutil.TempFile(dir1, "file") assert.Nil(err) defer file3.Close() file4, err := CreateFile(filepath.Join(dir1, "file4")) assert.Nil(err) defer file4.Close() defer os.RemoveAll(dir1) type args struct { filename string destFilename string maxTries int } tests := []struct { name string args args want string wantErr bool }{ { "invalid filename", args{ "", file1Name, 1, }, "", true, }, { "invalid move from directory", args{ dir1, file2.Name(), 1, },
}, { "invalid move to dir", args{ file1Name, dir1, 1, }, "", true, }, { "invalid move to same file", args{ file1Name, file1Name, 1, }, "", true, }, { "invalid move to invalid file (1)", args{ file1Name, "", 1, }, "", true, }, { "invalid move to invalid file (2)", args{ file1Name, " ", 1, }, "", true, }, { "existing destination, zero maxTries", args{ file1Name, file2.Name(), 0, }, "", true, }, { "existing destination, one maxTries", args{ file1Name, file2.Name(), 1, }, file2.Name() + "(1)", false, }, { "move to open file", args{ file2.Name(), file3.Name(), 1, }, file3.Name() + "(1)", false, }, { "move to exclusive file", args{ file3.Name(), file4.Name(), 1, }, file4.Name() + "(1)", false, }, } for _, tt := range tests { got, gotErr := MoveFileSafe(tt.args.filename, tt.args.destFilename, tt.args.maxTries) assert.Equal(tt.wantErr, gotErr != nil, tt.name) assert.Equal(tt.want, got, tt.name) } } func Test_copyFile(t *testing.T) { assert := assert.New(t) file1, err := ioutil.TempFile("", "file") assert.Nil(err) file1.Close() defer os.Remove(file1.Name()) type args struct { filename string destFilename string } tests := []struct { name string args args wantErr bool }{ { "invalid filename", args{ "", file1.Name(), }, true, }, { "invalid destFilename", args{ file1.Name(), "", }, true, }, } for _, tt := range tests { gotErr := copyFile(tt.args.filename, tt.args.destFilename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) } } func Test_moveFile(t *testing.T) { assert := assert.New(t) file1, err := ioutil.TempFile("", "file") assert.Nil(err) file1.Close() defer os.Remove(file1.Name()) type args struct { filename string destFilename string } tests := []struct { name string args args wantErr bool }{ { "invalid filename", args{ "", file1.Name(), }, true, }, { "invalid destFilename", args{ file1.Name(), "", }, true, }, } for _, tt := range tests { gotErr := moveFile(tt.args.filename, tt.args.destFilename) assert.Equal(tt.wantErr, gotErr != nil, tt.name) } }
"", true,
set6_test.go
package dense import "testing" func
(t *testing.T) { s := NewSet6(2, 4, 5, 7, 60) if s.Count() != 5 { t.Errorf("Set %v is supposed to contain 5 elements, got %v", s, s.Count()) } for i, v := range []int64{2, 4, 5, 7, 60} { if !s.Contains(v) { t.Errorf("Set %v is supposed to contain %v", s, v) } if n, ok := s.Ordinal(v); n != uint64(i) || !ok { t.Errorf("%dth element is not at ordinal %d (%v)", i, n, ok) } } if n, ok := s.Ordinal(10); n != 4 || ok { t.Errorf("Ordinal of elem 10 in %v: expected 4, false, got %v, %v", s, n, ok) } if n, ok := s.Ordinal(63); n != 5 || ok { t.Errorf("Ordinal of elem 63 in %v: expected 5, false, got %v, %v", s, n, ok) } }
TestSet6
lib.rs
extern crate chrono; extern crate failure; extern crate oauth2; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; mod provider; mod session; mod user;
pub use provider::Provider; pub use session::{Params, Session}; pub use user::User; pub struct Ferry { pub providers: Vec<&'static provider::Provider>, } impl Ferry { pub fn new(providers: Vec<&'static provider::Provider>) -> Ferry { Ferry { providers: providers, } } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } // #[test] // fn add_provider() { // let mut ferry = Ferry::new(vec![Provider{}]) // } }
egress.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: egress.proto /* Package loggregator_v2 is a generated protocol buffer package. It is generated from these files: egress.proto egress_query.proto envelope.proto ingress.proto It has these top-level messages: EgressRequest EgressBatchRequest Selector LogSelector GaugeSelector CounterSelector TimerSelector EventSelector ContainerMetricRequest QueryResponse Envelope EnvelopeBatch Value Log Counter Gauge GaugeValue Timer Event IngressResponse BatchSenderResponse SendResponse */ package loggregator_v2 import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import ( context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type EgressRequest struct { // shard_id instructs Loggregator to shard envelopes between other // subscriptions with the same shard_id. Loggregator will do its best to // split the load evenly between subscriptions with the same shard_id. ShardId string `protobuf:"bytes,1,opt,name=shard_id,json=shardId" json:"shard_id,omitempty"` // TODO: This can be removed once selector has been around long enough. LegacySelector *Selector `protobuf:"bytes,2,opt,name=legacy_selector,json=legacySelector" json:"legacy_selector,omitempty"` // selector is the preferred (over legacy_selector) mechanism to select // what envelope types the subscription wants. Selectors []*Selector `protobuf:"bytes,4,rep,name=selectors" json:"selectors,omitempty"` // TODO: This can be removed once the envelope.deprecated_tags is removed. UsePreferredTags bool `protobuf:"varint,3,opt,name=use_preferred_tags,json=usePreferredTags" json:"use_preferred_tags,omitempty"` } func (m *EgressRequest) Reset() { *m = EgressRequest{} } func (m *EgressRequest) String() string { return proto.CompactTextString(m) } func (*EgressRequest) ProtoMessage() {} func (*EgressRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *EgressRequest) GetShardId() string { if m != nil { return m.ShardId } return "" } func (m *EgressRequest) GetLegacySelector() *Selector { if m != nil { return m.LegacySelector } return nil } func (m *EgressRequest) GetSelectors() []*Selector { if m != nil { return m.Selectors } return nil } func (m *EgressRequest) GetUsePreferredTags() bool { if m != nil { return m.UsePreferredTags } return false } type EgressBatchRequest struct { // shard_id instructs Loggregator to shard envelopes between other // subscriptions with the same shard_id. Loggregator will do its best to // split the load evenly between subscriptions with the same shard_id. ShardId string `protobuf:"bytes,1,opt,name=shard_id,json=shardId" json:"shard_id,omitempty"` // TODO: This can be removed once selector has been around long enough. LegacySelector *Selector `protobuf:"bytes,2,opt,name=legacy_selector,json=legacySelector" json:"legacy_selector,omitempty"` // selector is the preferred (over legacy_selector) mechanism to select // what envelope types the subscription wants. Selectors []*Selector `protobuf:"bytes,4,rep,name=selectors" json:"selectors,omitempty"` // TODO: This can be removed once the envelope.deprecated_tags is removed. UsePreferredTags bool `protobuf:"varint,3,opt,name=use_preferred_tags,json=usePreferredTags" json:"use_preferred_tags,omitempty"` } func (m *EgressBatchRequest) Reset() { *m = EgressBatchRequest{} } func (m *EgressBatchRequest) String() string { return proto.CompactTextString(m) } func (*EgressBatchRequest) ProtoMessage() {} func (*EgressBatchRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *EgressBatchRequest) GetShardId() string { if m != nil { return m.ShardId } return "" } func (m *EgressBatchRequest) GetLegacySelector() *Selector { if m != nil { return m.LegacySelector } return nil } func (m *EgressBatchRequest) GetSelectors() []*Selector { if m != nil { return m.Selectors } return nil } func (m *EgressBatchRequest) GetUsePreferredTags() bool { if m != nil { return m.UsePreferredTags } return false } // Selector instructs Loggregator to only send envelopes that match the given // criteria. type Selector struct { SourceId string `protobuf:"bytes,1,opt,name=source_id,json=sourceId" json:"source_id,omitempty"` // Types that are valid to be assigned to Message: // *Selector_Log // *Selector_Counter // *Selector_Gauge // *Selector_Timer // *Selector_Event Message isSelector_Message `protobuf_oneof:"Message"` } func (m *Selector) Reset() { *m = Selector{} } func (m *Selector) String() string { return proto.CompactTextString(m) } func (*Selector) ProtoMessage() {} func (*Selector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type isSelector_Message interface { isSelector_Message() } type Selector_Log struct { Log *LogSelector `protobuf:"bytes,2,opt,name=log,oneof"` } type Selector_Counter struct { Counter *CounterSelector `protobuf:"bytes,3,opt,name=counter,oneof"` } type Selector_Gauge struct { Gauge *GaugeSelector `protobuf:"bytes,4,opt,name=gauge,oneof"` } type Selector_Timer struct { Timer *TimerSelector `protobuf:"bytes,5,opt,name=timer,oneof"` } type Selector_Event struct { Event *EventSelector `protobuf:"bytes,6,opt,name=event,oneof"` } func (*Selector_Log) isSelector_Message() {} func (*Selector_Counter) isSelector_Message() {} func (*Selector_Gauge) isSelector_Message() {} func (*Selector_Timer) isSelector_Message() {} func (*Selector_Event) isSelector_Message() {} func (m *Selector) GetMessage() isSelector_Message { if m != nil { return m.Message } return nil } func (m *Selector) GetSourceId() string { if m != nil { return m.SourceId } return "" } func (m *Selector) GetLog() *LogSelector { if x, ok := m.GetMessage().(*Selector_Log); ok { return x.Log } return nil } func (m *Selector) GetCounter() *CounterSelector { if x, ok := m.GetMessage().(*Selector_Counter); ok { return x.Counter } return nil } func (m *Selector) GetGauge() *GaugeSelector { if x, ok := m.GetMessage().(*Selector_Gauge); ok { return x.Gauge } return nil } func (m *Selector) GetTimer() *TimerSelector { if x, ok := m.GetMessage().(*Selector_Timer); ok { return x.Timer } return nil } func (m *Selector) GetEvent() *EventSelector { if x, ok := m.GetMessage().(*Selector_Event); ok { return x.Event } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Selector) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Selector_OneofMarshaler, _Selector_OneofUnmarshaler, _Selector_OneofSizer, []interface{}{ (*Selector_Log)(nil), (*Selector_Counter)(nil), (*Selector_Gauge)(nil), (*Selector_Timer)(nil), (*Selector_Event)(nil), } } func _Selector_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Selector) // Message switch x := m.Message.(type) { case *Selector_Log: b.EncodeVarint(2<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Log); err != nil { return err } case *Selector_Counter: b.EncodeVarint(3<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Counter); err != nil { return err } case *Selector_Gauge: b.EncodeVarint(4<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Gauge); err != nil { return err } case *Selector_Timer: b.EncodeVarint(5<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Timer); err != nil { return err } case *Selector_Event: b.EncodeVarint(6<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Event); err != nil { return err } case nil: default: return fmt.Errorf("Selector.Message has unexpected type %T", x) } return nil } func _Selector_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Selector) switch tag { case 2: // Message.log if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(LogSelector) err := b.DecodeMessage(msg) m.Message = &Selector_Log{msg} return true, err case 3: // Message.counter if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(CounterSelector) err := b.DecodeMessage(msg) m.Message = &Selector_Counter{msg} return true, err case 4: // Message.gauge if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(GaugeSelector) err := b.DecodeMessage(msg) m.Message = &Selector_Gauge{msg} return true, err case 5: // Message.timer if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(TimerSelector) err := b.DecodeMessage(msg) m.Message = &Selector_Timer{msg} return true, err case 6: // Message.event if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(EventSelector) err := b.DecodeMessage(msg) m.Message = &Selector_Event{msg} return true, err default: return false, nil } } func _Selector_OneofSizer(msg proto.Message) (n int) { m := msg.(*Selector) // Message switch x := m.Message.(type) { case *Selector_Log: s := proto.Size(x.Log) n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Selector_Counter: s := proto.Size(x.Counter) n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Selector_Gauge: s := proto.Size(x.Gauge) n += proto.SizeVarint(4<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Selector_Timer: s := proto.Size(x.Timer) n += proto.SizeVarint(5<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Selector_Event: s := proto.Size(x.Event) n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // LogSelector instructs Loggregator to egress Log envelopes to the given // subscription. type LogSelector struct { } func (m *LogSelector) Reset() { *m = LogSelector{} } func (m *LogSelector) String() string { return proto.CompactTextString(m) } func (*LogSelector) ProtoMessage() {} func (*LogSelector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } // GaugeSelector instructs Loggregator to egress Gauge envelopes to the // given subscription. type GaugeSelector struct { } func (m *GaugeSelector) Reset() { *m = GaugeSelector{} } func (m *GaugeSelector) String() string { return proto.CompactTextString(m) } func (*GaugeSelector) ProtoMessage() {} func (*GaugeSelector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } // CounterSelector instructs Loggregator to egress Counter envelopes to the // given subscription type CounterSelector struct { } func (m *CounterSelector) Reset() { *m = CounterSelector{} } func (m *CounterSelector) String() string { return proto.CompactTextString(m) } func (*CounterSelector) ProtoMessage() {} func (*CounterSelector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } // TimerSelector instructs Loggregator to egress Timer envelopes to the given // subscription. type TimerSelector struct { } func (m *TimerSelector) Reset() { *m = TimerSelector{} } func (m *TimerSelector) String() string { return proto.CompactTextString(m) } func (*TimerSelector) ProtoMessage() {} func (*TimerSelector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } // EventSelector instructs Loggregator to egress Event envelopes to the given // subscription. type EventSelector struct { } func (m *EventSelector) Reset() { *m = EventSelector{} } func (m *EventSelector) String() string { return proto.CompactTextString(m) } func (*EventSelector) ProtoMessage() {} func (*EventSelector) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func init() { proto.RegisterType((*EgressRequest)(nil), "loggregator.v2.EgressRequest") proto.RegisterType((*EgressBatchRequest)(nil), "loggregator.v2.EgressBatchRequest")
proto.RegisterType((*LogSelector)(nil), "loggregator.v2.LogSelector") proto.RegisterType((*GaugeSelector)(nil), "loggregator.v2.GaugeSelector") proto.RegisterType((*CounterSelector)(nil), "loggregator.v2.CounterSelector") proto.RegisterType((*TimerSelector)(nil), "loggregator.v2.TimerSelector") proto.RegisterType((*EventSelector)(nil), "loggregator.v2.EventSelector") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for Egress service type EgressClient interface { Receiver(ctx context.Context, in *EgressRequest, opts ...grpc.CallOption) (Egress_ReceiverClient, error) BatchedReceiver(ctx context.Context, in *EgressBatchRequest, opts ...grpc.CallOption) (Egress_BatchedReceiverClient, error) } type egressClient struct { cc *grpc.ClientConn } func NewEgressClient(cc *grpc.ClientConn) EgressClient { return &egressClient{cc} } func (c *egressClient) Receiver(ctx context.Context, in *EgressRequest, opts ...grpc.CallOption) (Egress_ReceiverClient, error) { stream, err := grpc.NewClientStream(ctx, &_Egress_serviceDesc.Streams[0], c.cc, "/loggregator.v2.Egress/Receiver", opts...) if err != nil { return nil, err } x := &egressReceiverClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type Egress_ReceiverClient interface { Recv() (*Envelope, error) grpc.ClientStream } type egressReceiverClient struct { grpc.ClientStream } func (x *egressReceiverClient) Recv() (*Envelope, error) { m := new(Envelope) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *egressClient) BatchedReceiver(ctx context.Context, in *EgressBatchRequest, opts ...grpc.CallOption) (Egress_BatchedReceiverClient, error) { stream, err := grpc.NewClientStream(ctx, &_Egress_serviceDesc.Streams[1], c.cc, "/loggregator.v2.Egress/BatchedReceiver", opts...) if err != nil { return nil, err } x := &egressBatchedReceiverClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type Egress_BatchedReceiverClient interface { Recv() (*EnvelopeBatch, error) grpc.ClientStream } type egressBatchedReceiverClient struct { grpc.ClientStream } func (x *egressBatchedReceiverClient) Recv() (*EnvelopeBatch, error) { m := new(EnvelopeBatch) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // Server API for Egress service type EgressServer interface { Receiver(*EgressRequest, Egress_ReceiverServer) error BatchedReceiver(*EgressBatchRequest, Egress_BatchedReceiverServer) error } func RegisterEgressServer(s *grpc.Server, srv EgressServer) { s.RegisterService(&_Egress_serviceDesc, srv) } func _Egress_Receiver_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(EgressRequest) if err := stream.RecvMsg(m); err != nil { return err } return srv.(EgressServer).Receiver(m, &egressReceiverServer{stream}) } type Egress_ReceiverServer interface { Send(*Envelope) error grpc.ServerStream } type egressReceiverServer struct { grpc.ServerStream } func (x *egressReceiverServer) Send(m *Envelope) error { return x.ServerStream.SendMsg(m) } func _Egress_BatchedReceiver_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(EgressBatchRequest) if err := stream.RecvMsg(m); err != nil { return err } return srv.(EgressServer).BatchedReceiver(m, &egressBatchedReceiverServer{stream}) } type Egress_BatchedReceiverServer interface { Send(*EnvelopeBatch) error grpc.ServerStream } type egressBatchedReceiverServer struct { grpc.ServerStream } func (x *egressBatchedReceiverServer) Send(m *EnvelopeBatch) error { return x.ServerStream.SendMsg(m) } var _Egress_serviceDesc = grpc.ServiceDesc{ ServiceName: "loggregator.v2.Egress", HandlerType: (*EgressServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "Receiver", Handler: _Egress_Receiver_Handler, ServerStreams: true, }, { StreamName: "BatchedReceiver", Handler: _Egress_BatchedReceiver_Handler, ServerStreams: true, }, }, Metadata: "egress.proto", } func init() { proto.RegisterFile("egress.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 425 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x94, 0xc1, 0x6e, 0xd3, 0x40, 0x10, 0x86, 0xbb, 0x4d, 0x9b, 0xd8, 0x13, 0x12, 0xc3, 0x9e, 0x96, 0x54, 0x15, 0x96, 0x4f, 0x39, 0x20, 0x83, 0x8c, 0xe0, 0xc2, 0x89, 0xa2, 0xa8, 0x54, 0x02, 0x09, 0x99, 0x1e, 0xb8, 0x59, 0x8b, 0x3d, 0x6c, 0x23, 0x99, 0x6c, 0xd8, 0x5d, 0x5b, 0xe2, 0x99, 0x78, 0x0e, 0x9e, 0x80, 0x0b, 0x8f, 0x83, 0x76, 0x1d, 0xb7, 0xb6, 0x13, 0x78, 0x80, 0x1e, 0x77, 0xff, 0xff, 0x9b, 0x99, 0xdf, 0x9a, 0x35, 0x3c, 0x40, 0xa1, 0x50, 0xeb, 0x78, 0xab, 0xa4, 0x91, 0x74, 0x5e, 0x4a, 0x21, 0x14, 0x0a, 0x6e, 0xa4, 0x8a, 0xeb, 0x64, 0x31, 0xc7, 0x4d, 0x8d, 0xa5, 0xdc, 0x62, 0xa3, 0x47, 0xbf, 0x09, 0xcc, 0x56, 0x0e, 0x48, 0xf1, 0x7b, 0x85, 0xda, 0xd0, 0xc7, 0xe0, 0xe9, 0x1b, 0xae, 0x8a, 0x6c, 0x5d, 0x30, 0x12, 0x92, 0xa5, 0x9f, 0x4e, 0xdc, 0xf9, 0xaa, 0xa0, 0x6f, 0x20, 0x28, 0x51, 0xf0, 0xfc, 0x47, 0xa6, 0xb1, 0xc4, 0xdc, 0x48, 0xc5, 0x8e, 0x43, 0xb2, 0x9c, 0x26, 0x2c, 0xee, 0xb7, 0x89, 0x3f, 0xed, 0xf4, 0x74, 0xde, 0x00, 0xed, 0x99, 0xbe, 0x02, 0xbf, 0x65, 0x35, 0x3b, 0x09, 0x47, 0xff, 0x85, 0xef, 0xac, 0xf4, 0x29, 0xd0, 0x4a, 0x63, 0xb6, 0x55, 0xf8, 0x15, 0x95, 0xc2, 0x22, 0x33, 0x5c, 0x68, 0x36, 0x0a, 0xc9, 0xd2, 0x4b, 0x1f, 0x56, 0x1a, 0x3f, 0xb6, 0xc2, 0x35, 0x17, 0x3a, 0xfa, 0x43, 0x80, 0x36, 0xa9, 0x2e, 0xb8, 0xc9, 0x6f, 0xee, 0x53, 0xb4, 0x5f, 0xc7, 0xe0, 0xdd, 0xb6, 0x3c, 0x03, 0x5f, 0xcb, 0x4a, 0xe5, 0x78, 0x97, 0xc8, 0x6b, 0x2e, 0xae, 0x0a, 0xfa, 0x0c, 0x46, 0xa5, 0x14, 0xbb, 0x18, 0x67, 0xc3, 0x49, 0xde, 0x4b, 0xd1, 0x96, 0x79, 0x77, 0x94, 0x5a, 0x27, 0x7d, 0x0d, 0x93, 0x5c, 0x56, 0x1b, 0x83, 0xca, 0x75, 0x9f, 0x26, 0x4f, 0x86, 0xd0, 0xdb, 0x46, 0xee, 0x80, 0x2d, 0x41, 0x5f, 0xc2, 0xa9, 0xe0, 0x95, 0x40, 0x76, 0xe2, 0xd0, 0xf3, 0x21, 0x7a, 0x69, 0xc5, 0x0e, 0xd8, 0xb8, 0x2d, 0x66, 0xd6, 0xdf, 0x50, 0xb1, 0xd3, 0xc3, 0xd8, 0xb5, 0x15, 0xbb, 0x98, 0x73, 0x5b, 0x0c, 0x6b, 0xdc, 0x18, 0x36, 0x3e, 0x8c, 0xad, 0xac, 0xd8, 0xc5, 0x9c, 0xfb, 0xc2, 0x87, 0xc9, 0x07, 0xd4, 0x9a, 0x0b, 0x8c, 0x66, 0x30, 0xed, 0x7c, 0x82, 0x28, 0x80, 0x59, 0x6f, 0xc2, 0xe8, 0x11, 0x04, 0x83, 0xb4, 0xd6, 0xd3, 0x1b, 0xc7, 0x5e, 0xf4, 0x1a, 0x25, 0x3f, 0x09, 0x8c, 0x9b, 0xbd, 0xa3, 0x97, 0xe0, 0xa5, 0x98, 0xe3, 0xba, 0x46, 0x45, 0xf7, 0xc7, 0xeb, 0xbe, 0xb8, 0xc5, 0xde, 0x96, 0xac, 0x76, 0x6f, 0x34, 0x3a, 0x7a, 0x4e, 0xe8, 0x67, 0x08, 0xdc, 0x12, 0x63, 0x71, 0x5b, 0x2f, 0x3a, 0x5c, 0xaf, 0xbb, 0xeb, 0x8b, 0xf3, 0x7f, 0x15, 0x75, 0x2e, 0x5b, 0xf9, 0xcb, 0xd8, 0xfd, 0x02, 0x5e, 0xfc, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x11, 0x21, 0x4c, 0xff, 0x32, 0x04, 0x00, 0x00, }
proto.RegisterType((*Selector)(nil), "loggregator.v2.Selector")
input.ts
import { Nullable } from 'nullable'; import { Another } from 'some'; class A { do(): Nullable<Another> {
new A();
return null; } }
bot.py
from os import environ from firebase_admin import credentials, db, initialize_app from flask import Flask, request from telebot import TeleBot, types from wikipedia import ( WikipediaPage, geosearch, page, random, search, set_lang, suggest, summary, ) # Firebase connection cred = credentials.Certificate("firebase.json") # Firebase key initialize_app( cred, {"databaseURL": "https://yourappname-user-default-rtdb.firebaseio.com/"} ) ref = db.reference("/") z = ref.get() # Telegram API TOKEN = "" # Bot key bot = TeleBot(TOKEN) # Flask connection server = Flask(__name__) # Common Messages error = "Wrong word, use <b>title</b>" error2 = "Wrong word, use <b>suggest</b>" word = " for the word..." # Languages lang_list = [ "aa", "ab", "abs", "ace", "ady", "ady-cyrl", "aeb", "aeb-arab", "aeb-latn", "af", "ak", "aln", "als", "alt", "am", "ami", "an", "ang", "anp", "ar", "arc", "arn", "arq", "ary", "arz", "as", "ase", "ast", "atj", "av", "avk", "awa", "ay", "az", "azb", "ba", "ban", "ban-bali", "bar", "bat-smg", "bbc", "bbc-latn", "bcc", "bcl", "be", "be-tarask", "be-x-old", "bg", "bgn", "bh", "bho", "bi", "bjn", "bm", "bn", "bo", "bpy", "bqi", "br", "brh", "bs", "btm", "bto", "bug", "bxr", "ca", "cbk-zam", "cdo", "ce", "ceb", "ch", "cho", "chr", "chy", "ckb", "co", "cps", "cr", "crh", "crh-cyrl", "crh-latn", "cs", "csb", "cu", "cv", "cy", "da", "de", "de-at", "de-ch", "de-formal", "din", "diq", "dsb", "dtp", "dty", "dv", "dz", "ee", "egl", "el", "eml", "en", "en-ca", "en-gb", "eo", "es", "es-419", "es-formal", "et", "eu", "ext", "fa", "ff", "fi", "fit", "fiu-vro", "fj", "fo", "fr", "frc", "frp", "frr", "fur", "fy", "ga", "gag", "gan", "gan-hans", "gan-hant", "gcr", "gd", "gl", "glk", "gn", "gom", "gom-deva", "gom-latn", "gor", "got", "grc", "gsw", "gu", "gv", "ha", "hak", "haw", "he", "hi", "hif", "hif-latn", "hil", "ho", "hr", "hrx", "hsb", "ht", "hu", "hu-formal", "hy", "hyw", "hz", "ia", "id", "ie", "ig", "ii", "ik", "ike-cans", "ike-latn", "ilo", "inh", "io", "is", "it", "iu", "ja", "jam", "jbo", "jut", "jv", "ka", "kaa", "kab", "kbd", "kbd-cyrl", "kbp", "kg", "khw", "ki", "kiu", "kj", "kjp", "kk", "kk-arab", "kk-cn", "kk-cyrl", "kk-kz", "kk-latn", "kk-tr", "kl", "km", "kn", "ko", "ko-kp", "koi", "kr", "krc", "kri", "krj", "krl", "ks", "ks-arab", "ks-deva", "ksh", "ku", "ku-arab", "ku-latn", "kum", "kv", "kw", "ky", "la", "lad", "lb", "lbe", "lez", "lfn", "lg", "li", "lij", "liv", "lki", "lld", "lmo", "ln", "lo", "loz", "lrc", "lt", "ltg", "lus", "luz", "lv", "lzh", "lzz", "mad", "mai", "map-bms", "mdf", "mg", "mh", "mhr", "mi", "min", "mk", "ml", "mn", "mni", "mnw", "mo", "mr", "mrh", "mrj", "ms", "mt", "mus", "mwl", "my", "myv", "mzn", "na", "nah", "nan", "nap", "nb", "nds", "nds-nl", "ne", "new", "ng", "nia", "niu", "nl", "nl-informal", "nn", "no", "nov", "nqo", "nrm", "nso", "nv", "ny", "nys", "oc", "olo", "om", "or", "os", "pa", "pag", "pam", "pap", "pcd", "pdc", "pdt", "pfl", "pi", "pih", "pl", "pms", "pnb", "pnt", "prg", "ps", "pt", "pt-br", "qu", "qug", "rgn", "rif", "rm", "rmy", "rn", "ro", "roa-rup", "roa-tara", "ru", "rue", "rup", "ruq", "ruq-cyrl", "ruq-latn", "rw", "sa", "sah", "sat", "sc", "scn", "sco", "sd", "sdc", "sdh", "se", "sei", "ses", "sg", "sgs", "sh", "shi", "shi-latn", "shi-tfng", "shn", "shy-latn", "si", "simple", "sk", "skr", "skr-arab", "sl", "sli", "sm", "sma", "smn", "sn", "so", "sq", "sr", "sr-ec", "sr-el", "srn", "ss", "st", "stq", "sty", "su", "sv", "sw", "szl", "szy", "ta", "tay", "tcy", "te", "tet", "tg", "tg-cyrl", "tg-latn", "th", "ti", "tk", "tl", "tly", "tn", "to", "tpi", "tr", "tru", "trv", "ts", "tt", "tt-cyrl", "tt-latn", "tum", "tw", "ty", "tyv", "tzm", "udm", "ug", "ug-arab", "ug-latn", "uk", "ur", "uz", "uz-cyrl", "uz-latn", "ve", "vec", "vep", "vi", "vls", "vmf", "vo", "vot", "vro", "wa", "war", "wo", "wuu", "xal", "xh", "xmf", "xsy", "yi", "yo", "yue", "za", "zea", "zgh", "zh", "zh-classical", "zh-cn", "zh-hans", "zh-hant", "zh-hk", "zh-min-nan", "zh-mo", "zh-my", "zh-sg", "zh-tw", "zh-yue", "zu", ] def main_keyboard(): markup = types.ReplyKeyboardMarkup( row_width=2, resize_keyboard=True, one_time_keyboard=True ) texts = [ "Definition 📖", "Title 🖊️️", "URL 🔗", "Language 🔣", "Random 🔀", "Help ⚠️", "Map 🗺️", "Nearby 📍", ] buttons = [] for text in texts: button = types.KeyboardButton(text) buttons.append(button) markup.add(*buttons) return markup def support_keyboard(): markup = types.ReplyKeyboardMarkup( row_width=2, resize_keyboard=True, one_time_keyboard=True ) texts = ["🧑🏻‍💻️ Dev", "🐛 Bug", "💻️ Source", "🔙 Back"] buttons = [] for text in texts: button = types.KeyboardButton(text) buttons.append(button) markup.add(*buttons) return markup def extra_keyboard(): markup = types.ReplyKeyboardMarkup( row_width=2, resize_keyboard=True, one_time_keyboard=True ) texts = ["Suggest 💡", "Fluky 💫", "Back ⬅️"] buttons = [] for text in texts: button = types.KeyboardButton(text) buttons.append(button) markup.add(*buttons) return markup def check(text, command): checker = str(text).replace("/", "").replace("#", "").lower().split(" ") if command in checker: return 1 return 0 def change_lan(message): user_id = str(message.from_user.id) set_lang(z[user_id]) @bot.message_handler(func=lambda message: check(message.text, "start")) def welcome(message): user_id = message.from_user.id ref.update({user_id: "en"}) welcome_msg = ( "Greetings " + message.from_user.first_name + ", I am Wikibot 🤖\n\n" "What can I do? Use <b>help</b>." ) bot.send_message( chat_id=message.chat.id, text=welcome_msg, parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "definition")) def definition(message): def_msg = bot.reply_to(message, "<b>Definition</b>" + word, parse_mode="html") bot.register_next_step_handler(def_msg, process_definition) def process_definition(message): try: def_msg = str(message.text) change_lan(message) def_str = summary(def_msg, sentences=10) def_split = def_str.split("\n\n", 1)[0] bot.send_message( chat_id=message.chat.id, text="<b>" + def_msg + "</b> \n\n" + def_split, parse_mode="html", reply_markup=main_keyboard(), ) except Exception as c: if str(c)[:7] == "Page id": msg = "<b>Not Found!</b>" else: msg = str(c).replace("may refer to", "<b>may refer to</b>") bot.send_message( chat_id=message.chat.id, text=msg, parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "title")) def title(message): title_msg = bot.reply_to(message, "<b>Title</b>" + word, parse_mode="html") bot.register_next_step_handler(title_msg, process_title) def process_title(message): try: title_msg = str(message.text) change_lan(message) title_result = search(title_msg) if title_result: bot.send_message( chat_id=message.chat.id, text="Possible titles are...", parse_mode="html", ) for i in title_result: bot.send_message( chat_id=message.chat.id, text=i.replace(title_msg, "<b>" + title_msg + "</b>").replace( title_msg.lower(), "<b>" + title_msg.lower() + "</b>" ), parse_mode="html", reply_markup=main_keyboard(), ) else: bot.send_message( chat_id=message.chat.id, text=error2, parse_mode="html", reply_markup=main_keyboard(), ) except Exception: bot.send_message( chat_id=message.chat.id, text=error2, parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "help")) def aid(message): text = ( "These keywords can be used to control me - \n\n" "<b>Primary</b> \n" "Definition 📖 - fetches definition of a word \n" "Title 🖊️️ - fetches a bunch of related titles\n" "URL 🔗 - gives the URL of wiki page of the word \n" "Prefix 🔡 - show all available languages \n" "Language 🔣 - set the language you want \n\n" "<b>Secondary</b> \n" "Nearby 📍 - locations near a coordinate \n" "Map 🗺️ - location in map with wiki database \n" "Random 🔀 - pops a random article from wiki \n\n" "<b>Extra</b> \n" "Fluky 💫 - fetches a random title from wiki \n" "Suggest 💡 - returns a suggested word if found \n" ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "url")) def url(message): url_msg = bot.reply_to(message, "<b>URL</b>" + word, parse_mode="html") bot.register_next_step_handler(url_msg, process_url) def process_url(message): try: url_message = str(message.text) change_lan(message) url_page = page(url_message).url url_link = "<a href='" + url_page + "'>🔗</a>" bot.send_message( chat_id=message.chat.id, text=url_link + "for <b>" + url_message + "</b>", parse_mode="html", reply_markup=main_keyboard(), ) except Exception: bot.send_message( chat_id=message.chat.id, text=error, parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "language")) def ln(message): ln_msg = bot.reply_to( message, "Type the prefix of your <b>language</b>...", pars
mode="html" ) bot.register_next_step_handler(ln_msg, process_ln) def process_ln(message): try: ln_msg = str(message.text).lower() if ln_msg in lang_list: user_id = message.from_user.id ref.update({user_id: str(message.text).lower()}) global z z = ref.get() text = "Set Successfully." else: text = ( "Please, check for the correct <a href=" '"https://github.com/themagicalmammal/wikibot/blob/master/Lang.md"' ">prefix</a>." ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=main_keyboard(), ) except Exception: bot.send_message( chat_id=message.chat.id, text="Error, changing language", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "support")) def support(message): text = ( "Support commands that I provide - \n\n" "Bugs 🐛 - to report bugs or suggest mods\n" "Dev 🧑🏻‍💻️ - provides information about my creator\n" "Source 💻️ - to view the source code" ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=support_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "prefix")) def prefix(message): text = ( "Language is set with the help of it's Prefix. \n<b>Example</b> - English:en<a " 'href="https://github.com/themagicalmammal/wikibot/blob/master/Lang.md"' ">.</a>" ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "random")) def randomize(message): try: change_lan(message) random_title = page(random(pages=1)).url random_text = "<a href='" + random_title + "'>✨</a>" bot.send_message( chat_id=message.chat.id, text=random_text, parse_mode="html", reply_markup=main_keyboard(), ) except: randomize(message) @bot.message_handler(func=lambda message: check(message.text, "map")) def chart(message): co_msg = bot.reply_to(message, "<b>Location</b> of the place...", parse_mode="html") bot.register_next_step_handler(co_msg, process_co) def process_co(message): try: co_msg = str(message.text) set_lang("en") lat, lon = WikipediaPage(co_msg).coordinates bot.send_message( chat_id=message.chat.id, text=str(round(lat, 5)) + ", " + str(round(lon, 5)) ) bot.send_location( chat_id=message.chat.id, latitude=lat, longitude=lon, reply_markup=main_keyboard(), ) except Exception: bot.send_message( chat_id=message.chat.id, text="Not a location.", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "nearby")) def geo(message): geo_msg = bot.reply_to( message, "Send me the <b>coordinates</b>...", parse_mode="html" ) bot.register_next_step_handler(geo_msg, process_geo) def process_geo(message): try: lat, lan = ( str(message.text) .replace("E", "") .replace("W", "") .replace("N", "") .replace("S", "") .replace("° ", "") .replace("°", "") .replace(",", "") .replace(" ", " ") .split(" ") ) set_lang("en") locations = geosearch(latitude=lat, longitude=lan, results=10, radius=1000) if locations: nearby = "<b>Nearby locations</b> are..." bot.send_message( chat_id=message.chat.id, text=nearby, parse_mode="html", reply_markup=main_keyboard(), ) for i in locations: bot.send_message( chat_id=message.chat.id, text=i, reply_markup=main_keyboard() ) else: sorry = "Sorry, can't find nearby locations" bot.send_message( chat_id=message.chat.id, text=sorry, reply_markup=main_keyboard() ) except Exception: bot.send_message( chat_id=message.chat.id, text="Use <b>Map</b> to get coordinates.", parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "fluky")) def fluky(message): change_lan(message) fluky_title = random(pages=1) bot.send_message( chat_id=message.chat.id, text=fluky_title, reply_markup=extra_keyboard() ) @bot.message_handler(func=lambda message: check(message.text, "back")) def back(message): bot.send_message( chat_id=message.chat.id, text="<b>Commands</b>", parse_mode="html", reply_markup=main_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "suggest")) def suggestion(message): suggest_msg = bot.reply_to( message, "<b>Suggestion</b> for the word...", parse_mode="html" ) bot.register_next_step_handler(suggest_msg, process_suggest) def process_suggest(message): sorry = "Sorry, <b>no suggestions.</b>" try: suggest_msg = str(message.text) change_lan(message) suggest_str = str(suggest(suggest_msg)) if suggest_str != "None": text = suggest_str else: text = sorry bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=extra_keyboard(), ) except Exception: bot.send_message( chat_id=message.chat.id, text=sorry, parse_mode="html", reply_markup=extra_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "bug")) def bug(message): text = ( "Submit a Issue or Revision<a " 'href="https://github.com/themagicalmammal/wikibot/issues">.</a> ' ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=support_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "dev")) def dev(message): text = ( "I was made with ❤ by @themagicalmammal" '<a href="https://github.com/themagicalmammal">.</a>' ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=support_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "source")) def source(message): text = ( "Checkout out How I was made" '<a href="https://github.com/themagicalmammal/wikibot">.</a>' ) bot.send_message( chat_id=message.chat.id, text=text, parse_mode="html", reply_markup=support_keyboard(), ) @bot.message_handler(func=lambda message: check(message.text, "extra")) def extra(message): bot.send_message( chat_id=message.chat.id, text="<b>Extra</b>", parse_mode="html", reply_markup=extra_keyboard(), ) @bot.message_handler(func=lambda message: True) def unrecognized(message): bot.send_message( chat_id=message.chat.id, text="<b>Please</b>, use a keyword", parse_mode="html", reply_markup=main_keyboard(), ) # Heroku Connection @server.route("/" + TOKEN, methods=["POST"]) def establish(): bot.process_new_updates( [types.Update.de_json(request.stream.read().decode("utf-8"))] ) return "!", 200 @server.route("/") def webhook(): bot.remove_webhook() bot.set_webhook(url="https://yourappname.herokuapp.com/" + TOKEN) return "!", 200 if __name__ == "__main__": server.run(host="0.0.0.0", port=int(environ.get("PORT", 5000)))
e_
load_save_model.py
import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from tensorflow.keras.datasets import mnist from tensorflow.keras.layers import * from tensorflow.keras.models import * def load_data(): (X_train, y_train), (X_test, y_test) = mnist.load_data() # Normalize data. X_train = X_train.astype('float32') / 255.0 X_test = X_test.astype('float32') / 255.0 # Reshape grayscale to include channel dimension. X_train = np.expand_dims(X_train, axis=3) X_test = np.expand_dims(X_test, axis=3)
y_test = label_binarizer.fit_transform(y_test) return X_train, y_train, X_test, y_test def build_network(): input_layer = Input(shape=(28, 28, 1), name='input_layer') convolution_1 = Conv2D(kernel_size=(2, 2), padding='same', strides=(2, 2), filters=32, name='convolution_1')(input_layer) activation_1 = ReLU(name='activation_1')(convolution_1) batch_normalization_1 = BatchNormalization(name='batch_normalization_1')(activation_1) pooling_1 = MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same', name='pooling_1')(batch_normalization_1) dropout = Dropout(rate=0.5, name='dropout')(pooling_1) flatten = Flatten(name='flatten')(dropout) dense_1 = Dense(units=128, name='dense_1')(flatten) activation_2 = ReLU(name='activation_2')(dense_1) dense_2 = Dense(units=10, name='dense_2')(activation_2) output = Softmax(name='output')(dense_2) network = Model(inputs=input_layer, outputs=output, name='my_model') return network def evaluate(model, X_test, y_test): _, accuracy = model.evaluate(X_test, y_test, verbose=0) print(f'Accuracy: {accuracy}') print('Loading and pre-processing data.') X_train, y_train, X_test, y_test = load_data() # Split dataset. X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, train_size=0.8) # Build network. model = build_network() # Compile and train model. print('Training network...') model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, validation_data=(X_valid, y_valid), epochs=40, batch_size=1024) print('Saving model and weights as HDF5.') model.save('model_and_weights.hdf5') print('Loading model and weights as HDF5.') loaded_model = load_model('model_and_weights.hdf5') print('Evaluating using loaded model.') evaluate(loaded_model, X_test, y_test)
# Process labels. label_binarizer = LabelBinarizer() y_train = label_binarizer.fit_transform(y_train)
dhtmlxscheduler_minical.js
/* @license dhtmlxScheduler v.4.4.4 Professional Evaluation This software is covered by DHTMLX Evaluation License. Contact [email protected] to get Commercial or Enterprise license. Usage without proper license is prohibited. (c) Dinamenta, UAB. */ Scheduler.plugin(function(e){e.templates.calendar_month=e.date.date_to_str("%F %Y"),e.templates.calendar_scale_date=e.date.date_to_str("%D"),e.templates.calendar_date=e.date.date_to_str("%d"),e.config.minicalendar={mark_events:!0},e._synced_minicalendars=[],e.renderCalendar=function(t,a,n){var i=null,r=t.date||e._currentDate();if("string"==typeof r&&(r=this.templates.api_date(r)),a)i=this._render_calendar(a.parentNode,r,t,a),e.unmarkCalendar(i);else{var o=t.container,d=t.position;if("string"==typeof o&&(o=document.getElementById(o)), "string"==typeof d&&(d=document.getElementById(d)),d&&"undefined"==typeof d.left){var l=getOffset(d);d={top:l.top+d.offsetHeight,left:l.left}}o||(o=e._get_def_cont(d)),i=this._render_calendar(o,r,t),i.onclick=function(t){t=t||event;var a=t.target||t.srcElement;if(-1!=a.className.indexOf("dhx_month_head")){var n=a.parentNode.className;if(-1==n.indexOf("dhx_after")&&-1==n.indexOf("dhx_before")){var i=e.templates.xml_date(this.getAttribute("date"));i.setDate(parseInt(a.innerHTML,10)),e.unmarkCalendar(this), e.markCalendar(this,i,"dhx_calendar_click"),this._last_date=i,this.conf.handler&&this.conf.handler.call(e,i,this)}}}}if(e.config.minicalendar.mark_events)for(var s=e.date.month_start(r),_=e.date.add(s,1,"month"),c=this.getEvents(s,_),u=this["filter_"+this._mode],h={},p=0;p<c.length;p++){var v=c[p];if(!u||u(v.id,v)){var m=v.start_date;for(m.valueOf()<s.valueOf()&&(m=s),m=e.date.date_part(new Date(m.valueOf()));m<v.end_date&&(h[+m]||(h[+m]=!0,this.markCalendar(i,m,"dhx_year_event")),m=this.date.add(m,1,"day"), !(m.valueOf()>=_.valueOf())););}}return this._markCalendarCurrentDate(i),i.conf=t,t.sync&&!n&&this._synced_minicalendars.push(i),i.conf._on_xle_handler||(i.conf._on_xle_handler=e.attachEvent("onXLE",function(){e.updateCalendar(i,i.conf.date)})),i},e._get_def_cont=function(e){return this._def_count||(this._def_count=document.createElement("DIV"),this._def_count.className="dhx_minical_popup",this._def_count.onclick=function(e){(e||event).cancelBubble=!0},document.body.appendChild(this._def_count)), this._def_count.style.left=e.left+"px",this._def_count.style.top=e.top+"px",this._def_count._created=new Date,this._def_count},e._locateCalendar=function(t,a){if("string"==typeof a&&(a=e.templates.api_date(a)),+a>+t._max_date||+a<+t._min_date)return null;for(var n=t.querySelector(".dhx_year_body").childNodes[0],i=0,r=new Date(t._min_date);+this.date.add(r,1,"week")<=+a;)r=this.date.add(r,1,"week"),i++;var o=e.config.start_on_monday,d=(a.getDay()||(o?7:0))-(o?1:0);return n.rows[i].cells[d].firstChild; },e.markCalendar=function(e,t,a){var n=this._locateCalendar(e,t);n&&(n.className+=" "+a)},e.unmarkCalendar=function(e,t,a){if(t=t||e._last_date,a=a||"dhx_calendar_click",t){var n=this._locateCalendar(e,t);n&&(n.className=(n.className||"").replace(RegExp(a,"g")))}},e._week_template=function(t){for(var a=t||250,n=0,i=document.createElement("div"),r=this.date.week_start(e._currentDate()),o=0;7>o;o++)this._cols[o]=Math.floor(a/(7-o)),this._render_x_header(o,n,r,i),r=this.date.add(r,1,"day"),a-=this._cols[o], n+=this._cols[o];return i.lastChild.className+=" dhx_scale_bar_last",i},e.updateCalendar=function(e,t){e.conf.date=t,this.renderCalendar(e.conf,e,!0)},e._mini_cal_arrows=["&nbsp","&nbsp"],e._render_calendar=function(t,a,n,i){var r=e.templates,o=this._cols;this._cols=[];var d=this._mode;this._mode="calendar";var l=this._colsS;this._colsS={height:0};var s=new Date(this._min_date),_=new Date(this._max_date),c=new Date(e._date),u=r.month_day,h=this._ignores_detected;this._ignores_detected=0,r.month_day=r.calendar_date, a=this.date.month_start(a);var p,v=this._week_template(t.offsetWidth-1-this.config.minicalendar.padding);i?p=i:(p=document.createElement("DIV"),p.className="dhx_cal_container dhx_mini_calendar"),p.setAttribute("date",this.templates.xml_format(a)),p.innerHTML="<div class='dhx_year_month'></div><div class='dhx_year_grid'><div class='dhx_year_week'>"+(v?v.innerHTML:"")+"</div><div class='dhx_year_body'></div></div>";var m=p.querySelector(".dhx_year_month"),g=p.querySelector(".dhx_year_week"),f=p.querySelector(".dhx_year_body"); if(m.innerHTML=this.templates.calendar_month(a),n.navigation)for(var b=function(t,a){var n=e.date.add(t._date,a,"month");e.updateCalendar(t,n),e._date.getMonth()==t._date.getMonth()&&e._date.getFullYear()==t._date.getFullYear()&&e._markCalendarCurrentDate(t)},y=["dhx_cal_prev_button","dhx_cal_next_button"],x=["left:1px;top:2px;position:absolute;","left:auto; right:1px;top:2px;position:absolute;"],k=[-1,1],w=function(t){return function(){if(n.sync)for(var a=e._synced_minicalendars,i=0;i<a.length;i++)b(a[i],t);else b(p,t); }},D=[e.locale.labels.prev,e.locale.labels.next],S=0;2>S;S++){var E=document.createElement("DIV");E.className=y[S],e._waiAria.headerButtonsAttributes(E,D[S]),E.style.cssText=x[S],E.innerHTML=this._mini_cal_arrows[S],m.appendChild(E),E.onclick=w(k[S])}p._date=new Date(a),p.week_start=(a.getDay()-(this.config.start_on_monday?1:0)+7)%7;var N=p._min_date=this.date.week_start(a);p._max_date=this.date.add(p._min_date,6,"week"),this._reset_month_scale(f,a,N,6),i||t.appendChild(p),g.style.height=g.childNodes[0].offsetHeight-1+"px"; var M=e.uid();e._waiAria.minicalHeader(m,M),e._waiAria.minicalGrid(p.querySelector(".dhx_year_grid"),M),e._waiAria.minicalRow(g);for(var A=g.querySelectorAll(".dhx_scale_bar"),O=0;O<A.length;O++)e._waiAria.minicalHeadCell(A[O]);for(var C=f.querySelectorAll("td"),T=new Date(s),O=0;O<C.length;O++)e._waiAria.minicalDayCell(C[O],new Date(T)),T=e.date.add(T,1,"day");return e._waiAria.minicalHeader(m,M),this._cols=o,this._mode=d,this._colsS=l,this._min_date=s,this._max_date=_,e._date=c,r.month_day=u,this._ignores_detected=h, p},e.destroyCalendar=function(t,a){!t&&this._def_count&&this._def_count.firstChild&&(a||(new Date).valueOf()-this._def_count._created.valueOf()>500)&&(t=this._def_count.firstChild),t&&(t.onclick=null,t.innerHTML="",t.parentNode&&t.parentNode.removeChild(t),this._def_count&&(this._def_count.style.top="-1000px"),t.conf&&t.conf._on_xle_handler&&e.detachEvent(t.conf._on_xle_handler))},e.isCalendarVisible=function(){return this._def_count&&parseInt(this._def_count.style.top,10)>0?this._def_count:!1},e._attach_minical_events=function(){ dhtmlxEvent(document.body,"click",function(){e.destroyCalendar()}),e._attach_minical_events=function(){}},e.attachEvent("onTemplatesReady",function(){e._attach_minical_events()}),e.templates.calendar_time=e.date.date_to_str("%d-%m-%Y"),e.form_blocks.calendar_time={render:function(t){var a="<input class='dhx_readonly' type='text' readonly='true'>",n=e.config,i=this.date.date_part(e._currentDate()),r=1440,o=0;n.limit_time_select&&(o=60*n.first_hour,r=60*n.last_hour+1),i.setHours(o/60),t._time_values=[], a+=" <select>";for(var d=o;r>d;d+=1*this.config.time_step){var l=this.templates.time_picker(i);a+="<option value='"+d+"'>"+l+"</option>",t._time_values.push(d),i=this.date.add(i,this.config.time_step,"minute")}a+="</select>";e.config.full_day;return"<div style='height:30px;padding-top:0; font-size:inherit;' class='dhx_section_time'>"+a+"<span style='font-weight:normal; font-size:10pt;'> &nbsp;&ndash;&nbsp; </span>"+a+"</div>"},set_value:function(t,a,n,i){function
(t,a,n){c(t,a,n),t.value=e.templates.calendar_time(a), t._date=e.date.date_part(new Date(a))}function o(e){for(var t=i._time_values,a=60*e.getHours()+e.getMinutes(),n=a,r=!1,o=0;o<t.length;o++){var d=t[o];if(d===a){r=!0;break}a>d&&(n=d)}return r||n?r?a:n:-1}var d,l,s=t.getElementsByTagName("input"),_=t.getElementsByTagName("select"),c=function(t,a,n){t.onclick=function(){e.destroyCalendar(null,!0),e.renderCalendar({position:t,date:new Date(this._date),navigation:!0,handler:function(a){t.value=e.templates.calendar_time(a),t._date=new Date(a),e.destroyCalendar(), e.config.event_duration&&e.config.auto_end_date&&0===n&&v()}})}};if(e.config.full_day){if(!t._full_day){var u="<label class='dhx_fullday'><input type='checkbox' name='full_day' value='true'> "+e.locale.labels.full_day+"&nbsp;</label></input>";e.config.wide_form||(u=t.previousSibling.innerHTML+u),t.previousSibling.innerHTML=u,t._full_day=!0}var h=t.previousSibling.getElementsByTagName("input")[0],p=0===e.date.time_part(n.start_date)&&0===e.date.time_part(n.end_date);h.checked=p,_[0].disabled=h.checked, _[1].disabled=h.checked,h.onclick=function(){if(h.checked===!0){var a={};e.form_blocks.calendar_time.get_value(t,a),d=e.date.date_part(a.start_date),l=e.date.date_part(a.end_date),(+l==+d||+l>=+d&&(0!==n.end_date.getHours()||0!==n.end_date.getMinutes()))&&(l=e.date.add(l,1,"day"))}var i=d||n.start_date,o=l||n.end_date;r(s[0],i),r(s[1],o),_[0].value=60*i.getHours()+i.getMinutes(),_[1].value=60*o.getHours()+o.getMinutes(),_[0].disabled=h.checked,_[1].disabled=h.checked}}if(e.config.event_duration&&e.config.auto_end_date){ var v=function(){d=e.date.add(s[0]._date,_[0].value,"minute"),l=new Date(d.getTime()+60*e.config.event_duration*1e3),s[1].value=e.templates.calendar_time(l),s[1]._date=e.date.date_part(new Date(l)),_[1].value=60*l.getHours()+l.getMinutes()};_[0].onchange=v}r(s[0],n.start_date,0),r(s[1],n.end_date,1),c=function(){},_[0].value=o(n.start_date),_[1].value=o(n.end_date)},get_value:function(t,a){var n=t.getElementsByTagName("input"),i=t.getElementsByTagName("select");return a.start_date=e.date.add(n[0]._date,i[0].value,"minute"), a.end_date=e.date.add(n[1]._date,i[1].value,"minute"),a.end_date<=a.start_date&&(a.end_date=e.date.add(a.start_date,e.config.time_step,"minute")),{start_date:new Date(a.start_date),end_date:new Date(a.end_date)}},focus:function(e){}},e.linkCalendar=function(t,a){var n=function(){var n=e._date,i=new Date(n.valueOf());return a&&(i=a(i)),i.setDate(1),e.updateCalendar(t,i),!0};e.attachEvent("onViewChange",n),e.attachEvent("onXLE",n),e.attachEvent("onEventAdded",n),e.attachEvent("onEventChanged",n),e.attachEvent("onAfterEventDelete",n), n()},e._markCalendarCurrentDate=function(t){var a=e._date,n=e._mode,i=e.date.month_start(new Date(t._date)),r=e.date.add(i,1,"month");if("day"==n||this._props&&this._props[n])i.valueOf()<=a.valueOf()&&r>a&&e.markCalendar(t,a,"dhx_calendar_click");else if("week"==n)for(var o=e.date.week_start(new Date(a.valueOf())),d=0;7>d;d++)i.valueOf()<=o.valueOf()&&r>o&&e.markCalendar(t,o,"dhx_calendar_click"),o=e.date.add(o,1,"day")},e.attachEvent("onEventCancel",function(){e.destroyCalendar(null,!0)})});
r
wfs.py
# import convert_ui_and_qrc_files import json import os import pathlib import shutil import sys from functools import partial from pprint import pprint import imagehash from PIL import Image from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor, QKeySequence, QPalette from PyQt5.QtWidgets import (QAbstractItemView, QDialog, QFileDialog, QFileSystemModel, QShortcut) from send2trash import send2trash from main_ui import Ui_MainWindow from vers import get_version if not os.path.exists('delete'): os.makedirs('delete') class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.ui = Ui_MainWindow() self.ui.setupUi(self) # style window self.setWindowTitle("Waifu File Sort") app_icon = QtGui.QIcon() app_icon.addFile("./icons/waifu_sort.png", QtCore.QSize(256, 256)) self.setWindowIcon(app_icon) # store important data self.path_hotkey_dict = {} self.hotkey_path_dict = {} self._shortcut_list = [] self.undo_list = [] self.delete_folder = str(pathlib.Path(find_data_file("delete"))) self.current_file_folder = "" self.pic_ext_list = [".jpg", ".png", ".webp", ".JPEG", ".PNG"] self.default_palette = QtGui.QGuiApplication.palette() # initialize source directory self.model = QFileSystemModel() self.model.setNameFilters( ["*.jpg", "*.png", "*.webp", "*.JPEG", "*.PNG"]) self.model.setNameFilterDisables(False) self.ui.treeView.setModel(self.model) self.ui.treeView.setSelectionMode(QAbstractItemView.SingleSelection) self.ui.tableWidget.setSelectionMode( QtWidgets.QAbstractItemView.SingleSelection ) self.ui.treeView.selectionModel().selectionChanged.connect( self.update_image_label ) # hotkeys self.delShortcut = QShortcut(QKeySequence("Delete"), self) self.delShortcut.activated.connect( partial(self.move_cb, None, self.delete_folder) ) self.undoShortcut = QShortcut(QKeySequence("Ctrl+Z"), self) self.undoShortcut.activated.connect(self.undo_cb) # callbacks init self.ui.browseBtn.clicked.connect(self.browse_source_click) self.ui.addDest.clicked.connect(self.add_dest_to_table) self.ui.removeDest.clicked.connect(self.remove_destination) self.ui.actionAbout.triggered.connect(self.show_about_dialog) self.ui.actionSave_Preset.triggered.connect(self.save_preset_cb) self.ui.actionLoad_Preset.triggered.connect(self.load_preset_cb) self.ui.actionClear_Delete_Folder.triggered.connect(self.clear_deleted_folder) self.ui.unmoveBtn.clicked.connect(self.undo_cb) self.ui.checkDeletedBtn.clicked.connect(self.check_deleted_btn_cb) self.ui.actionFancy.triggered.connect(self.set_fancy_style) self.ui.actionLight.triggered.connect(self.set_light_style) self.ui.actionDark.triggered.connect(self.set_dark_style) self.ui.comboMode.currentTextChanged.connect(self.change_file_type) self.ui.actionOrange.triggered.connect(self.set_orange_style) self.ui.actionRemove_Duplicates.triggered.connect( self.remove_duplicate_pictures) self.ui.actionRemove_Duplicates_Recursively.triggered.connect( partial(self.remove_duplicate_pictures, recursive_delete=True)) self.set_dark_style() def remove_duplicate_pictures(self, recursive_delete=False): root_path = self.model.rootPath() if root_path == ".": return # if source destination wasnt chosen # check for missclick msg = "Are you sure you want to delete (trash bin) duplicate pictures from source folder?" reply = QtWidgets.QMessageBox.question(self, 'Message', msg, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply != QtWidgets.QMessageBox.Yes: return # gather pictures from root path all_pictures = [] if recursive_delete: # recursive search for path in pathlib.Path(root_path).glob(r'**/*'): if path.suffix in self.pic_ext_list: all_pictures.append(path) else: # non recursive for path in pathlib.Path(root_path).glob(r'*'): if path.suffix in self.pic_ext_list: all_pictures.append(path) # add phash of picture to dictionary, replace with shorter filename if same hash found result_pics = {} for path in all_pictures: with Image.open(path) as img: img_hash = str(imagehash.phash(img)) if img_hash in result_pics: dict_fname = result_pics[img_hash].stem if len(path.stem) < len(dict_fname): result_pics[img_hash] = path else: result_pics[img_hash] = path result_pics = {value: key for key, value in result_pics.items()} # delete all pictures that are not in a result_pics dict for path in all_pictures: if path not in result_pics: try: shutil.move(str(path), self.delete_folder) except shutil.Error: send2trash(str(path)) QtWidgets.QMessageBox.about(self, "Info", "Done") def add_text_to_buttons(self): self.ui.addDest.setText("Add") self.ui.removeDest.setText("Remove") self.ui.browseBtn.setText("Browse") self.ui.checkDeletedBtn.setText("Deleted") self.ui.unmoveBtn.setText("Undo") def remove_text_from_buttons(self): self.ui.addDest.setText("") self.ui.removeDest.setText("") self.ui.browseBtn.setText("") self.ui.checkDeletedBtn.setText("") self.ui.unmoveBtn.setText("") def set_orange_style(self): QtGui.QGuiApplication.setPalette(self.default_palette) with open("./styles/orange.css") as f: style_text = f.read() self.setStyleSheet(style_text) self.add_text_to_buttons() def set_fancy_style(self): QtGui.QGuiApplication.setPalette(self.default_palette) with open("./styles/fancy.css") as f: style_text = f.read() self.setStyleSheet(style_text) self.remove_text_from_buttons() def set_light_style(self): QtGui.QGuiApplication.setPalette(self.default_palette) self.setStyleSheet(" ") self.add_text_to_buttons() def set_dark_style(self): self.setStyleSheet(" ") self.add_text_to_buttons() dark_palette = QPalette() dark_palette.setColor(QPalette.Window, QColor(53, 53, 53)) dark_palette.setColor(QPalette.WindowText, Qt.white) dark_palette.setColor(QPalette.Base, QColor(25, 25, 25)) dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) dark_palette.setColor(QPalette.ToolTipBase, Qt.white) dark_palette.setColor(QPalette.ToolTipText, Qt.white) dark_palette.setColor(QPalette.Text, Qt.white) dark_palette.setColor(QPalette.Button, QColor(53, 53, 53)) dark_palette.setColor(QPalette.ButtonText, Qt.white) dark_palette.setColor(QPalette.BrightText, Qt.red) dark_palette.setColor(QPalette.Link, QColor(42, 130, 218)) dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218)) dark_palette.setColor(QPalette.HighlightedText, Qt.black) QtGui.QGuiApplication.setPalette(dark_palette) def change_file_type(self): """ Change source directory display between pictures and files """ mode = self.ui.comboMode.currentText() if mode == "Files": self.model.setNameFilters(["*.*"]) elif mode == "Pictures": self.model.setNameFilters( ["*.jpg", "*.png", "*.webp", ".JPEG", ".PNG"]) def check_deleted_btn_cb(self): """ This is supposed to change model view to the deleted folder, and second press is supposed to bring you back to the previous folder, but it doesnt work if you dont select an image in deleted folder. """ ind = self.ui.treeView.currentIndex() file_path = self.model.filePath(ind) try: file_path = pathlib.Path(file_path).parents[0].resolve() except IndexError: return if file_path != pathlib.Path(self.delete_folder).resolve(): self.model.setRootPath(self.delete_folder) self.ui.treeView.setRootIndex(self.model.index(self.delete_folder)) else: self.model.setRootPath(self.current_file_folder) self.ui.treeView.setRootIndex( self.model.index(self.current_file_folder)) def clear_deleted_folder(self): msg = "Are you sure you want to clear folder with deleted files?" reply = QtWidgets.QMessageBox.question(self, 'Message', msg, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: p = pathlib.Path(self.delete_folder) for filename in p.glob("*"): send2trash(str(filename)) QtWidgets.QMessageBox.about( self, "Delete folder cleared", "Delete folder cleared" ) def undo_cb(self): """ Store actions in a list, revert them 1 by 1 """ try: last_operation = self.undo_list[-1] except IndexError: return pic_path, dest_path = last_operation pic_path = pathlib.Path(pic_path) dest_path = pathlib.Path(dest_path, pic_path.name) pic_path, dest_path = dest_path, pic_path # print(pic_path.parents[0], dest_path) try: shutil.move(pic_path, str(dest_path)) except shutil.Error: QtWidgets.QMessageBox.warning(
return del self.undo_list[-1] def load_preset_cb(self): """ Load user settings from file """ dialog = QFileDialog() dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden) dialog.setDefaultSuffix("json") dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setNameFilters(["JSON (*.json)"]) if dialog.exec_() == QDialog.Accepted: preset_path = dialog.selectedFiles()[0] self.path_hotkey_dict = load_json(preset_path) self.path_hotkey_dict = { k: v for k, v in self.path_hotkey_dict.items() if v is not None } print("loaded dict: ", self.path_hotkey_dict) self.hotkey_path_dict = { value: key for key, value in self.path_hotkey_dict.items() } self.restore_table_from_dict() else: print("Cancelled") def save_preset_cb(self): """ Save user settings to file """ dialog = QFileDialog() dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden) dialog.setDefaultSuffix("json") dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setNameFilters(["JSON (*.json)"]) if dialog.exec_() == QDialog.Accepted: preset_path = dialog.selectedFiles()[0] save_json(self.path_hotkey_dict, preset_path) QtWidgets.QMessageBox.information( self, "Saved", f"Saved hotkey preset: {preset_path}" ) else: print("Cancelled") def show_about_dialog(self): text = ( "<center>" "<h1>Waifu File Sort</h1>" "&#8291;" "</center>" f"<p>Version {get_version()}<br/>" ) QtWidgets.QMessageBox.about(self, "About Waifu File Sort", text) def restore_table_from_dict(self): self.clear_table_widget() row_counter = 0 for shortcut in self._shortcut_list: shortcut.setEnabled(False) self._shortcut_list = [] for path, hotkey in self.path_hotkey_dict.items(): path = pathlib.Path(path) self.add_dest_to_table(dest_path=path.name, hotkey=hotkey) self.ui.tableWidget.item(row_counter, 0).setToolTip(str(path)) shortcut = QShortcut(QKeySequence(hotkey), self) shortcut.activated.connect( lambda mypath=path: self.move_cb(input_path=mypath)) self._shortcut_list.append(shortcut) row_counter += 1 def clear_table_widget(self): self.ui.tableWidget.clearContents() self.ui.tableWidget.setRowCount(0) def remove_destination(self): # get selected row or return # delete info from both dicts # reconstruct table widget from dict current_row = self.ui.tableWidget.currentRow() # print(f"{current_row=}") try: dest_path = self.ui.tableWidget.item(current_row, 0).toolTip() except AttributeError: return hotkey = self.ui.tableWidget.cellWidget(current_row, 2).text() # print("deleting hotkey: ", hotkey) self.delete_hotkey(hotkey) try: del self.path_hotkey_dict[dest_path] except KeyError: pass try: del self.hotkey_path_dict[hotkey] except KeyError: pass self.restore_table_from_dict() def delete_hotkey(self, name): for shortcut in self._shortcut_list: key_name = shortcut.key().toString() # print("k-name: ", key_name) if key_name == name.upper(): # print("DELETED hotkey: ", name) shortcut.setEnabled(False) def add_dest_to_table(self, dest_path=None, hotkey=None): self.ui.tableWidget.setEditTriggers( self.ui.tableWidget.NoEditTriggers ) # disable editing and sorting self.ui.tableWidget.setSortingEnabled(False) row_counter = self.ui.tableWidget.rowCount() self.ui.tableWidget.insertRow(row_counter) ######################################################## # add path label dest_path = QtWidgets.QTableWidgetItem( dest_path or "Press browse to specify destination directory" ) self.ui.tableWidget.setItem(row_counter, 0, dest_path) ######################################################## # add browse button browse_btn = QtWidgets.QPushButton("Browse") browse_btn.clicked.connect( lambda *args, row_ind=row_counter: self.browse_dest_click(row_ind) ) self.ui.tableWidget.setCellWidget(row_counter, 1, browse_btn) ######################################################## # add hotkey line edit hotkey_line = QtWidgets.QLineEdit() hotkey_line.setPlaceholderText("Add hotkey") hotkey_line.setText(hotkey) hotkey_line.setMaxLength(1) hotkey_line.textChanged.connect( lambda *args, row_ind=row_counter: self.hotkey_line_text_changed_cb( hotkey_line, row_ind ) ) self.ui.tableWidget.setCellWidget(row_counter, 2, hotkey_line) ######################################################## # add send button send_btn = QtWidgets.QPushButton("Send") send_btn.clicked.connect( lambda *args, row_ind=row_counter: self.move_cb(row=row_ind) ) self.ui.tableWidget.setCellWidget(row_counter, 3, send_btn) def move_cb(self, row=None, input_path=None): ind = self.ui.treeView.currentIndex() pic_path = self.model.filePath(ind) dest_path = input_path or self.ui.tableWidget.item(row, 0).toolTip() dest_path = pathlib.Path(dest_path) if dest_path.is_dir() and str(dest_path) != ".": try: shutil.move(pic_path, str(dest_path)) except shutil.Error: QtWidgets.QMessageBox.warning( self, "Warning", "File already exists") return self.undo_list.append((pic_path, str(dest_path))) else: # notify user QtWidgets.QMessageBox.warning( self, "Warning", "Press Browse to add destination folder" ) def hotkey_line_text_changed_cb(self, hotkey_line, row_ind): hotkey = hotkey_line.text() path = self.ui.tableWidget.item(row_ind, 0).toolTip() if not path and len(hotkey) > 0: QtWidgets.QMessageBox.warning( self, "Warning", "Press Browse to add destination folder, add hotkey after" ) hotkey_line.clear() hotkey_line.clearFocus() return # check if hotkey line edit is empty and delete hotkey if len(hotkey) == 0 and path != "": hotkey_to_del = self.path_hotkey_dict[path] self.delete_hotkey(hotkey_to_del) self.path_hotkey_dict[path] = hotkey self.hotkey_path_dict = { value: key for key, value in self.path_hotkey_dict.items() } shortcut = QShortcut(QKeySequence(hotkey), self) # self._shortcut_list.append(shortcut.key().toString()) self._shortcut_list.append(shortcut) dest_path = self.hotkey_path_dict[hotkey] shortcut.activated.connect(lambda: self.move_cb(input_path=dest_path)) if len(hotkey) > 0: hotkey_line.clearFocus() def browse_dest_click(self, caller_row): # print(caller_row) dialog = QFileDialog() folder_path = dialog.getExistingDirectory(None, "Select Folder") p = pathlib.Path(folder_path) if folder_path: self.ui.tableWidget.item(caller_row, 0).setText(p.name) self.ui.tableWidget.item(caller_row, 0).setToolTip(str(p)) self.path_hotkey_dict[str(p)] = self.ui.tableWidget.cellWidget( caller_row, 2 ).text() def browse_source_click(self): dialog = QFileDialog() folder_path = dialog.getExistingDirectory(None, "Select Folder") if folder_path: self.model.setRootPath(folder_path) self.ui.treeView.setRootIndex(self.model.index(folder_path)) def update_image_label(self): ind = self.ui.treeView.currentIndex() file_path = self.model.filePath(ind) # keep track of current folder for check button return location try: path_to_current_folder = pathlib.Path(file_path).parents[0] except IndexError: return # fix click on C drive crash if str(path_to_current_folder.resolve()) != str( pathlib.Path(self.delete_folder).resolve() ): self.current_file_folder = str(path_to_current_folder) pixmap = QtGui.QPixmap(file_path) pixmap = pixmap.scaled( self.ui.imageLabel.width(), self.ui.imageLabel.height(), QtCore.Qt.KeepAspectRatio, ) self.ui.imageLabel.setPixmap(pixmap) self.ui.imageLabel.setAlignment(QtCore.Qt.AlignCenter) def save_json(data, result_name_with_ext): with open(result_name_with_ext, "w") as fp: json.dump(data, fp) def load_json(input_name_and_ext): with open(input_name_and_ext, "r") as fp: data = json.load(fp) return data def find_data_file(folder, filename=None): if getattr(sys, "frozen", False): # The application is frozen datadir = os.path.dirname(sys.executable) else: # The application is not frozen datadir = os.path.dirname(__file__) # The following line has been changed to match where you store your data files: if filename: return os.path.join(datadir, folder, filename) else: return os.path.join(datadir, folder) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) app.setStyle("Fusion") w = MainWindow() w.show() sys.exit(app.exec_())
self, "Warning", "File already exists") except AttributeError: return except FileNotFoundError:
time.js
"use strict"; class
{ static get current() { let hrtime = process.hrtime(); return (hrtime[0] * 1000000 + hrtime[1] / 1000) / 1000; } } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Time; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGltZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlscy90aW1lLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFDQTtJQUVFLFdBQVcsT0FBTztRQUNoQixJQUFJLE1BQU0sR0FBRyxPQUFPLENBQUMsTUFBTSxFQUFFLENBQUE7UUFDN0IsTUFBTSxDQUFDLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxHQUFHLE9BQU8sR0FBRyxNQUFNLENBQUMsQ0FBQyxDQUFDLEdBQUcsSUFBSSxDQUFDLEdBQUcsSUFBSSxDQUFDO0lBQ3pELENBQUM7QUFDSCxDQUFDO0FBTkQ7c0JBTUMsQ0FBQSJ9
Time
log.go
package log import ( "os" "github.com/go-logr/logr" "github.com/go-logr/zapr" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) const TimeFormat = "2006-01-02 15:04:05.999" var GlobalLogger, LogrLogger = MustNewLogger() var AtomicLevel = zap.NewAtomicLevel() // 通过更改 level 可一更改runtime logger的level func SetLevel(level str
GlobalLogger.Info("logger level updated", zap.String("level", level)) _ = AtomicLevel.UnmarshalText([]byte(level)) } func MustNewLogger() (*zap.Logger, logr.Logger) { config := zap.NewProductionConfig() config.Encoding = "console" config.Level = AtomicLevel // level from env _ = AtomicLevel.UnmarshalText([]byte(os.Getenv("LOG_LEVEL"))) config.EncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(TimeFormat) config.DisableCaller = false // disable caller config.DisableStacktrace = true // disable stacktrace logger, err := config.Build() if err != nil { panic(err) } return logger, zapr.NewLogger(logger) }
ing) {
index.tsx
import * as React from 'react' import * as Kb from '../../../common-adapters' import * as Styles from '../../../styles' // TODO: This is now desktop-only, so remove references to isMobile. export type Props = { contents: string isSelected: boolean keybaseUser: string name: string onSelect: () => void unreadPayments: number } const rightColumnStyle = Styles.platformStyles({ isElectron: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', }, }) const styles = Styles.styleSheetCreate({ amount: { ...rightColumnStyle, }, amountSelected: { ...rightColumnStyle, color: Styles.globalColors.white, }, avatar: {marginRight: Styles.globalMargins.xtiny}, badge: { marginLeft: 6, }, containerBox: { height: Styles.isMobile ? 56 : 48, }, icon: { alignSelf: 'center', height: 32, marginLeft: Styles.globalMargins.tiny, marginRight: Styles.globalMargins.tiny, }, rightColumn: rightColumnStyle, title: { ...rightColumnStyle, color: Styles.globalColors.black, }, titleSelected: { ...Styles.globalStyles.fontSemibold, ...rightColumnStyle, color: Styles.globalColors.white, }, unread: { backgroundColor: Styles.globalColors.orange, borderRadius: 6, flexShrink: 0, height: Styles.globalMargins.tiny, width: Styles.globalMargins.tiny, }, unreadContainer: { alignItems: 'center', alignSelf: 'stretch', flex: 1, justifyContent: 'flex-end', paddingRight: Styles.globalMargins.tiny, }, }) const HoverBox = Styles.isMobile ? Kb.Box2 : Styles.styled(Kb.Box2)({ ':hover': {backgroundColor: Styles.globalColors.blueGreyDark}, }) const WalletRow = (props: Props) => { return ( <Kb.ClickableBox onClick={props.onSelect}> <HoverBox style={Styles.collapseStyles([ styles.containerBox, props.isSelected ? {backgroundColor: Styles.globalColors.purpleLight} : {}, ])} direction="horizontal" fullWidth={true} >
type={props.isSelected ? 'icon-wallet-open-32' : 'icon-wallet-32'} color={Styles.globalColors.black} style={Kb.iconCastPlatformStyles(styles.icon)} /> <Kb.Box2 direction="vertical" style={styles.rightColumn}> <Kb.Box2 direction="horizontal" fullWidth={true}> {!!props.keybaseUser && ( <Kb.Avatar size={16} style={Kb.avatarCastPlatformStyles(styles.avatar)} username={props.keybaseUser} /> )} <Kb.Text type="BodySemibold" style={props.isSelected ? styles.titleSelected : styles.title}> {props.name} </Kb.Text> </Kb.Box2> <Kb.Text type="BodySmall" style={props.isSelected ? styles.amountSelected : styles.amount}> {props.contents} </Kb.Text> </Kb.Box2> {!!props.unreadPayments && <UnreadIcon unreadPayments={props.unreadPayments} />} </HoverBox> <Kb.Divider /> </Kb.ClickableBox> ) } const UnreadIcon = (props: {unreadPayments: number}) => ( <Kb.Box2 direction="horizontal" style={styles.unreadContainer}> {Styles.isMobile ? ( <Kb.Badge badgeNumber={props.unreadPayments} badgeStyle={styles.badge} /> ) : ( <Kb.Box2 direction="vertical" style={styles.unread} /> )} </Kb.Box2> ) export {WalletRow}
<Kb.Icon
blueprintcircuit.py
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Blueprint circuit object.""" from typing import Optional from abc import ABC, abstractmethod from qiskit.circuit import QuantumCircuit from qiskit.circuit.parametertable import ParameterTable, ParameterView class BlueprintCircuit(QuantumCircuit, ABC): """Blueprint circuit object. In many applications it is necessary to pass around the structure a circuit will have without explicitly knowing e.g. its number of qubits, or other missing information. This can be solved by having a circuit that knows how to construct itself, once all information is available. This class provides an interface for such circuits. Before internal data of the circuit is accessed, the ``_build`` method is called. There the configuration of the circuit is checked. """ def __init__(self, *regs, name: Optional[str] = None) -> None: """Create a new blueprint circuit. The ``_data`` argument storing the internal circuit data is set to ``None`` to indicate that the circuit has not been built yet. """ super().__init__(*regs, name=name) self._data = None self._qregs = [] self._cregs = [] self._qubits = [] self._qubit_set = set() @abstractmethod def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration allows the circuit to be built. Args: raise_on_failure: If True, raise if the configuration is invalid. If False, return False if the configuration is invalid. Returns: True, if the configuration is valid. Otherwise, depending on the value of ``raise_on_failure`` an error is raised or False is returned. """ raise NotImplementedError @abstractmethod def _build(self) -> None: """Build the circuit.""" # do not build the circuit if _data is already populated if self._data is not None: return self._data = [] # check whether the configuration is valid self._check_configuration() def
(self) -> None: """Invalidate the current circuit build.""" self._data = None self._parameter_table = ParameterTable() self.global_phase = 0 @property def qregs(self): """A list of the quantum registers associated with the circuit.""" return self._qregs @qregs.setter def qregs(self, qregs): """Set the quantum registers associated with the circuit.""" self._qregs = qregs self._qubits = [qbit for qreg in qregs for qbit in qreg] self._qubit_set = set(self._qubits) self._invalidate() @property def data(self): if self._data is None: self._build() return super().data @property def num_parameters(self) -> int: if self._data is None: self._build() return super().num_parameters @property def parameters(self) -> ParameterView: if self._data is None: self._build() return super().parameters def qasm(self, formatted=False, filename=None, encoding=None): if self._data is None: self._build() return super().qasm(formatted, filename, encoding) def append(self, instruction, qargs=None, cargs=None): if self._data is None: self._build() return super().append(instruction, qargs, cargs) def compose(self, other, qubits=None, clbits=None, front=False, inplace=False): if self._data is None: self._build() return super().compose(other, qubits, clbits, front, inplace) def inverse(self): if self._data is None: self._build() return super().inverse() def __len__(self): return len(self.data) def __getitem__(self, item): return self.data[item] def size(self): if self._data is None: self._build() return super().size() def to_instruction(self, parameter_map=None, label=None): if self._data is None: self._build() return super().to_instruction(parameter_map, label=label) def to_gate(self, parameter_map=None, label=None): if self._data is None: self._build() return super().to_gate(parameter_map, label=label) def depth(self): if self._data is None: self._build() return super().depth() def count_ops(self): if self._data is None: self._build() return super().count_ops() def num_nonlocal_gates(self): if self._data is None: self._build() return super().num_nonlocal_gates() def num_connected_components(self, unitary_only=False): if self._data is None: self._build() return super().num_connected_components(unitary_only=unitary_only) def copy(self, name=None): if self._data is None: self._build() return super().copy(name=name)
_invalidate
SettingsNav.tsx
import React from "react"; import { LinkWithQuery } from "../commonComponents/LinkWithQuery"; const SettingsNav = () => { const classNameByActive = ({ isActive }: { isActive: boolean }) => isActive ? "active" : ""; return ( <nav className="prime-secondary-nav" aria-label="Secondary navigation"> <ul className="usa-nav__secondary-links prime-nav"> <li className="usa-nav__secondary-item"> <LinkWithQuery to={`/settings`} end className={classNameByActive}> Manage users </LinkWithQuery> </li> <li className="usa-nav__secondary-item"> <LinkWithQuery to={`/settings/facilities`} className={classNameByActive} > Manage facilities </LinkWithQuery> </li> <li className="usa-nav__secondary-item"> <LinkWithQuery to={`/settings/organization`} className={classNameByActive} > Manage organization </LinkWithQuery> </li> <li className="usa-nav__secondary-item">
> Patient self-registration </LinkWithQuery> </li> </ul> </nav> ); }; export default SettingsNav;
<LinkWithQuery to={`/settings/self-registration`} className={classNameByActive}
secp256k1_32.rs
//! Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Rust secp256k1 32 '2^256 - 2^32 - 977' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp //! curve description: secp256k1 //! machine_wordsize = 32 (from "32") //! requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp //! m = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f (from "2^256 - 2^32 - 977") //! //! NOTE: In addition to the bounds specified above each function, all //! functions synthesized for this Montgomery arithmetic require the //! input to be strictly less than the prime modulus (m), and also //! require the input to be in the unique saturated representation. //! All functions also ensure that these two properties are true of //! return values. //! //! Computed values: //! eval z = z[0] + (z[1] << 32) + (z[2] << 64) + (z[3] << 96) + (z[4] << 128) + (z[5] << 160) + (z[6] << 192) + (z[7] << 224) //! bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) //! twos_complement_eval z = let x1 := z[0] + (z[1] << 32) + (z[2] << 64) + (z[3] << 96) + (z[4] << 128) + (z[5] << 160) + (z[6] << 192) + (z[7] << 224) in //! if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 #![allow(unused_parens)] #[allow(non_camel_case_types)] pub type fiat_secp256k1_u1 = u8; pub type fiat_secp256k1_i1 = i8; pub type fiat_secp256k1_u2 = u8; pub type fiat_secp256k1_i2 = i8; /// The function fiat_secp256k1_addcarryx_u32 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^32 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] #[inline] pub fn fiat_secp256k1_addcarryx_u32(out1: &mut u32, out2: &mut fiat_secp256k1_u1, arg1: fiat_secp256k1_u1, arg2: u32, arg3: u32) -> () { let x1: u64 = (((arg1 as u64) + (arg2 as u64)) + (arg3 as u64)); let x2: u32 = ((x1 & (0xffffffff as u64)) as u32); let x3: fiat_secp256k1_u1 = ((x1 >> 32) as fiat_secp256k1_u1); *out1 = x2; *out2 = x3; } /// The function fiat_secp256k1_subborrowx_u32 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^32 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] #[inline] pub fn fiat_secp256k1_subborrowx_u32(out1: &mut u32, out2: &mut fiat_secp256k1_u1, arg1: fiat_secp256k1_u1, arg2: u32, arg3: u32) -> () { let x1: i64 = (((arg2 as i64) - (arg1 as i64)) - (arg3 as i64)); let x2: fiat_secp256k1_i1 = ((x1 >> 32) as fiat_secp256k1_i1); let x3: u32 = ((x1 & (0xffffffff as i64)) as u32); *out1 = x3; *out2 = (((0x0 as fiat_secp256k1_i2) - (x2 as fiat_secp256k1_i2)) as fiat_secp256k1_u1); } /// The function fiat_secp256k1_mulx_u32 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^32 /// out2 = ⌊arg1 * arg2 / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0xffffffff] #[inline] pub fn fiat_secp256k1_mulx_u32(out1: &mut u32, out2: &mut u32, arg1: u32, arg2: u32) -> () { let x1: u64 = ((arg1 as u64) * (arg2 as u64)); let x2: u32 = ((x1 & (0xffffffff as u64)) as u32); let x3: u32 = ((x1 >> 32) as u32); *out1 = x2; *out2 = x3; } /// The function fiat_secp256k1_cmovznz_u32 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] #[inline] pub fn fiat_secp256k1_cmovznz_u32(out1: &mut u32, arg1: fiat_secp256k1_u1, arg2: u32, arg3: u32) -> () { let x1: fiat_secp256k1_u1 = (!(!arg1)); let x2: u32 = ((((((0x0 as fiat_secp256k1_i2) - (x1 as fiat_secp256k1_i2)) as fiat_secp256k1_i1) as i64) & (0xffffffff as i64)) as u32); let x3: u32 = ((x2 & arg3) | ((!x2) & arg2)); *out1 = x3; } /// The function fiat_secp256k1_mul multiplies two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_mul(out1: &mut [u32; 8], arg1: &[u32; 8], arg2: &[u32; 8]) -> () { let x1: u32 = (arg1[1]); let x2: u32 = (arg1[2]); let x3: u32 = (arg1[3]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[5]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[7]); let x8: u32 = (arg1[0]); let mut x9: u32 = 0; let mut x10: u32 = 0; fiat_secp256k1_mulx_u32(&mut x9, &mut x10, x8, (arg2[7])); let mut x11: u32 = 0; let mut x12: u32 = 0; fiat_secp256k1_mulx_u32(&mut x11, &mut x12, x8, (arg2[6])); let mut x13: u32 = 0; let mut x14: u32 = 0; fiat_secp256k1_mulx_u32(&mut x13, &mut x14, x8, (arg2[5])); let mut x15: u32 = 0; let mut x16: u32 = 0; fiat_secp256k1_mulx_u32(&mut x15, &mut x16, x8, (arg2[4])); let mut x17: u32 = 0; let mut x18: u32 = 0; fiat_secp256k1_mulx_u32(&mut x17, &mut x18, x8, (arg2[3])); let mut x19: u32 = 0; let mut x20: u32 = 0; fiat_secp256k1_mulx_u32(&mut x19, &mut x20, x8, (arg2[2])); let mut x21: u32 = 0; let mut x22: u32 = 0; fiat_secp256k1_mulx_u32(&mut x21, &mut x22, x8, (arg2[1])); let mut x23: u32 = 0; let mut x24: u32 = 0; fiat_secp256k1_mulx_u32(&mut x23, &mut x24, x8, (arg2[0])); let mut x25: u32 = 0; let mut x26: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x25, &mut x26, 0x0, x24, x21); let mut x27: u32 = 0; let mut x28: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x27, &mut x28, x26, x22, x19); let mut x29: u32 = 0; let mut x30: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x29, &mut x30, x28, x20, x17); let mut x31: u32 = 0; let mut x32: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x31, &mut x32, x30, x18, x15); let mut x33: u32 = 0; let mut x34: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x33, &mut x34, x32, x16, x13); let mut x35: u32 = 0; let mut x36: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x35, &mut x36, x34, x14, x11); let mut x37: u32 = 0; let mut x38: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x37, &mut x38, x36, x12, x9); let x39: u32 = ((x38 as u32) + x10); let mut x40: u32 = 0; let mut x41: u32 = 0; fiat_secp256k1_mulx_u32(&mut x40, &mut x41, x23, 0xd2253531); let mut x42: u32 = 0; let mut x43: u32 = 0; fiat_secp256k1_mulx_u32(&mut x42, &mut x43, x40, 0xffffffff); let mut x44: u32 = 0; let mut x45: u32 = 0; fiat_secp256k1_mulx_u32(&mut x44, &mut x45, x40, 0xffffffff); let mut x46: u32 = 0; let mut x47: u32 = 0; fiat_secp256k1_mulx_u32(&mut x46, &mut x47, x40, 0xffffffff); let mut x48: u32 = 0; let mut x49: u32 = 0; fiat_secp256k1_mulx_u32(&mut x48, &mut x49, x40, 0xffffffff); let mut x50: u32 = 0; let mut x51: u32 = 0; fiat_secp256k1_mulx_u32(&mut x50, &mut x51, x40, 0xffffffff); let mut x52: u32 = 0; let mut x53: u32 = 0; fiat_secp256k1_mulx_u32(&mut x52, &mut x53, x40, 0xffffffff); let mut x54: u32 = 0; let mut x55: u32 = 0; fiat_secp256k1_mulx_u32(&mut x54, &mut x55, x40, 0xfffffffe); let mut x56: u32 = 0; let mut x57: u32 = 0; fiat_secp256k1_mulx_u32(&mut x56, &mut x57, x40, 0xfffffc2f); let mut x58: u32 = 0; let mut x59: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x58, &mut x59, 0x0, x57, x54); let mut x60: u32 = 0; let mut x61: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x60, &mut x61, x59, x55, x52); let mut x62: u32 = 0; let mut x63: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x62, &mut x63, x61, x53, x50); let mut x64: u32 = 0; let mut x65: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x64, &mut x65, x63, x51, x48); let mut x66: u32 = 0; let mut x67: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x66, &mut x67, x65, x49, x46); let mut x68: u32 = 0; let mut x69: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x68, &mut x69, x67, x47, x44); let mut x70: u32 = 0; let mut x71: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x70, &mut x71, x69, x45, x42); let x72: u32 = ((x71 as u32) + x43); let mut x73: u32 = 0; let mut x74: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x73, &mut x74, 0x0, x23, x56); let mut x75: u32 = 0; let mut x76: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x75, &mut x76, x74, x25, x58); let mut x77: u32 = 0; let mut x78: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x77, &mut x78, x76, x27, x60); let mut x79: u32 = 0; let mut x80: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x79, &mut x80, x78, x29, x62); let mut x81: u32 = 0; let mut x82: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x81, &mut x82, x80, x31, x64); let mut x83: u32 = 0; let mut x84: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x83, &mut x84, x82, x33, x66); let mut x85: u32 = 0; let mut x86: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x85, &mut x86, x84, x35, x68); let mut x87: u32 = 0; let mut x88: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x87, &mut x88, x86, x37, x70); let mut x89: u32 = 0; let mut x90: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x89, &mut x90, x88, x39, x72); let mut x91: u32 = 0; let mut x92: u32 = 0; fiat_secp256k1_mulx_u32(&mut x91, &mut x92, x1, (arg2[7])); let mut x93: u32 = 0; let mut x94: u32 = 0; fiat_secp256k1_mulx_u32(&mut x93, &mut x94, x1, (arg2[6])); let mut x95: u32 = 0; let mut x96: u32 = 0; fiat_secp256k1_mulx_u32(&mut x95, &mut x96, x1, (arg2[5])); let mut x97: u32 = 0; let mut x98: u32 = 0; fiat_secp256k1_mulx_u32(&mut x97, &mut x98, x1, (arg2[4])); let mut x99: u32 = 0; let mut x100: u32 = 0; fiat_secp256k1_mulx_u32(&mut x99, &mut x100, x1, (arg2[3])); let mut x101: u32 = 0; let mut x102: u32 = 0; fiat_secp256k1_mulx_u32(&mut x101, &mut x102, x1, (arg2[2])); let mut x103: u32 = 0; let mut x104: u32 = 0; fiat_secp256k1_mulx_u32(&mut x103, &mut x104, x1, (arg2[1])); let mut x105: u32 = 0; let mut x106: u32 = 0; fiat_secp256k1_mulx_u32(&mut x105, &mut x106, x1, (arg2[0])); let mut x107: u32 = 0; let mut x108: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x107, &mut x108, 0x0, x106, x103); let mut x109: u32 = 0; let mut x110: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x109, &mut x110, x108, x104, x101); let mut x111: u32 = 0; let mut x112: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x111, &mut x112, x110, x102, x99); let mut x113: u32 = 0; let mut x114: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x113, &mut x114, x112, x100, x97); let mut x115: u32 = 0; let mut x116: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x115, &mut x116, x114, x98, x95); let mut x117: u32 = 0; let mut x118: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x117, &mut x118, x116, x96, x93); let mut x119: u32 = 0; let mut x120: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x119, &mut x120, x118, x94, x91); let x121: u32 = ((x120 as u32) + x92); let mut x122: u32 = 0; let mut x123: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x122, &mut x123, 0x0, x75, x105); let mut x124: u32 = 0; let mut x125: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x124, &mut x125, x123, x77, x107); let mut x126: u32 = 0; let mut x127: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x126, &mut x127, x125, x79, x109); let mut x128: u32 = 0; let mut x129: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x128, &mut x129, x127, x81, x111); let mut x130: u32 = 0; let mut x131: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x130, &mut x131, x129, x83, x113); let mut x132: u32 = 0; let mut x133: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x132, &mut x133, x131, x85, x115); let mut x134: u32 = 0; let mut x135: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x134, &mut x135, x133, x87, x117); let mut x136: u32 = 0; let mut x137: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x136, &mut x137, x135, x89, x119); let mut x138: u32 = 0; let mut x139: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x138, &mut x139, x137, (x90 as u32), x121); let mut x140: u32 = 0; let mut x141: u32 = 0; fiat_secp256k1_mulx_u32(&mut x140, &mut x141, x122, 0xd2253531); let mut x142: u32 = 0; let mut x143: u32 = 0; fiat_secp256k1_mulx_u32(&mut x142, &mut x143, x140, 0xffffffff); let mut x144: u32 = 0; let mut x145: u32 = 0; fiat_secp256k1_mulx_u32(&mut x144, &mut x145, x140, 0xffffffff); let mut x146: u32 = 0; let mut x147: u32 = 0; fiat_secp256k1_mulx_u32(&mut x146, &mut x147, x140, 0xffffffff); let mut x148: u32 = 0; let mut x149: u32 = 0; fiat_secp256k1_mulx_u32(&mut x148, &mut x149, x140, 0xffffffff); let mut x150: u32 = 0; let mut x151: u32 = 0; fiat_secp256k1_mulx_u32(&mut x150, &mut x151, x140, 0xffffffff); let mut x152: u32 = 0; let mut x153: u32 = 0; fiat_secp256k1_mulx_u32(&mut x152, &mut x153, x140, 0xffffffff); let mut x154: u32 = 0; let mut x155: u32 = 0; fiat_secp256k1_mulx_u32(&mut x154, &mut x155, x140, 0xfffffffe); let mut x156: u32 = 0; let mut x157: u32 = 0; fiat_secp256k1_mulx_u32(&mut x156, &mut x157, x140, 0xfffffc2f); let mut x158: u32 = 0; let mut x159: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x158, &mut x159, 0x0, x157, x154); let mut x160: u32 = 0; let mut x161: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x160, &mut x161, x159, x155, x152); let mut x162: u32 = 0; let mut x163: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x162, &mut x163, x161, x153, x150); let mut x164: u32 = 0; let mut x165: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x164, &mut x165, x163, x151, x148); let mut x166: u32 = 0; let mut x167: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x166, &mut x167, x165, x149, x146); let mut x168: u32 = 0; let mut x169: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x168, &mut x169, x167, x147, x144); let mut x170: u32 = 0; let mut x171: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x170, &mut x171, x169, x145, x142); let x172: u32 = ((x171 as u32) + x143); let mut x173: u32 = 0; let mut x174: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x173, &mut x174, 0x0, x122, x156); let mut x175: u32 = 0; let mut x176: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x175, &mut x176, x174, x124, x158); let mut x177: u32 = 0; let mut x178: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x177, &mut x178, x176, x126, x160); let mut x179: u32 = 0; let mut x180: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x179, &mut x180, x178, x128, x162); let mut x181: u32 = 0; let mut x182: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x181, &mut x182, x180, x130, x164); let mut x183: u32 = 0; let mut x184: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x183, &mut x184, x182, x132, x166); let mut x185: u32 = 0; let mut x186: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x185, &mut x186, x184, x134, x168); let mut x187: u32 = 0; let mut x188: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x187, &mut x188, x186, x136, x170); let mut x189: u32 = 0; let mut x190: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x189, &mut x190, x188, x138, x172); let x191: u32 = ((x190 as u32) + (x139 as u32)); let mut x192: u32 = 0; let mut x193: u32 = 0; fiat_secp256k1_mulx_u32(&mut x192, &mut x193, x2, (arg2[7])); let mut x194: u32 = 0; let mut x195: u32 = 0; fiat_secp256k1_mulx_u32(&mut x194, &mut x195, x2, (arg2[6])); let mut x196: u32 = 0; let mut x197: u32 = 0; fiat_secp256k1_mulx_u32(&mut x196, &mut x197, x2, (arg2[5])); let mut x198: u32 = 0; let mut x199: u32 = 0; fiat_secp256k1_mulx_u32(&mut x198, &mut x199, x2, (arg2[4])); let mut x200: u32 = 0; let mut x201: u32 = 0; fiat_secp256k1_mulx_u32(&mut x200, &mut x201, x2, (arg2[3])); let mut x202: u32 = 0; let mut x203: u32 = 0; fiat_secp256k1_mulx_u32(&mut x202, &mut x203, x2, (arg2[2])); let mut x204: u32 = 0; let mut x205: u32 = 0; fiat_secp256k1_mulx_u32(&mut x204, &mut x205, x2, (arg2[1])); let mut x206: u32 = 0; let mut x207: u32 = 0; fiat_secp256k1_mulx_u32(&mut x206, &mut x207, x2, (arg2[0])); let mut x208: u32 = 0; let mut x209: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x208, &mut x209, 0x0, x207, x204); let mut x210: u32 = 0; let mut x211: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x210, &mut x211, x209, x205, x202); let mut x212: u32 = 0; let mut x213: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x212, &mut x213, x211, x203, x200); let mut x214: u32 = 0; let mut x215: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x214, &mut x215, x213, x201, x198); let mut x216: u32 = 0; let mut x217: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x216, &mut x217, x215, x199, x196); let mut x218: u32 = 0; let mut x219: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x218, &mut x219, x217, x197, x194); let mut x220: u32 = 0; let mut x221: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x220, &mut x221, x219, x195, x192); let x222: u32 = ((x221 as u32) + x193); let mut x223: u32 = 0; let mut x224: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x223, &mut x224, 0x0, x175, x206); let mut x225: u32 = 0; let mut x226: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x225, &mut x226, x224, x177, x208); let mut x227: u32 = 0; let mut x228: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x227, &mut x228, x226, x179, x210); let mut x229: u32 = 0; let mut x230: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x229, &mut x230, x228, x181, x212); let mut x231: u32 = 0; let mut x232: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x231, &mut x232, x230, x183, x214); let mut x233: u32 = 0; let mut x234: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x233, &mut x234, x232, x185, x216); let mut x235: u32 = 0; let mut x236: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x235, &mut x236, x234, x187, x218); let mut x237: u32 = 0; let mut x238: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x237, &mut x238, x236, x189, x220); let mut x239: u32 = 0; let mut x240: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x239, &mut x240, x238, x191, x222); let mut x241: u32 = 0; let mut x242: u32 = 0; fiat_secp256k1_mulx_u32(&mut x241, &mut x242, x223, 0xd2253531); let mut x243: u32 = 0; let mut x244: u32 = 0; fiat_secp256k1_mulx_u32(&mut x243, &mut x244, x241, 0xffffffff); let mut x245: u32 = 0; let mut x246: u32 = 0; fiat_secp256k1_mulx_u32(&mut x245, &mut x246, x241, 0xffffffff); let mut x247: u32 = 0; let mut x248: u32 = 0; fiat_secp256k1_mulx_u32(&mut x247, &mut x248, x241, 0xffffffff); let mut x249: u32 = 0; let mut x250: u32 = 0; fiat_secp256k1_mulx_u32(&mut x249, &mut x250, x241, 0xffffffff); let mut x251: u32 = 0; let mut x252: u32 = 0; fiat_secp256k1_mulx_u32(&mut x251, &mut x252, x241, 0xffffffff); let mut x253: u32 = 0; let mut x254: u32 = 0; fiat_secp256k1_mulx_u32(&mut x253, &mut x254, x241, 0xffffffff); let mut x255: u32 = 0; let mut x256: u32 = 0; fiat_secp256k1_mulx_u32(&mut x255, &mut x256, x241, 0xfffffffe); let mut x257: u32 = 0; let mut x258: u32 = 0; fiat_secp256k1_mulx_u32(&mut x257, &mut x258, x241, 0xfffffc2f); let mut x259: u32 = 0; let mut x260: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x259, &mut x260, 0x0, x258, x255); let mut x261: u32 = 0; let mut x262: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x261, &mut x262, x260, x256, x253); let mut x263: u32 = 0; let mut x264: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x263, &mut x264, x262, x254, x251); let mut x265: u32 = 0; let mut x266: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x265, &mut x266, x264, x252, x249); let mut x267: u32 = 0; let mut x268: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x267, &mut x268, x266, x250, x247); let mut x269: u32 = 0; let mut x270: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x269, &mut x270, x268, x248, x245); let mut x271: u32 = 0; let mut x272: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x271, &mut x272, x270, x246, x243); let x273: u32 = ((x272 as u32) + x244); let mut x274: u32 = 0; let mut x275: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x274, &mut x275, 0x0, x223, x257); let mut x276: u32 = 0; let mut x277: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x276, &mut x277, x275, x225, x259); let mut x278: u32 = 0; let mut x279: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x278, &mut x279, x277, x227, x261); let mut x280: u32 = 0; let mut x281: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x280, &mut x281, x279, x229, x263); let mut x282: u32 = 0; let mut x283: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x282, &mut x283, x281, x231, x265); let mut x284: u32 = 0; let mut x285: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x284, &mut x285, x283, x233, x267); let mut x286: u32 = 0; let mut x287: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x286, &mut x287, x285, x235, x269); let mut x288: u32 = 0; let mut x289: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x288, &mut x289, x287, x237, x271); let mut x290: u32 = 0; let mut x291: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x290, &mut x291, x289, x239, x273); let x292: u32 = ((x291 as u32) + (x240 as u32)); let mut x293: u32 = 0; let mut x294: u32 = 0; fiat_secp256k1_mulx_u32(&mut x293, &mut x294, x3, (arg2[7])); let mut x295: u32 = 0; let mut x296: u32 = 0; fiat_secp256k1_mulx_u32(&mut x295, &mut x296, x3, (arg2[6])); let mut x297: u32 = 0; let mut x298: u32 = 0; fiat_secp256k1_mulx_u32(&mut x297, &mut x298, x3, (arg2[5])); let mut x299: u32 = 0; let mut x300: u32 = 0; fiat_secp256k1_mulx_u32(&mut x299, &mut x300, x3, (arg2[4])); let mut x301: u32 = 0; let mut x302: u32 = 0; fiat_secp256k1_mulx_u32(&mut x301, &mut x302, x3, (arg2[3])); let mut x303: u32 = 0; let mut x304: u32 = 0; fiat_secp256k1_mulx_u32(&mut x303, &mut x304, x3, (arg2[2])); let mut x305: u32 = 0; let mut x306: u32 = 0; fiat_secp256k1_mulx_u32(&mut x305, &mut x306, x3, (arg2[1])); let mut x307: u32 = 0; let mut x308: u32 = 0; fiat_secp256k1_mulx_u32(&mut x307, &mut x308, x3, (arg2[0])); let mut x309: u32 = 0; let mut x310: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x309, &mut x310, 0x0, x308, x305); let mut x311: u32 = 0; let mut x312: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x311, &mut x312, x310, x306, x303); let mut x313: u32 = 0; let mut x314: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x313, &mut x314, x312, x304, x301); let mut x315: u32 = 0; let mut x316: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x315, &mut x316, x314, x302, x299); let mut x317: u32 = 0; let mut x318: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x317, &mut x318, x316, x300, x297); let mut x319: u32 = 0; let mut x320: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x319, &mut x320, x318, x298, x295); let mut x321: u32 = 0; let mut x322: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x321, &mut x322, x320, x296, x293); let x323: u32 = ((x322 as u32) + x294); let mut x324: u32 = 0; let mut x325: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x324, &mut x325, 0x0, x276, x307); let mut x326: u32 = 0; let mut x327: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x326, &mut x327, x325, x278, x309); let mut x328: u32 = 0; let mut x329: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x328, &mut x329, x327, x280, x311); let mut x330: u32 = 0; let mut x331: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x330, &mut x331, x329, x282, x313); let mut x332: u32 = 0; let mut x333: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x332, &mut x333, x331, x284, x315); let mut x334: u32 = 0; let mut x335: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x334, &mut x335, x333, x286, x317); let mut x336: u32 = 0; let mut x337: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x336, &mut x337, x335, x288, x319); let mut x338: u32 = 0; let mut x339: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x338, &mut x339, x337, x290, x321); let mut x340: u32 = 0; let mut x341: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x340, &mut x341, x339, x292, x323); let mut x342: u32 = 0; let mut x343: u32 = 0; fiat_secp256k1_mulx_u32(&mut x342, &mut x343, x324, 0xd2253531); let mut x344: u32 = 0; let mut x345: u32 = 0; fiat_secp256k1_mulx_u32(&mut x344, &mut x345, x342, 0xffffffff); let mut x346: u32 = 0; let mut x347: u32 = 0; fiat_secp256k1_mulx_u32(&mut x346, &mut x347, x342, 0xffffffff); let mut x348: u32 = 0; let mut x349: u32 = 0; fiat_secp256k1_mulx_u32(&mut x348, &mut x349, x342, 0xffffffff); let mut x350: u32 = 0; let mut x351: u32 = 0; fiat_secp256k1_mulx_u32(&mut x350, &mut x351, x342, 0xffffffff); let mut x352: u32 = 0; let mut x353: u32 = 0; fiat_secp256k1_mulx_u32(&mut x352, &mut x353, x342, 0xffffffff); let mut x354: u32 = 0; let mut x355: u32 = 0; fiat_secp256k1_mulx_u32(&mut x354, &mut x355, x342, 0xffffffff); let mut x356: u32 = 0; let mut x357: u32 = 0; fiat_secp256k1_mulx_u32(&mut x356, &mut x357, x342, 0xfffffffe); let mut x358: u32 = 0; let mut x359: u32 = 0; fiat_secp256k1_mulx_u32(&mut x358, &mut x359, x342, 0xfffffc2f); let mut x360: u32 = 0; let mut x361: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x360, &mut x361, 0x0, x359, x356); let mut x362: u32 = 0; let mut x363: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x362, &mut x363, x361, x357, x354); let mut x364: u32 = 0; let mut x365: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x364, &mut x365, x363, x355, x352); let mut x366: u32 = 0; let mut x367: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x366, &mut x367, x365, x353, x350); let mut x368: u32 = 0; let mut x369: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x368, &mut x369, x367, x351, x348); let mut x370: u32 = 0; let mut x371: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x370, &mut x371, x369, x349, x346); let mut x372: u32 = 0; let mut x373: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x372, &mut x373, x371, x347, x344); let x374: u32 = ((x373 as u32) + x345); let mut x375: u32 = 0; let mut x376: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x375, &mut x376, 0x0, x324, x358); let mut x377: u32 = 0; let mut x378: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x377, &mut x378, x376, x326, x360); let mut x379: u32 = 0; let mut x380: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x379, &mut x380, x378, x328, x362); let mut x381: u32 = 0; let mut x382: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x381, &mut x382, x380, x330, x364); let mut x383: u32 = 0; let mut x384: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x383, &mut x384, x382, x332, x366); let mut x385: u32 = 0; let mut x386: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x385, &mut x386, x384, x334, x368); let mut x387: u32 = 0; let mut x388: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x387, &mut x388, x386, x336, x370); let mut x389: u32 = 0; let mut x390: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x389, &mut x390, x388, x338, x372); let mut x391: u32 = 0; let mut x392: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x391, &mut x392, x390, x340, x374); let x393: u32 = ((x392 as u32) + (x341 as u32)); let mut x394: u32 = 0; let mut x395: u32 = 0; fiat_secp256k1_mulx_u32(&mut x394, &mut x395, x4, (arg2[7])); let mut x396: u32 = 0; let mut x397: u32 = 0; fiat_secp256k1_mulx_u32(&mut x396, &mut x397, x4, (arg2[6])); let mut x398: u32 = 0; let mut x399: u32 = 0; fiat_secp256k1_mulx_u32(&mut x398, &mut x399, x4, (arg2[5])); let mut x400: u32 = 0; let mut x401: u32 = 0; fiat_secp256k1_mulx_u32(&mut x400, &mut x401, x4, (arg2[4])); let mut x402: u32 = 0; let mut x403: u32 = 0; fiat_secp256k1_mulx_u32(&mut x402, &mut x403, x4, (arg2[3])); let mut x404: u32 = 0; let mut x405: u32 = 0; fiat_secp256k1_mulx_u32(&mut x404, &mut x405, x4, (arg2[2])); let mut x406: u32 = 0; let mut x407: u32 = 0; fiat_secp256k1_mulx_u32(&mut x406, &mut x407, x4, (arg2[1])); let mut x408: u32 = 0; let mut x409: u32 = 0; fiat_secp256k1_mulx_u32(&mut x408, &mut x409, x4, (arg2[0])); let mut x410: u32 = 0; let mut x411: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x410, &mut x411, 0x0, x409, x406); let mut x412: u32 = 0; let mut x413: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x412, &mut x413, x411, x407, x404); let mut x414: u32 = 0; let mut x415: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x414, &mut x415, x413, x405, x402); let mut x416: u32 = 0; let mut x417: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x416, &mut x417, x415, x403, x400); let mut x418: u32 = 0; let mut x419: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x418, &mut x419, x417, x401, x398); let mut x420: u32 = 0; let mut x421: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x420, &mut x421, x419, x399, x396); let mut x422: u32 = 0; let mut x423: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x422, &mut x423, x421, x397, x394); let x424: u32 = ((x423 as u32) + x395); let mut x425: u32 = 0; let mut x426: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x425, &mut x426, 0x0, x377, x408); let mut x427: u32 = 0; let mut x428: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x427, &mut x428, x426, x379, x410); let mut x429: u32 = 0; let mut x430: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x429, &mut x430, x428, x381, x412); let mut x431: u32 = 0; let mut x432: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x431, &mut x432, x430, x383, x414); let mut x433: u32 = 0; let mut x434: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x433, &mut x434, x432, x385, x416); let mut x435: u32 = 0; let mut x436: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x435, &mut x436, x434, x387, x418); let mut x437: u32 = 0; let mut x438: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x437, &mut x438, x436, x389, x420); let mut x439: u32 = 0; let mut x440: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x439, &mut x440, x438, x391, x422); let mut x441: u32 = 0; let mut x442: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x441, &mut x442, x440, x393, x424); let mut x443: u32 = 0; let mut x444: u32 = 0; fiat_secp256k1_mulx_u32(&mut x443, &mut x444, x425, 0xd2253531); let mut x445: u32 = 0; let mut x446: u32 = 0; fiat_secp256k1_mulx_u32(&mut x445, &mut x446, x443, 0xffffffff); let mut x447: u32 = 0; let mut x448: u32 = 0; fiat_secp256k1_mulx_u32(&mut x447, &mut x448, x443, 0xffffffff); let mut x449: u32 = 0; let mut x450: u32 = 0; fiat_secp256k1_mulx_u32(&mut x449, &mut x450, x443, 0xffffffff); let mut x451: u32 = 0; let mut x452: u32 = 0; fiat_secp256k1_mulx_u32(&mut x451, &mut x452, x443, 0xffffffff); let mut x453: u32 = 0; let mut x454: u32 = 0; fiat_secp256k1_mulx_u32(&mut x453, &mut x454, x443, 0xffffffff); let mut x455: u32 = 0; let mut x456: u32 = 0; fiat_secp256k1_mulx_u32(&mut x455, &mut x456, x443, 0xffffffff); let mut x457: u32 = 0; let mut x458: u32 = 0; fiat_secp256k1_mulx_u32(&mut x457, &mut x458, x443, 0xfffffffe); let mut x459: u32 = 0; let mut x460: u32 = 0; fiat_secp256k1_mulx_u32(&mut x459, &mut x460, x443, 0xfffffc2f); let mut x461: u32 = 0; let mut x462: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x461, &mut x462, 0x0, x460, x457); let mut x463: u32 = 0; let mut x464: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x463, &mut x464, x462, x458, x455); let mut x465: u32 = 0; let mut x466: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x465, &mut x466, x464, x456, x453); let mut x467: u32 = 0; let mut x468: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x467, &mut x468, x466, x454, x451); let mut x469: u32 = 0; let mut x470: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x469, &mut x470, x468, x452, x449); let mut x471: u32 = 0; let mut x472: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x471, &mut x472, x470, x450, x447); let mut x473: u32 = 0; let mut x474: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x473, &mut x474, x472, x448, x445); let x475: u32 = ((x474 as u32) + x446); let mut x476: u32 = 0; let mut x477: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x476, &mut x477, 0x0, x425, x459); let mut x478: u32 = 0; let mut x479: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x478, &mut x479, x477, x427, x461); let mut x480: u32 = 0; let mut x481: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x480, &mut x481, x479, x429, x463); let mut x482: u32 = 0; let mut x483: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x482, &mut x483, x481, x431, x465); let mut x484: u32 = 0; let mut x485: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x484, &mut x485, x483, x433, x467); let mut x486: u32 = 0; let mut x487: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x486, &mut x487, x485, x435, x469); let mut x488: u32 = 0; let mut x489: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x488, &mut x489, x487, x437, x471); let mut x490: u32 = 0; let mut x491: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x490, &mut x491, x489, x439, x473); let mut x492: u32 = 0; let mut x493: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x492, &mut x493, x491, x441, x475); let x494: u32 = ((x493 as u32) + (x442 as u32)); let mut x495: u32 = 0; let mut x496: u32 = 0; fiat_secp256k1_mulx_u32(&mut x495, &mut x496, x5, (arg2[7])); let mut x497: u32 = 0; let mut x498: u32 = 0; fiat_secp256k1_mulx_u32(&mut x497, &mut x498, x5, (arg2[6])); let mut x499: u32 = 0; let mut x500: u32 = 0; fiat_secp256k1_mulx_u32(&mut x499, &mut x500, x5, (arg2[5])); let mut x501: u32 = 0; let mut x502: u32 = 0; fiat_secp256k1_mulx_u32(&mut x501, &mut x502, x5, (arg2[4])); let mut x503: u32 = 0; let mut x504: u32 = 0; fiat_secp256k1_mulx_u32(&mut x503, &mut x504, x5, (arg2[3])); let mut x505: u32 = 0; let mut x506: u32 = 0; fiat_secp256k1_mulx_u32(&mut x505, &mut x506, x5, (arg2[2])); let mut x507: u32 = 0; let mut x508: u32 = 0; fiat_secp256k1_mulx_u32(&mut x507, &mut x508, x5, (arg2[1])); let mut x509: u32 = 0; let mut x510: u32 = 0; fiat_secp256k1_mulx_u32(&mut x509, &mut x510, x5, (arg2[0])); let mut x511: u32 = 0; let mut x512: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x511, &mut x512, 0x0, x510, x507); let mut x513: u32 = 0; let mut x514: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x513, &mut x514, x512, x508, x505); let mut x515: u32 = 0; let mut x516: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x515, &mut x516, x514, x506, x503); let mut x517: u32 = 0; let mut x518: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x517, &mut x518, x516, x504, x501); let mut x519: u32 = 0; let mut x520: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x519, &mut x520, x518, x502, x499); let mut x521: u32 = 0; let mut x522: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x521, &mut x522, x520, x500, x497); let mut x523: u32 = 0; let mut x524: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x523, &mut x524, x522, x498, x495); let x525: u32 = ((x524 as u32) + x496); let mut x526: u32 = 0; let mut x527: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x526, &mut x527, 0x0, x478, x509); let mut x528: u32 = 0; let mut x529: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x528, &mut x529, x527, x480, x511); let mut x530: u32 = 0; let mut x531: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x530, &mut x531, x529, x482, x513); let mut x532: u32 = 0; let mut x533: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x532, &mut x533, x531, x484, x515); let mut x534: u32 = 0; let mut x535: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x534, &mut x535, x533, x486, x517); let mut x536: u32 = 0; let mut x537: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x536, &mut x537, x535, x488, x519); let mut x538: u32 = 0; let mut x539: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x538, &mut x539, x537, x490, x521); let mut x540: u32 = 0; let mut x541: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x540, &mut x541, x539, x492, x523); let mut x542: u32 = 0; let mut x543: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x542, &mut x543, x541, x494, x525); let mut x544: u32 = 0; let mut x545: u32 = 0; fiat_secp256k1_mulx_u32(&mut x544, &mut x545, x526, 0xd2253531); let mut x546: u32 = 0; let mut x547: u32 = 0; fiat_secp256k1_mulx_u32(&mut x546, &mut x547, x544, 0xffffffff); let mut x548: u32 = 0; let mut x549: u32 = 0; fiat_secp256k1_mulx_u32(&mut x548, &mut x549, x544, 0xffffffff); let mut x550: u32 = 0; let mut x551: u32 = 0; fiat_secp256k1_mulx_u32(&mut x550, &mut x551, x544, 0xffffffff); let mut x552: u32 = 0; let mut x553: u32 = 0; fiat_secp256k1_mulx_u32(&mut x552, &mut x553, x544, 0xffffffff); let mut x554: u32 = 0; let mut x555: u32 = 0; fiat_secp256k1_mulx_u32(&mut x554, &mut x555, x544, 0xffffffff); let mut x556: u32 = 0; let mut x557: u32 = 0; fiat_secp256k1_mulx_u32(&mut x556, &mut x557, x544, 0xffffffff); let mut x558: u32 = 0; let mut x559: u32 = 0; fiat_secp256k1_mulx_u32(&mut x558, &mut x559, x544, 0xfffffffe); let mut x560: u32 = 0; let mut x561: u32 = 0; fiat_secp256k1_mulx_u32(&mut x560, &mut x561, x544, 0xfffffc2f); let mut x562: u32 = 0; let mut x563: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x562, &mut x563, 0x0, x561, x558); let mut x564: u32 = 0; let mut x565: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x564, &mut x565, x563, x559, x556); let mut x566: u32 = 0; let mut x567: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x566, &mut x567, x565, x557, x554); let mut x568: u32 = 0; let mut x569: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x568, &mut x569, x567, x555, x552); let mut x570: u32 = 0; let mut x571: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x570, &mut x571, x569, x553, x550); let mut x572: u32 = 0; let mut x573: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x572, &mut x573, x571, x551, x548); let mut x574: u32 = 0; let mut x575: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x574, &mut x575, x573, x549, x546); let x576: u32 = ((x575 as u32) + x547); let mut x577: u32 = 0; let mut x578: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x577, &mut x578, 0x0, x526, x560); let mut x579: u32 = 0; let mut x580: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x579, &mut x580, x578, x528, x562); let mut x581: u32 = 0; let mut x582: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x581, &mut x582, x580, x530, x564); let mut x583: u32 = 0; let mut x584: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x583, &mut x584, x582, x532, x566); let mut x585: u32 = 0; let mut x586: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x585, &mut x586, x584, x534, x568); let mut x587: u32 = 0; let mut x588: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x587, &mut x588, x586, x536, x570); let mut x589: u32 = 0; let mut x590: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x589, &mut x590, x588, x538, x572); let mut x591: u32 = 0; let mut x592: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x591, &mut x592, x590, x540, x574); let mut x593: u32 = 0; let mut x594: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x593, &mut x594, x592, x542, x576); let x595: u32 = ((x594 as u32) + (x543 as u32)); let mut x596: u32 = 0; let mut x597: u32 = 0; fiat_secp256k1_mulx_u32(&mut x596, &mut x597, x6, (arg2[7])); let mut x598: u32 = 0; let mut x599: u32 = 0; fiat_secp256k1_mulx_u32(&mut x598, &mut x599, x6, (arg2[6])); let mut x600: u32 = 0; let mut x601: u32 = 0; fiat_secp256k1_mulx_u32(&mut x600, &mut x601, x6, (arg2[5])); let mut x602: u32 = 0; let mut x603: u32 = 0; fiat_secp256k1_mulx_u32(&mut x602, &mut x603, x6, (arg2[4])); let mut x604: u32 = 0; let mut x605: u32 = 0; fiat_secp256k1_mulx_u32(&mut x604, &mut x605, x6, (arg2[3])); let mut x606: u32 = 0; let mut x607: u32 = 0; fiat_secp256k1_mulx_u32(&mut x606, &mut x607, x6, (arg2[2])); let mut x608: u32 = 0; let mut x609: u32 = 0; fiat_secp256k1_mulx_u32(&mut x608, &mut x609, x6, (arg2[1])); let mut x610: u32 = 0; let mut x611: u32 = 0; fiat_secp256k1_mulx_u32(&mut x610, &mut x611, x6, (arg2[0])); let mut x612: u32 = 0; let mut x613: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x612, &mut x613, 0x0, x611, x608); let mut x614: u32 = 0; let mut x615: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x614, &mut x615, x613, x609, x606); let mut x616: u32 = 0; let mut x617: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x616, &mut x617, x615, x607, x604); let mut x618: u32 = 0; let mut x619: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x618, &mut x619, x617, x605, x602); let mut x620: u32 = 0; let mut x621: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x620, &mut x621, x619, x603, x600); let mut x622: u32 = 0; let mut x623: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x622, &mut x623, x621, x601, x598); let mut x624: u32 = 0; let mut x625: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x624, &mut x625, x623, x599, x596); let x626: u32 = ((x625 as u32) + x597); let mut x627: u32 = 0; let mut x628: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x627, &mut x628, 0x0, x579, x610); let mut x629: u32 = 0; let mut x630: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x629, &mut x630, x628, x581, x612); let mut x631: u32 = 0; let mut x632: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x631, &mut x632, x630, x583, x614); let mut x633: u32 = 0; let mut x634: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x633, &mut x634, x632, x585, x616); let mut x635: u32 = 0; let mut x636: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x635, &mut x636, x634, x587, x618); let mut x637: u32 = 0; let mut x638: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x637, &mut x638, x636, x589, x620); let mut x639: u32 = 0; let mut x640: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x639, &mut x640, x638, x591, x622); let mut x641: u32 = 0; let mut x642: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x641, &mut x642, x640, x593, x624); let mut x643: u32 = 0; let mut x644: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x643, &mut x644, x642, x595, x626); let mut x645: u32 = 0; let mut x646: u32 = 0; fiat_secp256k1_mulx_u32(&mut x645, &mut x646, x627, 0xd2253531); let mut x647: u32 = 0; let mut x648: u32 = 0; fiat_secp256k1_mulx_u32(&mut x647, &mut x648, x645, 0xffffffff); let mut x649: u32 = 0; let mut x650: u32 = 0; fiat_secp256k1_mulx_u32(&mut x649, &mut x650, x645, 0xffffffff); let mut x651: u32 = 0; let mut x652: u32 = 0; fiat_secp256k1_mulx_u32(&mut x651, &mut x652, x645, 0xffffffff); let mut x653: u32 = 0; let mut x654: u32 = 0; fiat_secp256k1_mulx_u32(&mut x653, &mut x654, x645, 0xffffffff); let mut x655: u32 = 0; let mut x656: u32 = 0; fiat_secp256k1_mulx_u32(&mut x655, &mut x656, x645, 0xffffffff); let mut x657: u32 = 0; let mut x658: u32 = 0; fiat_secp256k1_mulx_u32(&mut x657, &mut x658, x645, 0xffffffff); let mut x659: u32 = 0; let mut x660: u32 = 0; fiat_secp256k1_mulx_u32(&mut x659, &mut x660, x645, 0xfffffffe); let mut x661: u32 = 0; let mut x662: u32 = 0; fiat_secp256k1_mulx_u32(&mut x661, &mut x662, x645, 0xfffffc2f); let mut x663: u32 = 0; let mut x664: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x663, &mut x664, 0x0, x662, x659); let mut x665: u32 = 0; let mut x666: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x665, &mut x666, x664, x660, x657); let mut x667: u32 = 0; let mut x668: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x667, &mut x668, x666, x658, x655); let mut x669: u32 = 0; let mut x670: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x669, &mut x670, x668, x656, x653); let mut x671: u32 = 0; let mut x672: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x671, &mut x672, x670, x654, x651); let mut x673: u32 = 0; let mut x674: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x673, &mut x674, x672, x652, x649); let mut x675: u32 = 0; let mut x676: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x675, &mut x676, x674, x650, x647); let x677: u32 = ((x676 as u32) + x648); let mut x678: u32 = 0; let mut x679: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x678, &mut x679, 0x0, x627, x661); let mut x680: u32 = 0; let mut x681: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x680, &mut x681, x679, x629, x663); let mut x682: u32 = 0; let mut x683: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x682, &mut x683, x681, x631, x665); let mut x684: u32 = 0; let mut x685: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x684, &mut x685, x683, x633, x667); let mut x686: u32 = 0; let mut x687: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x686, &mut x687, x685, x635, x669); let mut x688: u32 = 0; let mut x689: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x688, &mut x689, x687, x637, x671); let mut x690: u32 = 0; let mut x691: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x690, &mut x691, x689, x639, x673); let mut x692: u32 = 0; let mut x693: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x692, &mut x693, x691, x641, x675); let mut x694: u32 = 0; let mut x695: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x694, &mut x695, x693, x643, x677); let x696: u32 = ((x695 as u32) + (x644 as u32)); let mut x697: u32 = 0; let mut x698: u32 = 0; fiat_secp256k1_mulx_u32(&mut x697, &mut x698, x7, (arg2[7])); let mut x699: u32 = 0; let mut x700: u32 = 0; fiat_secp256k1_mulx_u32(&mut x699, &mut x700, x7, (arg2[6])); let mut x701: u32 = 0; let mut x702: u32 = 0; fiat_secp256k1_mulx_u32(&mut x701, &mut x702, x7, (arg2[5])); let mut x703: u32 = 0; let mut x704: u32 = 0; fiat_secp256k1_mulx_u32(&mut x703, &mut x704, x7, (arg2[4])); let mut x705: u32 = 0; let mut x706: u32 = 0; fiat_secp256k1_mulx_u32(&mut x705, &mut x706, x7, (arg2[3])); let mut x707: u32 = 0; let mut x708: u32 = 0; fiat_secp256k1_mulx_u32(&mut x707, &mut x708, x7, (arg2[2])); let mut x709: u32 = 0; let mut x710: u32 = 0; fiat_secp256k1_mulx_u32(&mut x709, &mut x710, x7, (arg2[1])); let mut x711: u32 = 0; let mut x712: u32 = 0; fiat_secp256k1_mulx_u32(&mut x711, &mut x712, x7, (arg2[0])); let mut x713: u32 = 0; let mut x714: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x713, &mut x714, 0x0, x712, x709); let mut x715: u32 = 0; let mut x716: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x715, &mut x716, x714, x710, x707); let mut x717: u32 = 0; let mut x718: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x717, &mut x718, x716, x708, x705); let mut x719: u32 = 0; let mut x720: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x719, &mut x720, x718, x706, x703); let mut x721: u32 = 0; let mut x722: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x721, &mut x722, x720, x704, x701); let mut x723: u32 = 0; let mut x724: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x723, &mut x724, x722, x702, x699); let mut x725: u32 = 0; let mut x726: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x725, &mut x726, x724, x700, x697); let x727: u32 = ((x726 as u32) + x698); let mut x728: u32 = 0; let mut x729: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x728, &mut x729, 0x0, x680, x711); let mut x730: u32 = 0; let mut x731: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x730, &mut x731, x729, x682, x713); let mut x732: u32 = 0; let mut x733: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x732, &mut x733, x731, x684, x715); let mut x734: u32 = 0; let mut x735: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x734, &mut x735, x733, x686, x717); let mut x736: u32 = 0; let mut x737: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x736, &mut x737, x735, x688, x719); let mut x738: u32 = 0; let mut x739: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x738, &mut x739, x737, x690, x721); let mut x740: u32 = 0; let mut x741: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x740, &mut x741, x739, x692, x723); let mut x742: u32 = 0; let mut x743: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x742, &mut x743, x741, x694, x725); let mut x744: u32 = 0; let mut x745: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x744, &mut x745, x743, x696, x727); let mut x746: u32 = 0; let mut x747: u32 = 0; fiat_secp256k1_mulx_u32(&mut x746, &mut x747, x728, 0xd2253531); let mut x748: u32 = 0; let mut x749: u32 = 0; fiat_secp256k1_mulx_u32(&mut x748, &mut x749, x746, 0xffffffff); let mut x750: u32 = 0; let mut x751: u32 = 0; fiat_secp256k1_mulx_u32(&mut x750, &mut x751, x746, 0xffffffff); let mut x752: u32 = 0; let mut x753: u32 = 0; fiat_secp256k1_mulx_u32(&mut x752, &mut x753, x746, 0xffffffff); let mut x754: u32 = 0; let mut x755: u32 = 0; fiat_secp256k1_mulx_u32(&mut x754, &mut x755, x746, 0xffffffff); let mut x756: u32 = 0; let mut x757: u32 = 0; fiat_secp256k1_mulx_u32(&mut x756, &mut x757, x746, 0xffffffff); let mut x758: u32 = 0; let mut x759: u32 = 0; fiat_secp256k1_mulx_u32(&mut x758, &mut x759, x746, 0xffffffff); let mut x760: u32 = 0; let mut x761: u32 = 0; fiat_secp256k1_mulx_u32(&mut x760, &mut x761, x746, 0xfffffffe); let mut x762: u32 = 0; let mut x763: u32 = 0; fiat_secp256k1_mulx_u32(&mut x762, &mut x763, x746, 0xfffffc2f); let mut x764: u32 = 0; let mut x765: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x764, &mut x765, 0x0, x763, x760); let mut x766: u32 = 0; let mut x767: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x766, &mut x767, x765, x761, x758); let mut x768: u32 = 0; let mut x769: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x768, &mut x769, x767, x759, x756); let mut x770: u32 = 0; let mut x771: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x770, &mut x771, x769, x757, x754); let mut x772: u32 = 0; let mut x773: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x772, &mut x773, x771, x755, x752); let mut x774: u32 = 0; let mut x775: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x774, &mut x775, x773, x753, x750); let mut x776: u32 = 0; let mut x777: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x776, &mut x777, x775, x751, x748); let x778: u32 = ((x777 as u32) + x749); let mut x779: u32 = 0; let mut x780: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x779, &mut x780, 0x0, x728, x762); let mut x781: u32 = 0; let mut x782: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x781, &mut x782, x780, x730, x764); let mut x783: u32 = 0; let mut x784: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x783, &mut x784, x782, x732, x766); let mut x785: u32 = 0; let mut x786: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x785, &mut x786, x784, x734, x768); let mut x787: u32 = 0; let mut x788: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x787, &mut x788, x786, x736, x770); let mut x789: u32 = 0; let mut x790: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x789, &mut x790, x788, x738, x772); let mut x791: u32 = 0; let mut x792: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x791, &mut x792, x790, x740, x774); let mut x793: u32 = 0; let mut x794: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x793, &mut x794, x792, x742, x776); let mut x795: u32 = 0; let mut x796: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x795, &mut x796, x794, x744, x778); let x797: u32 = ((x796 as u32) + (x745 as u32)); let mut x798: u32 = 0; let mut x799: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x798, &mut x799, 0x0, x781, 0xfffffc2f); let mut x800: u32 = 0; let mut x801: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x800, &mut x801, x799, x783, 0xfffffffe); let mut x802: u32 = 0; let mut x803: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x802, &mut x803, x801, x785, 0xffffffff); let mut x804: u32 = 0; let mut x805: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x804, &mut x805, x803, x787, 0xffffffff); let mut x806: u32 = 0; let mut x807: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x806, &mut x807, x805, x789, 0xffffffff); let mut x808: u32 = 0; let mut x809: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x808, &mut x809, x807, x791, 0xffffffff); let mut x810: u32 = 0; let mut x811: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x810, &mut x811, x809, x793, 0xffffffff); let mut x812: u32 = 0; let mut x813: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x812, &mut x813, x811, x795, 0xffffffff); let mut x814: u32 = 0; let mut x815: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x814, &mut x815, x813, x797, (0x0 as u32)); let mut x816: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x816, x815, x798, x781); let mut x817: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x817, x815, x800, x783); let mut x818: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x818, x815, x802, x785); let mut x819: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x819, x815, x804, x787); let mut x820: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x820, x815, x806, x789); let mut x821: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x821, x815, x808, x791); let mut x822: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x822, x815, x810, x793); let mut x823: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x823, x815, x812, x795); out1[0] = x816; out1[1] = x817; out1[2] = x818; out1[3] = x819; out1[4] = x820; out1[5] = x821; out1[6] = x822; out1[7] = x823; } /// The function fiat_secp256k1_square squares a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_square(out1: &mut [u32; 8], arg1: &[u32; 8]) -> () { let x1: u32 = (arg1[1]); let x2: u32 = (arg1[2]); let x3: u32 = (arg1[3]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[5]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[7]); let x8: u32 = (arg1[0]); let mut x9: u32 = 0; let mut x10: u32 = 0; fiat_secp256k1_mulx_u32(&mut x9, &mut x10, x8, (arg1[7])); let mut x11: u32 = 0; let mut x12: u32 = 0; fiat_secp256k1_mulx_u32(&mut x11, &mut x12, x8, (arg1[6])); let mut x13: u32 = 0; let mut x14: u32 = 0; fiat_secp256k1_mulx_u32(&mut x13, &mut x14, x8, (arg1[5])); let mut x15: u32 = 0; let mut x16: u32 = 0; fiat_secp256k1_mulx_u32(&mut x15, &mut x16, x8, (arg1[4])); let mut x17: u32 = 0; let mut x18: u32 = 0; fiat_secp256k1_mulx_u32(&mut x17, &mut x18, x8, (arg1[3])); let mut x19: u32 = 0; let mut x20: u32 = 0; fiat_secp256k1_mulx_u32(&mut x19, &mut x20, x8, (arg1[2])); let mut x21: u32 = 0; let mut x22: u32 = 0; fiat_secp256k1_mulx_u32(&mut x21, &mut x22, x8, (arg1[1])); let mut x23: u32 = 0; let mut x24: u32 = 0; fiat_secp256k1_mulx_u32(&mut x23, &mut x24, x8, (arg1[0])); let mut x25: u32 = 0; let mut x26: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x25, &mut x26, 0x0, x24, x21); let mut x27: u32 = 0; let mut x28: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x27, &mut x28, x26, x22, x19); let mut x29: u32 = 0; let mut x30: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x29, &mut x30, x28, x20, x17); let mut x31: u32 = 0; let mut x32: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x31, &mut x32, x30, x18, x15); let mut x33: u32 = 0; let mut x34: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x33, &mut x34, x32, x16, x13); let mut x35: u32 = 0; let mut x36: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x35, &mut x36, x34, x14, x11); let mut x37: u32 = 0; let mut x38: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x37, &mut x38, x36, x12, x9); let x39: u32 = ((x38 as u32) + x10); let mut x40: u32 = 0; let mut x41: u32 = 0; fiat_secp256k1_mulx_u32(&mut x40, &mut x41, x23, 0xd2253531); let mut x42: u32 = 0; let mut x43: u32 = 0; fiat_secp256k1_mulx_u32(&mut x42, &mut x43, x40, 0xffffffff); let mut x44: u32 = 0; let mut x45: u32 = 0; fiat_secp256k1_mulx_u32(&mut x44, &mut x45, x40, 0xffffffff); let mut x46: u32 = 0; let mut x47: u32 = 0; fiat_secp256k1_mulx_u32(&mut x46, &mut x47, x40, 0xffffffff); let mut x48: u32 = 0; let mut x49: u32 = 0; fiat_secp256k1_mulx_u32(&mut x48, &mut x49, x40, 0xffffffff); let mut x50: u32 = 0; let mut x51: u32 = 0; fiat_secp256k1_mulx_u32(&mut x50, &mut x51, x40, 0xffffffff); let mut x52: u32 = 0; let mut x53: u32 = 0; fiat_secp256k1_mulx_u32(&mut x52, &mut x53, x40, 0xffffffff); let mut x54: u32 = 0; let mut x55: u32 = 0; fiat_secp256k1_mulx_u32(&mut x54, &mut x55, x40, 0xfffffffe); let mut x56: u32 = 0; let mut x57: u32 = 0; fiat_secp256k1_mulx_u32(&mut x56, &mut x57, x40, 0xfffffc2f); let mut x58: u32 = 0; let mut x59: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x58, &mut x59, 0x0, x57, x54); let mut x60: u32 = 0; let mut x61: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x60, &mut x61, x59, x55, x52); let mut x62: u32 = 0; let mut x63: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x62, &mut x63, x61, x53, x50); let mut x64: u32 = 0; let mut x65: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x64, &mut x65, x63, x51, x48); let mut x66: u32 = 0; let mut x67: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x66, &mut x67, x65, x49, x46); let mut x68: u32 = 0; let mut x69: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x68, &mut x69, x67, x47, x44); let mut x70: u32 = 0; let mut x71: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x70, &mut x71, x69, x45, x42); let x72: u32 = ((x71 as u32) + x43); let mut x73: u32 = 0; let mut x74: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x73, &mut x74, 0x0, x23, x56); let mut x75: u32 = 0; let mut x76: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x75, &mut x76, x74, x25, x58); let mut x77: u32 = 0; let mut x78: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x77, &mut x78, x76, x27, x60); let mut x79: u32 = 0; let mut x80: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x79, &mut x80, x78, x29, x62); let mut x81: u32 = 0; let mut x82: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x81, &mut x82, x80, x31, x64); let mut x83: u32 = 0; let mut x84: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x83, &mut x84, x82, x33, x66); let mut x85: u32 = 0; let mut x86: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x85, &mut x86, x84, x35, x68); let mut x87: u32 = 0; let mut x88: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x87, &mut x88, x86, x37, x70); let mut x89: u32 = 0; let mut x90: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x89, &mut x90, x88, x39, x72); let mut x91: u32 = 0; let mut x92: u32 = 0; fiat_secp256k1_mulx_u32(&mut x91, &mut x92, x1, (arg1[7])); let mut x93: u32 = 0; let mut x94: u32 = 0; fiat_secp256k1_mulx_u32(&mut x93, &mut x94, x1, (arg1[6])); let mut x95: u32 = 0; let mut x96: u32 = 0; fiat_secp256k1_mulx_u32(&mut x95, &mut x96, x1, (arg1[5])); let mut x97: u32 = 0; let mut x98: u32 = 0; fiat_secp256k1_mulx_u32(&mut x97, &mut x98, x1, (arg1[4])); let mut x99: u32 = 0; let mut x100: u32 = 0; fiat_secp256k1_mulx_u32(&mut x99, &mut x100, x1, (arg1[3])); let mut x101: u32 = 0; let mut x102: u32 = 0; fiat_secp256k1_mulx_u32(&mut x101, &mut x102, x1, (arg1[2])); let mut x103: u32 = 0; let mut x104: u32 = 0; fiat_secp256k1_mulx_u32(&mut x103, &mut x104, x1, (arg1[1])); let mut x105: u32 = 0; let mut x106: u32 = 0; fiat_secp256k1_mulx_u32(&mut x105, &mut x106, x1, (arg1[0])); let mut x107: u32 = 0; let mut x108: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x107, &mut x108, 0x0, x106, x103); let mut x109: u32 = 0; let mut x110: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x109, &mut x110, x108, x104, x101); let mut x111: u32 = 0; let mut x112: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x111, &mut x112, x110, x102, x99); let mut x113: u32 = 0; let mut x114: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x113, &mut x114, x112, x100, x97); let mut x115: u32 = 0; let mut x116: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x115, &mut x116, x114, x98, x95); let mut x117: u32 = 0; let mut x118: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x117, &mut x118, x116, x96, x93); let mut x119: u32 = 0; let mut x120: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x119, &mut x120, x118, x94, x91); let x121: u32 = ((x120 as u32) + x92); let mut x122: u32 = 0; let mut x123: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x122, &mut x123, 0x0, x75, x105); let mut x124: u32 = 0; let mut x125: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x124, &mut x125, x123, x77, x107); let mut x126: u32 = 0; let mut x127: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x126, &mut x127, x125, x79, x109); let mut x128: u32 = 0; let mut x129: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x128, &mut x129, x127, x81, x111); let mut x130: u32 = 0; let mut x131: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x130, &mut x131, x129, x83, x113); let mut x132: u32 = 0; let mut x133: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x132, &mut x133, x131, x85, x115); let mut x134: u32 = 0; let mut x135: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x134, &mut x135, x133, x87, x117); let mut x136: u32 = 0; let mut x137: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x136, &mut x137, x135, x89, x119); let mut x138: u32 = 0; let mut x139: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x138, &mut x139, x137, (x90 as u32), x121); let mut x140: u32 = 0; let mut x141: u32 = 0; fiat_secp256k1_mulx_u32(&mut x140, &mut x141, x122, 0xd2253531); let mut x142: u32 = 0; let mut x143: u32 = 0; fiat_secp256k1_mulx_u32(&mut x142, &mut x143, x140, 0xffffffff); let mut x144: u32 = 0; let mut x145: u32 = 0; fiat_secp256k1_mulx_u32(&mut x144, &mut x145, x140, 0xffffffff); let mut x146: u32 = 0; let mut x147: u32 = 0; fiat_secp256k1_mulx_u32(&mut x146, &mut x147, x140, 0xffffffff); let mut x148: u32 = 0; let mut x149: u32 = 0; fiat_secp256k1_mulx_u32(&mut x148, &mut x149, x140, 0xffffffff); let mut x150: u32 = 0; let mut x151: u32 = 0; fiat_secp256k1_mulx_u32(&mut x150, &mut x151, x140, 0xffffffff); let mut x152: u32 = 0; let mut x153: u32 = 0; fiat_secp256k1_mulx_u32(&mut x152, &mut x153, x140, 0xffffffff); let mut x154: u32 = 0; let mut x155: u32 = 0; fiat_secp256k1_mulx_u32(&mut x154, &mut x155, x140, 0xfffffffe); let mut x156: u32 = 0; let mut x157: u32 = 0; fiat_secp256k1_mulx_u32(&mut x156, &mut x157, x140, 0xfffffc2f); let mut x158: u32 = 0; let mut x159: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x158, &mut x159, 0x0, x157, x154); let mut x160: u32 = 0; let mut x161: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x160, &mut x161, x159, x155, x152); let mut x162: u32 = 0; let mut x163: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x162, &mut x163, x161, x153, x150); let mut x164: u32 = 0; let mut x165: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x164, &mut x165, x163, x151, x148); let mut x166: u32 = 0; let mut x167: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x166, &mut x167, x165, x149, x146); let mut x168: u32 = 0; let mut x169: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x168, &mut x169, x167, x147, x144); let mut x170: u32 = 0; let mut x171: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x170, &mut x171, x169, x145, x142); let x172: u32 = ((x171 as u32) + x143); let mut x173: u32 = 0; let mut x174: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x173, &mut x174, 0x0, x122, x156); let mut x175: u32 = 0; let mut x176: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x175, &mut x176, x174, x124, x158); let mut x177: u32 = 0; let mut x178: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x177, &mut x178, x176, x126, x160); let mut x179: u32 = 0; let mut x180: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x179, &mut x180, x178, x128, x162); let mut x181: u32 = 0; let mut x182: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x181, &mut x182, x180, x130, x164); let mut x183: u32 = 0; let mut x184: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x183, &mut x184, x182, x132, x166); let mut x185: u32 = 0; let mut x186: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x185, &mut x186, x184, x134, x168); let mut x187: u32 = 0; let mut x188: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x187, &mut x188, x186, x136, x170); let mut x189: u32 = 0; let mut x190: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x189, &mut x190, x188, x138, x172); let x191: u32 = ((x190 as u32) + (x139 as u32)); let mut x192: u32 = 0; let mut x193: u32 = 0; fiat_secp256k1_mulx_u32(&mut x192, &mut x193, x2, (arg1[7])); let mut x194: u32 = 0; let mut x195: u32 = 0; fiat_secp256k1_mulx_u32(&mut x194, &mut x195, x2, (arg1[6])); let mut x196: u32 = 0; let mut x197: u32 = 0; fiat_secp256k1_mulx_u32(&mut x196, &mut x197, x2, (arg1[5])); let mut x198: u32 = 0; let mut x199: u32 = 0; fiat_secp256k1_mulx_u32(&mut x198, &mut x199, x2, (arg1[4])); let mut x200: u32 = 0; let mut x201: u32 = 0; fiat_secp256k1_mulx_u32(&mut x200, &mut x201, x2, (arg1[3])); let mut x202: u32 = 0; let mut x203: u32 = 0; fiat_secp256k1_mulx_u32(&mut x202, &mut x203, x2, (arg1[2])); let mut x204: u32 = 0; let mut x205: u32 = 0; fiat_secp256k1_mulx_u32(&mut x204, &mut x205, x2, (arg1[1])); let mut x206: u32 = 0; let mut x207: u32 = 0; fiat_secp256k1_mulx_u32(&mut x206, &mut x207, x2, (arg1[0])); let mut x208: u32 = 0; let mut x209: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x208, &mut x209, 0x0, x207, x204); let mut x210: u32 = 0; let mut x211: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x210, &mut x211, x209, x205, x202); let mut x212: u32 = 0; let mut x213: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x212, &mut x213, x211, x203, x200); let mut x214: u32 = 0; let mut x215: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x214, &mut x215, x213, x201, x198); let mut x216: u32 = 0; let mut x217: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x216, &mut x217, x215, x199, x196); let mut x218: u32 = 0; let mut x219: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x218, &mut x219, x217, x197, x194); let mut x220: u32 = 0; let mut x221: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x220, &mut x221, x219, x195, x192); let x222: u32 = ((x221 as u32) + x193); let mut x223: u32 = 0; let mut x224: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x223, &mut x224, 0x0, x175, x206); let mut x225: u32 = 0; let mut x226: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x225, &mut x226, x224, x177, x208); let mut x227: u32 = 0; let mut x228: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x227, &mut x228, x226, x179, x210); let mut x229: u32 = 0; let mut x230: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x229, &mut x230, x228, x181, x212); let mut x231: u32 = 0; let mut x232: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x231, &mut x232, x230, x183, x214); let mut x233: u32 = 0; let mut x234: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x233, &mut x234, x232, x185, x216); let mut x235: u32 = 0; let mut x236: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x235, &mut x236, x234, x187, x218); let mut x237: u32 = 0; let mut x238: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x237, &mut x238, x236, x189, x220); let mut x239: u32 = 0; let mut x240: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x239, &mut x240, x238, x191, x222); let mut x241: u32 = 0; let mut x242: u32 = 0; fiat_secp256k1_mulx_u32(&mut x241, &mut x242, x223, 0xd2253531); let mut x243: u32 = 0; let mut x244: u32 = 0; fiat_secp256k1_mulx_u32(&mut x243, &mut x244, x241, 0xffffffff); let mut x245: u32 = 0; let mut x246: u32 = 0; fiat_secp256k1_mulx_u32(&mut x245, &mut x246, x241, 0xffffffff); let mut x247: u32 = 0; let mut x248: u32 = 0; fiat_secp256k1_mulx_u32(&mut x247, &mut x248, x241, 0xffffffff); let mut x249: u32 = 0; let mut x250: u32 = 0; fiat_secp256k1_mulx_u32(&mut x249, &mut x250, x241, 0xffffffff); let mut x251: u32 = 0; let mut x252: u32 = 0; fiat_secp256k1_mulx_u32(&mut x251, &mut x252, x241, 0xffffffff); let mut x253: u32 = 0; let mut x254: u32 = 0; fiat_secp256k1_mulx_u32(&mut x253, &mut x254, x241, 0xffffffff); let mut x255: u32 = 0; let mut x256: u32 = 0; fiat_secp256k1_mulx_u32(&mut x255, &mut x256, x241, 0xfffffffe); let mut x257: u32 = 0; let mut x258: u32 = 0; fiat_secp256k1_mulx_u32(&mut x257, &mut x258, x241, 0xfffffc2f); let mut x259: u32 = 0; let mut x260: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x259, &mut x260, 0x0, x258, x255); let mut x261: u32 = 0; let mut x262: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x261, &mut x262, x260, x256, x253); let mut x263: u32 = 0; let mut x264: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x263, &mut x264, x262, x254, x251); let mut x265: u32 = 0; let mut x266: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x265, &mut x266, x264, x252, x249); let mut x267: u32 = 0; let mut x268: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x267, &mut x268, x266, x250, x247); let mut x269: u32 = 0; let mut x270: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x269, &mut x270, x268, x248, x245); let mut x271: u32 = 0; let mut x272: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x271, &mut x272, x270, x246, x243); let x273: u32 = ((x272 as u32) + x244); let mut x274: u32 = 0; let mut x275: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x274, &mut x275, 0x0, x223, x257); let mut x276: u32 = 0; let mut x277: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x276, &mut x277, x275, x225, x259); let mut x278: u32 = 0; let mut x279: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x278, &mut x279, x277, x227, x261); let mut x280: u32 = 0; let mut x281: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x280, &mut x281, x279, x229, x263); let mut x282: u32 = 0; let mut x283: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x282, &mut x283, x281, x231, x265); let mut x284: u32 = 0; let mut x285: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x284, &mut x285, x283, x233, x267); let mut x286: u32 = 0; let mut x287: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x286, &mut x287, x285, x235, x269); let mut x288: u32 = 0; let mut x289: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x288, &mut x289, x287, x237, x271); let mut x290: u32 = 0; let mut x291: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x290, &mut x291, x289, x239, x273); let x292: u32 = ((x291 as u32) + (x240 as u32)); let mut x293: u32 = 0; let mut x294: u32 = 0; fiat_secp256k1_mulx_u32(&mut x293, &mut x294, x3, (arg1[7])); let mut x295: u32 = 0; let mut x296: u32 = 0; fiat_secp256k1_mulx_u32(&mut x295, &mut x296, x3, (arg1[6])); let mut x297: u32 = 0; let mut x298: u32 = 0; fiat_secp256k1_mulx_u32(&mut x297, &mut x298, x3, (arg1[5])); let mut x299: u32 = 0; let mut x300: u32 = 0; fiat_secp256k1_mulx_u32(&mut x299, &mut x300, x3, (arg1[4])); let mut x301: u32 = 0; let mut x302: u32 = 0; fiat_secp256k1_mulx_u32(&mut x301, &mut x302, x3, (arg1[3])); let mut x303: u32 = 0; let mut x304: u32 = 0; fiat_secp256k1_mulx_u32(&mut x303, &mut x304, x3, (arg1[2])); let mut x305: u32 = 0; let mut x306: u32 = 0; fiat_secp256k1_mulx_u32(&mut x305, &mut x306, x3, (arg1[1])); let mut x307: u32 = 0; let mut x308: u32 = 0; fiat_secp256k1_mulx_u32(&mut x307, &mut x308, x3, (arg1[0])); let mut x309: u32 = 0; let mut x310: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x309, &mut x310, 0x0, x308, x305); let mut x311: u32 = 0; let mut x312: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x311, &mut x312, x310, x306, x303); let mut x313: u32 = 0; let mut x314: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x313, &mut x314, x312, x304, x301); let mut x315: u32 = 0; let mut x316: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x315, &mut x316, x314, x302, x299); let mut x317: u32 = 0; let mut x318: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x317, &mut x318, x316, x300, x297); let mut x319: u32 = 0; let mut x320: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x319, &mut x320, x318, x298, x295); let mut x321: u32 = 0; let mut x322: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x321, &mut x322, x320, x296, x293); let x323: u32 = ((x322 as u32) + x294); let mut x324: u32 = 0; let mut x325: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x324, &mut x325, 0x0, x276, x307); let mut x326: u32 = 0; let mut x327: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x326, &mut x327, x325, x278, x309); let mut x328: u32 = 0; let mut x329: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x328, &mut x329, x327, x280, x311); let mut x330: u32 = 0; let mut x331: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x330, &mut x331, x329, x282, x313); let mut x332: u32 = 0; let mut x333: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x332, &mut x333, x331, x284, x315); let mut x334: u32 = 0; let mut x335: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x334, &mut x335, x333, x286, x317); let mut x336: u32 = 0; let mut x337: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x336, &mut x337, x335, x288, x319); let mut x338: u32 = 0; let mut x339: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x338, &mut x339, x337, x290, x321); let mut x340: u32 = 0; let mut x341: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x340, &mut x341, x339, x292, x323); let mut x342: u32 = 0; let mut x343: u32 = 0; fiat_secp256k1_mulx_u32(&mut x342, &mut x343, x324, 0xd2253531); let mut x344: u32 = 0; let mut x345: u32 = 0; fiat_secp256k1_mulx_u32(&mut x344, &mut x345, x342, 0xffffffff); let mut x346: u32 = 0; let mut x347: u32 = 0; fiat_secp256k1_mulx_u32(&mut x346, &mut x347, x342, 0xffffffff); let mut x348: u32 = 0; let mut x349: u32 = 0; fiat_secp256k1_mulx_u32(&mut x348, &mut x349, x342, 0xffffffff); let mut x350: u32 = 0; let mut x351: u32 = 0; fiat_secp256k1_mulx_u32(&mut x350, &mut x351, x342, 0xffffffff); let mut x352: u32 = 0; let mut x353: u32 = 0; fiat_secp256k1_mulx_u32(&mut x352, &mut x353, x342, 0xffffffff); let mut x354: u32 = 0; let mut x355: u32 = 0; fiat_secp256k1_mulx_u32(&mut x354, &mut x355, x342, 0xffffffff); let mut x356: u32 = 0; let mut x357: u32 = 0; fiat_secp256k1_mulx_u32(&mut x356, &mut x357, x342, 0xfffffffe); let mut x358: u32 = 0; let mut x359: u32 = 0; fiat_secp256k1_mulx_u32(&mut x358, &mut x359, x342, 0xfffffc2f); let mut x360: u32 = 0; let mut x361: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x360, &mut x361, 0x0, x359, x356); let mut x362: u32 = 0; let mut x363: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x362, &mut x363, x361, x357, x354); let mut x364: u32 = 0; let mut x365: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x364, &mut x365, x363, x355, x352); let mut x366: u32 = 0; let mut x367: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x366, &mut x367, x365, x353, x350); let mut x368: u32 = 0; let mut x369: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x368, &mut x369, x367, x351, x348); let mut x370: u32 = 0; let mut x371: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x370, &mut x371, x369, x349, x346); let mut x372: u32 = 0; let mut x373: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x372, &mut x373, x371, x347, x344); let x374: u32 = ((x373 as u32) + x345); let mut x375: u32 = 0; let mut x376: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x375, &mut x376, 0x0, x324, x358); let mut x377: u32 = 0; let mut x378: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x377, &mut x378, x376, x326, x360); let mut x379: u32 = 0; let mut x380: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x379, &mut x380, x378, x328, x362); let mut x381: u32 = 0; let mut x382: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x381, &mut x382, x380, x330, x364); let mut x383: u32 = 0; let mut x384: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x383, &mut x384, x382, x332, x366); let mut x385: u32 = 0; let mut x386: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x385, &mut x386, x384, x334, x368); let mut x387: u32 = 0; let mut x388: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x387, &mut x388, x386, x336, x370); let mut x389: u32 = 0; let mut x390: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x389, &mut x390, x388, x338, x372); let mut x391: u32 = 0; let mut x392: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x391, &mut x392, x390, x340, x374); let x393: u32 = ((x392 as u32) + (x341 as u32)); let mut x394: u32 = 0; let mut x395: u32 = 0; fiat_secp256k1_mulx_u32(&mut x394, &mut x395, x4, (arg1[7])); let mut x396: u32 = 0; let mut x397: u32 = 0; fiat_secp256k1_mulx_u32(&mut x396, &mut x397, x4, (arg1[6])); let mut x398: u32 = 0; let mut x399: u32 = 0; fiat_secp256k1_mulx_u32(&mut x398, &mut x399, x4, (arg1[5])); let mut x400: u32 = 0; let mut x401: u32 = 0; fiat_secp256k1_mulx_u32(&mut x400, &mut x401, x4, (arg1[4])); let mut x402: u32 = 0; let mut x403: u32 = 0; fiat_secp256k1_mulx_u32(&mut x402, &mut x403, x4, (arg1[3])); let mut x404: u32 = 0; let mut x405: u32 = 0; fiat_secp256k1_mulx_u32(&mut x404, &mut x405, x4, (arg1[2])); let mut x406: u32 = 0; let mut x407: u32 = 0; fiat_secp256k1_mulx_u32(&mut x406, &mut x407, x4, (arg1[1])); let mut x408: u32 = 0; let mut x409: u32 = 0; fiat_secp256k1_mulx_u32(&mut x408, &mut x409, x4, (arg1[0])); let mut x410: u32 = 0; let mut x411: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x410, &mut x411, 0x0, x409, x406); let mut x412: u32 = 0; let mut x413: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x412, &mut x413, x411, x407, x404); let mut x414: u32 = 0; let mut x415: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x414, &mut x415, x413, x405, x402); let mut x416: u32 = 0; let mut x417: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x416, &mut x417, x415, x403, x400); let mut x418: u32 = 0; let mut x419: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x418, &mut x419, x417, x401, x398); let mut x420: u32 = 0; let mut x421: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x420, &mut x421, x419, x399, x396); let mut x422: u32 = 0; let mut x423: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x422, &mut x423, x421, x397, x394); let x424: u32 = ((x423 as u32) + x395); let mut x425: u32 = 0; let mut x426: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x425, &mut x426, 0x0, x377, x408); let mut x427: u32 = 0; let mut x428: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x427, &mut x428, x426, x379, x410); let mut x429: u32 = 0; let mut x430: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x429, &mut x430, x428, x381, x412); let mut x431: u32 = 0; let mut x432: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x431, &mut x432, x430, x383, x414); let mut x433: u32 = 0; let mut x434: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x433, &mut x434, x432, x385, x416); let mut x435: u32 = 0; let mut x436: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x435, &mut x436, x434, x387, x418); let mut x437: u32 = 0; let mut x438: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x437, &mut x438, x436, x389, x420); let mut x439: u32 = 0; let mut x440: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x439, &mut x440, x438, x391, x422); let mut x441: u32 = 0; let mut x442: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x441, &mut x442, x440, x393, x424); let mut x443: u32 = 0; let mut x444: u32 = 0; fiat_secp256k1_mulx_u32(&mut x443, &mut x444, x425, 0xd2253531); let mut x445: u32 = 0; let mut x446: u32 = 0; fiat_secp256k1_mulx_u32(&mut x445, &mut x446, x443, 0xffffffff); let mut x447: u32 = 0; let mut x448: u32 = 0; fiat_secp256k1_mulx_u32(&mut x447, &mut x448, x443, 0xffffffff); let mut x449: u32 = 0; let mut x450: u32 = 0; fiat_secp256k1_mulx_u32(&mut x449, &mut x450, x443, 0xffffffff); let mut x451: u32 = 0; let mut x452: u32 = 0; fiat_secp256k1_mulx_u32(&mut x451, &mut x452, x443, 0xffffffff); let mut x453: u32 = 0; let mut x454: u32 = 0; fiat_secp256k1_mulx_u32(&mut x453, &mut x454, x443, 0xffffffff); let mut x455: u32 = 0; let mut x456: u32 = 0; fiat_secp256k1_mulx_u32(&mut x455, &mut x456, x443, 0xffffffff); let mut x457: u32 = 0; let mut x458: u32 = 0; fiat_secp256k1_mulx_u32(&mut x457, &mut x458, x443, 0xfffffffe); let mut x459: u32 = 0; let mut x460: u32 = 0; fiat_secp256k1_mulx_u32(&mut x459, &mut x460, x443, 0xfffffc2f); let mut x461: u32 = 0; let mut x462: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x461, &mut x462, 0x0, x460, x457); let mut x463: u32 = 0; let mut x464: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x463, &mut x464, x462, x458, x455); let mut x465: u32 = 0; let mut x466: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x465, &mut x466, x464, x456, x453); let mut x467: u32 = 0; let mut x468: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x467, &mut x468, x466, x454, x451); let mut x469: u32 = 0; let mut x470: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x469, &mut x470, x468, x452, x449); let mut x471: u32 = 0; let mut x472: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x471, &mut x472, x470, x450, x447); let mut x473: u32 = 0; let mut x474: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x473, &mut x474, x472, x448, x445); let x475: u32 = ((x474 as u32) + x446); let mut x476: u32 = 0; let mut x477: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x476, &mut x477, 0x0, x425, x459); let mut x478: u32 = 0; let mut x479: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x478, &mut x479, x477, x427, x461); let mut x480: u32 = 0; let mut x481: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x480, &mut x481, x479, x429, x463); let mut x482: u32 = 0; let mut x483: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x482, &mut x483, x481, x431, x465); let mut x484: u32 = 0; let mut x485: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x484, &mut x485, x483, x433, x467); let mut x486: u32 = 0; let mut x487: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x486, &mut x487, x485, x435, x469); let mut x488: u32 = 0; let mut x489: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x488, &mut x489, x487, x437, x471); let mut x490: u32 = 0; let mut x491: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x490, &mut x491, x489, x439, x473); let mut x492: u32 = 0; let mut x493: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x492, &mut x493, x491, x441, x475); let x494: u32 = ((x493 as u32) + (x442 as u32)); let mut x495: u32 = 0; let mut x496: u32 = 0; fiat_secp256k1_mulx_u32(&mut x495, &mut x496, x5, (arg1[7])); let mut x497: u32 = 0; let mut x498: u32 = 0; fiat_secp256k1_mulx_u32(&mut x497, &mut x498, x5, (arg1[6])); let mut x499: u32 = 0; let mut x500: u32 = 0; fiat_secp256k1_mulx_u32(&mut x499, &mut x500, x5, (arg1[5])); let mut x501: u32 = 0; let mut x502: u32 = 0; fiat_secp256k1_mulx_u32(&mut x501, &mut x502, x5, (arg1[4])); let mut x503: u32 = 0; let mut x504: u32 = 0; fiat_secp256k1_mulx_u32(&mut x503, &mut x504, x5, (arg1[3])); let mut x505: u32 = 0; let mut x506: u32 = 0; fiat_secp256k1_mulx_u32(&mut x505, &mut x506, x5, (arg1[2])); let mut x507: u32 = 0; let mut x508: u32 = 0; fiat_secp256k1_mulx_u32(&mut x507, &mut x508, x5, (arg1[1])); let mut x509: u32 = 0; let mut x510: u32 = 0; fiat_secp256k1_mulx_u32(&mut x509, &mut x510, x5, (arg1[0])); let mut x511: u32 = 0; let mut x512: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x511, &mut x512, 0x0, x510, x507); let mut x513: u32 = 0; let mut x514: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x513, &mut x514, x512, x508, x505); let mut x515: u32 = 0; let mut x516: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x515, &mut x516, x514, x506, x503); let mut x517: u32 = 0; let mut x518: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x517, &mut x518, x516, x504, x501); let mut x519: u32 = 0; let mut x520: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x519, &mut x520, x518, x502, x499); let mut x521: u32 = 0; let mut x522: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x521, &mut x522, x520, x500, x497); let mut x523: u32 = 0; let mut x524: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x523, &mut x524, x522, x498, x495); let x525: u32 = ((x524 as u32) + x496); let mut x526: u32 = 0; let mut x527: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x526, &mut x527, 0x0, x478, x509); let mut x528: u32 = 0; let mut x529: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x528, &mut x529, x527, x480, x511); let mut x530: u32 = 0; let mut x531: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x530, &mut x531, x529, x482, x513); let mut x532: u32 = 0; let mut x533: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x532, &mut x533, x531, x484, x515); let mut x534: u32 = 0; let mut x535: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x534, &mut x535, x533, x486, x517); let mut x536: u32 = 0; let mut x537: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x536, &mut x537, x535, x488, x519); let mut x538: u32 = 0; let mut x539: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x538, &mut x539, x537, x490, x521); let mut x540: u32 = 0; let mut x541: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x540, &mut x541, x539, x492, x523); let mut x542: u32 = 0; let mut x543: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x542, &mut x543, x541, x494, x525); let mut x544: u32 = 0; let mut x545: u32 = 0; fiat_secp256k1_mulx_u32(&mut x544, &mut x545, x526, 0xd2253531); let mut x546: u32 = 0; let mut x547: u32 = 0; fiat_secp256k1_mulx_u32(&mut x546, &mut x547, x544, 0xffffffff); let mut x548: u32 = 0; let mut x549: u32 = 0; fiat_secp256k1_mulx_u32(&mut x548, &mut x549, x544, 0xffffffff); let mut x550: u32 = 0; let mut x551: u32 = 0; fiat_secp256k1_mulx_u32(&mut x550, &mut x551, x544, 0xffffffff); let mut x552: u32 = 0; let mut x553: u32 = 0; fiat_secp256k1_mulx_u32(&mut x552, &mut x553, x544, 0xffffffff); let mut x554: u32 = 0; let mut x555: u32 = 0; fiat_secp256k1_mulx_u32(&mut x554, &mut x555, x544, 0xffffffff); let mut x556: u32 = 0; let mut x557: u32 = 0; fiat_secp256k1_mulx_u32(&mut x556, &mut x557, x544, 0xffffffff); let mut x558: u32 = 0; let mut x559: u32 = 0; fiat_secp256k1_mulx_u32(&mut x558, &mut x559, x544, 0xfffffffe); let mut x560: u32 = 0; let mut x561: u32 = 0; fiat_secp256k1_mulx_u32(&mut x560, &mut x561, x544, 0xfffffc2f); let mut x562: u32 = 0; let mut x563: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x562, &mut x563, 0x0, x561, x558); let mut x564: u32 = 0; let mut x565: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x564, &mut x565, x563, x559, x556); let mut x566: u32 = 0; let mut x567: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x566, &mut x567, x565, x557, x554); let mut x568: u32 = 0; let mut x569: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x568, &mut x569, x567, x555, x552); let mut x570: u32 = 0; let mut x571: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x570, &mut x571, x569, x553, x550); let mut x572: u32 = 0; let mut x573: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x572, &mut x573, x571, x551, x548); let mut x574: u32 = 0; let mut x575: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x574, &mut x575, x573, x549, x546); let x576: u32 = ((x575 as u32) + x547); let mut x577: u32 = 0; let mut x578: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x577, &mut x578, 0x0, x526, x560); let mut x579: u32 = 0; let mut x580: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x579, &mut x580, x578, x528, x562); let mut x581: u32 = 0; let mut x582: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x581, &mut x582, x580, x530, x564); let mut x583: u32 = 0; let mut x584: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x583, &mut x584, x582, x532, x566); let mut x585: u32 = 0; let mut x586: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x585, &mut x586, x584, x534, x568); let mut x587: u32 = 0; let mut x588: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x587, &mut x588, x586, x536, x570); let mut x589: u32 = 0; let mut x590: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x589, &mut x590, x588, x538, x572); let mut x591: u32 = 0; let mut x592: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x591, &mut x592, x590, x540, x574); let mut x593: u32 = 0; let mut x594: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x593, &mut x594, x592, x542, x576); let x595: u32 = ((x594 as u32) + (x543 as u32)); let mut x596: u32 = 0; let mut x597: u32 = 0; fiat_secp256k1_mulx_u32(&mut x596, &mut x597, x6, (arg1[7])); let mut x598: u32 = 0; let mut x599: u32 = 0; fiat_secp256k1_mulx_u32(&mut x598, &mut x599, x6, (arg1[6])); let mut x600: u32 = 0; let mut x601: u32 = 0; fiat_secp256k1_mulx_u32(&mut x600, &mut x601, x6, (arg1[5])); let mut x602: u32 = 0; let mut x603: u32 = 0; fiat_secp256k1_mulx_u32(&mut x602, &mut x603, x6, (arg1[4])); let mut x604: u32 = 0; let mut x605: u32 = 0; fiat_secp256k1_mulx_u32(&mut x604, &mut x605, x6, (arg1[3])); let mut x606: u32 = 0; let mut x607: u32 = 0; fiat_secp256k1_mulx_u32(&mut x606, &mut x607, x6, (arg1[2])); let mut x608: u32 = 0; let mut x609: u32 = 0; fiat_secp256k1_mulx_u32(&mut x608, &mut x609, x6, (arg1[1])); let mut x610: u32 = 0; let mut x611: u32 = 0; fiat_secp256k1_mulx_u32(&mut x610, &mut x611, x6, (arg1[0])); let mut x612: u32 = 0; let mut x613: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x612, &mut x613, 0x0, x611, x608); let mut x614: u32 = 0; let mut x615: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x614, &mut x615, x613, x609, x606); let mut x616: u32 = 0; let mut x617: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x616, &mut x617, x615, x607, x604); let mut x618: u32 = 0; let mut x619: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x618, &mut x619, x617, x605, x602); let mut x620: u32 = 0; let mut x621: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x620, &mut x621, x619, x603, x600); let mut x622: u32 = 0; let mut x623: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x622, &mut x623, x621, x601, x598); let mut x624: u32 = 0; let mut x625: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x624, &mut x625, x623, x599, x596); let x626: u32 = ((x625 as u32) + x597); let mut x627: u32 = 0; let mut x628: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x627, &mut x628, 0x0, x579, x610); let mut x629: u32 = 0; let mut x630: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x629, &mut x630, x628, x581, x612); let mut x631: u32 = 0; let mut x632: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x631, &mut x632, x630, x583, x614); let mut x633: u32 = 0; let mut x634: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x633, &mut x634, x632, x585, x616); let mut x635: u32 = 0; let mut x636: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x635, &mut x636, x634, x587, x618); let mut x637: u32 = 0; let mut x638: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x637, &mut x638, x636, x589, x620); let mut x639: u32 = 0; let mut x640: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x639, &mut x640, x638, x591, x622); let mut x641: u32 = 0; let mut x642: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x641, &mut x642, x640, x593, x624); let mut x643: u32 = 0; let mut x644: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x643, &mut x644, x642, x595, x626); let mut x645: u32 = 0; let mut x646: u32 = 0; fiat_secp256k1_mulx_u32(&mut x645, &mut x646, x627, 0xd2253531); let mut x647: u32 = 0; let mut x648: u32 = 0; fiat_secp256k1_mulx_u32(&mut x647, &mut x648, x645, 0xffffffff); let mut x649: u32 = 0; let mut x650: u32 = 0; fiat_secp256k1_mulx_u32(&mut x649, &mut x650, x645, 0xffffffff); let mut x651: u32 = 0; let mut x652: u32 = 0; fiat_secp256k1_mulx_u32(&mut x651, &mut x652, x645, 0xffffffff); let mut x653: u32 = 0; let mut x654: u32 = 0; fiat_secp256k1_mulx_u32(&mut x653, &mut x654, x645, 0xffffffff); let mut x655: u32 = 0; let mut x656: u32 = 0; fiat_secp256k1_mulx_u32(&mut x655, &mut x656, x645, 0xffffffff); let mut x657: u32 = 0; let mut x658: u32 = 0; fiat_secp256k1_mulx_u32(&mut x657, &mut x658, x645, 0xffffffff); let mut x659: u32 = 0; let mut x660: u32 = 0; fiat_secp256k1_mulx_u32(&mut x659, &mut x660, x645, 0xfffffffe); let mut x661: u32 = 0; let mut x662: u32 = 0; fiat_secp256k1_mulx_u32(&mut x661, &mut x662, x645, 0xfffffc2f); let mut x663: u32 = 0; let mut x664: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x663, &mut x664, 0x0, x662, x659); let mut x665: u32 = 0; let mut x666: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x665, &mut x666, x664, x660, x657); let mut x667: u32 = 0; let mut x668: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x667, &mut x668, x666, x658, x655); let mut x669: u32 = 0; let mut x670: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x669, &mut x670, x668, x656, x653); let mut x671: u32 = 0; let mut x672: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x671, &mut x672, x670, x654, x651); let mut x673: u32 = 0; let mut x674: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x673, &mut x674, x672, x652, x649); let mut x675: u32 = 0; let mut x676: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x675, &mut x676, x674, x650, x647); let x677: u32 = ((x676 as u32) + x648); let mut x678: u32 = 0; let mut x679: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x678, &mut x679, 0x0, x627, x661); let mut x680: u32 = 0; let mut x681: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x680, &mut x681, x679, x629, x663); let mut x682: u32 = 0; let mut x683: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x682, &mut x683, x681, x631, x665); let mut x684: u32 = 0; let mut x685: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x684, &mut x685, x683, x633, x667); let mut x686: u32 = 0; let mut x687: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x686, &mut x687, x685, x635, x669); let mut x688: u32 = 0; let mut x689: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x688, &mut x689, x687, x637, x671); let mut x690: u32 = 0; let mut x691: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x690, &mut x691, x689, x639, x673); let mut x692: u32 = 0; let mut x693: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x692, &mut x693, x691, x641, x675); let mut x694: u32 = 0; let mut x695: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x694, &mut x695, x693, x643, x677); let x696: u32 = ((x695 as u32) + (x644 as u32)); let mut x697: u32 = 0; let mut x698: u32 = 0; fiat_secp256k1_mulx_u32(&mut x697, &mut x698, x7, (arg1[7])); let mut x699: u32 = 0; let mut x700: u32 = 0; fiat_secp256k1_mulx_u32(&mut x699, &mut x700, x7, (arg1[6])); let mut x701: u32 = 0; let mut x702: u32 = 0; fiat_secp256k1_mulx_u32(&mut x701, &mut x702, x7, (arg1[5])); let mut x703: u32 = 0; let mut x704: u32 = 0; fiat_secp256k1_mulx_u32(&mut x703, &mut x704, x7, (arg1[4])); let mut x705: u32 = 0; let mut x706: u32 = 0; fiat_secp256k1_mulx_u32(&mut x705, &mut x706, x7, (arg1[3])); let mut x707: u32 = 0; let mut x708: u32 = 0; fiat_secp256k1_mulx_u32(&mut x707, &mut x708, x7, (arg1[2])); let mut x709: u32 = 0; let mut x710: u32 = 0; fiat_secp256k1_mulx_u32(&mut x709, &mut x710, x7, (arg1[1])); let mut x711: u32 = 0; let mut x712: u32 = 0; fiat_secp256k1_mulx_u32(&mut x711, &mut x712, x7, (arg1[0])); let mut x713: u32 = 0; let mut x714: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x713, &mut x714, 0x0, x712, x709); let mut x715: u32 = 0; let mut x716: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x715, &mut x716, x714, x710, x707); let mut x717: u32 = 0; let mut x718: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x717, &mut x718, x716, x708, x705); let mut x719: u32 = 0; let mut x720: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x719, &mut x720, x718, x706, x703); let mut x721: u32 = 0; let mut x722: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x721, &mut x722, x720, x704, x701); let mut x723: u32 = 0; let mut x724: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x723, &mut x724, x722, x702, x699); let mut x725: u32 = 0; let mut x726: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x725, &mut x726, x724, x700, x697); let x727: u32 = ((x726 as u32) + x698); let mut x728: u32 = 0; let mut x729: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x728, &mut x729, 0x0, x680, x711); let mut x730: u32 = 0; let mut x731: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x730, &mut x731, x729, x682, x713); let mut x732: u32 = 0; let mut x733: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x732, &mut x733, x731, x684, x715); let mut x734: u32 = 0; let mut x735: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x734, &mut x735, x733, x686, x717); let mut x736: u32 = 0; let mut x737: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x736, &mut x737, x735, x688, x719); let mut x738: u32 = 0; let mut x739: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x738, &mut x739, x737, x690, x721); let mut x740: u32 = 0; let mut x741: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x740, &mut x741, x739, x692, x723); let mut x742: u32 = 0; let mut x743: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x742, &mut x743, x741, x694, x725); let mut x744: u32 = 0; let mut x745: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x744, &mut x745, x743, x696, x727); let mut x746: u32 = 0; let mut x747: u32 = 0; fiat_secp256k1_mulx_u32(&mut x746, &mut x747, x728, 0xd2253531); let mut x748: u32 = 0; let mut x749: u32 = 0; fiat_secp256k1_mulx_u32(&mut x748, &mut x749, x746, 0xffffffff); let mut x750: u32 = 0; let mut x751: u32 = 0; fiat_secp256k1_mulx_u32(&mut x750, &mut x751, x746, 0xffffffff); let mut x752: u32 = 0; let mut x753: u32 = 0; fiat_secp256k1_mulx_u32(&mut x752, &mut x753, x746, 0xffffffff); let mut x754: u32 = 0; let mut x755: u32 = 0; fiat_secp256k1_mulx_u32(&mut x754, &mut x755, x746, 0xffffffff); let mut x756: u32 = 0; let mut x757: u32 = 0; fiat_secp256k1_mulx_u32(&mut x756, &mut x757, x746, 0xffffffff); let mut x758: u32 = 0; let mut x759: u32 = 0; fiat_secp256k1_mulx_u32(&mut x758, &mut x759, x746, 0xffffffff); let mut x760: u32 = 0; let mut x761: u32 = 0; fiat_secp256k1_mulx_u32(&mut x760, &mut x761, x746, 0xfffffffe); let mut x762: u32 = 0; let mut x763: u32 = 0; fiat_secp256k1_mulx_u32(&mut x762, &mut x763, x746, 0xfffffc2f); let mut x764: u32 = 0; let mut x765: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x764, &mut x765, 0x0, x763, x760); let mut x766: u32 = 0; let mut x767: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x766, &mut x767, x765, x761, x758); let mut x768: u32 = 0; let mut x769: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x768, &mut x769, x767, x759, x756); let mut x770: u32 = 0; let mut x771: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x770, &mut x771, x769, x757, x754); let mut x772: u32 = 0; let mut x773: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x772, &mut x773, x771, x755, x752); let mut x774: u32 = 0; let mut x775: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x774, &mut x775, x773, x753, x750); let mut x776: u32 = 0; let mut x777: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x776, &mut x777, x775, x751, x748); let x778: u32 = ((x777 as u32) + x749); let mut x779: u32 = 0; let mut x780: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x779, &mut x780, 0x0, x728, x762); let mut x781: u32 = 0; let mut x782: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x781, &mut x782, x780, x730, x764); let mut x783: u32 = 0; let mut x784: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x783, &mut x784, x782, x732, x766); let mut x785: u32 = 0; let mut x786: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x785, &mut x786, x784, x734, x768); let mut x787: u32 = 0; let mut x788: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x787, &mut x788, x786, x736, x770); let mut x789: u32 = 0; let mut x790: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x789, &mut x790, x788, x738, x772); let mut x791: u32 = 0; let mut x792: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x791, &mut x792, x790, x740, x774); let mut x793: u32 = 0; let mut x794: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x793, &mut x794, x792, x742, x776); let mut x795: u32 = 0; let mut x796: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x795, &mut x796, x794, x744, x778); let x797: u32 = ((x796 as u32) + (x745 as u32)); let mut x798: u32 = 0; let mut x799: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x798, &mut x799, 0x0, x781, 0xfffffc2f); let mut x800: u32 = 0; let mut x801: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x800, &mut x801, x799, x783, 0xfffffffe); let mut x802: u32 = 0; let mut x803: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x802, &mut x803, x801, x785, 0xffffffff); let mut x804: u32 = 0; let mut x805: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x804, &mut x805, x803, x787, 0xffffffff); let mut x806: u32 = 0; let mut x807: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x806, &mut x807, x805, x789, 0xffffffff); let mut x808: u32 = 0; let mut x809: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x808, &mut x809, x807, x791, 0xffffffff); let mut x810: u32 = 0; let mut x811: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x810, &mut x811, x809, x793, 0xffffffff); let mut x812: u32 = 0; let mut x813: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x812, &mut x813, x811, x795, 0xffffffff); let mut x814: u32 = 0; let mut x815: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x814, &mut x815, x813, x797, (0x0 as u32)); let mut x816: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x816, x815, x798, x781); let mut x817: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x817, x815, x800, x783); let mut x818: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x818, x815, x802, x785); let mut x819: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x819, x815, x804, x787); let mut x820: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x820, x815, x806, x789); let mut x821: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x821, x815, x808, x791); let mut x822: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x822, x815, x810, x793); let mut x823: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x823, x815, x812, x795); out1[0] = x816; out1[1] = x817; out1[2] = x818; out1[3] = x819; out1[4] = x820; out1[5] = x821; out1[6] = x822; out1[7] = x823; } /// The function fiat_secp256k1_add adds two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_add(out1: &mut [u32; 8], arg1: &[u32; 8], arg2: &[u32; 8]) -> () { let mut x1: u32 = 0; let mut x2: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x1, &mut x2, 0x0, (arg1[0]), (arg2[0])); let mut x3: u32 = 0; let mut x4: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x3, &mut x4, x2, (arg1[1]), (arg2[1])); let mut x5: u32 = 0; let mut x6: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x5, &mut x6, x4, (arg1[2]), (arg2[2])); let mut x7: u32 = 0; let mut x8: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x7, &mut x8, x6, (arg1[3]), (arg2[3])); let mut x9: u32 = 0; let mut x10: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x9, &mut x10, x8, (arg1[4]), (arg2[4])); let mut x11: u32 = 0; let mut x12: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x11, &mut x12, x10, (arg1[5]), (arg2[5])); let mut x13: u32 = 0; let mut x14: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x13, &mut x14, x12, (arg1[6]), (arg2[6])); let mut x15: u32 = 0; let mut x16: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x15, &mut x16, x14, (arg1[7]), (arg2[7])); let mut x17: u32 = 0; let mut x18: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x17, &mut x18, 0x0, x1, 0xfffffc2f); let mut x19: u32 = 0; let mut x20: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x19, &mut x20, x18, x3, 0xfffffffe); let mut x21: u32 = 0; let mut x22: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x21, &mut x22, x20, x5, 0xffffffff); let mut x23: u32 = 0; let mut x24: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x23, &mut x24, x22, x7, 0xffffffff); let mut x25: u32 = 0; let mut x26: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x25, &mut x26, x24, x9, 0xffffffff); let mut x27: u32 = 0; let mut x28: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x27, &mut x28, x26, x11, 0xffffffff); let mut x29: u32 = 0; let mut x30: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x29, &mut x30, x28, x13, 0xffffffff); let mut x31: u32 = 0; let mut x32: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x31, &mut x32, x30, x15, 0xffffffff); let mut x33: u32 = 0; let mut x34: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x33, &mut x34, x32, (x16 as u32), (0x0 as u32)); let mut x35: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x35, x34, x17, x1); let mut x36: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x36, x34, x19, x3); let mut x37: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x37, x34, x21, x5); let mut x38: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x38, x34, x23, x7); let mut x39: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x39, x34, x25, x9); let mut x40: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x40, x34, x27, x11); let mut x41: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x41, x34, x29, x13); let mut x42: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x42, x34, x31, x15); out1[0] = x35; out1[1] = x36; out1[2] = x37; out1[3] = x38; out1[4] = x39; out1[5] = x40; out1[6] = x41; out1[7] = x42; } /// The function fiat_secp256k1_sub subtracts two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_sub(out1: &mut [u32; 8], arg1: &[u32; 8], arg2: &[u32; 8]) -> () { let mut x1: u32 = 0; let mut x2: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x1, &mut x2, 0x0, (arg1[0]), (arg2[0])); let mut x3: u32 = 0; let mut x4: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x3, &mut x4, x2, (arg1[1]), (arg2[1])); let mut x5: u32 = 0; let mut x6: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x5, &mut x6, x4, (arg1[2]), (arg2[2])); let mut x7: u32 = 0; let mut x8: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x7, &mut x8, x6, (arg1[3]), (arg2[3])); let mut x9: u32 = 0; let mut x10: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x9, &mut x10, x8, (arg1[4]), (arg2[4])); let mut x11: u32 = 0; let mut x12: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x11, &mut x12, x10, (arg1[5]), (arg2[5])); let mut x13: u32 = 0; let mut x14: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x13, &mut x14, x12, (arg1[6]), (arg2[6])); let mut x15: u32 = 0; let mut x16: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x15, &mut x16, x14, (arg1[7]), (arg2[7])); let mut x17: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x17, x16, (0x0 as u32), 0xffffffff); let mut x18: u32 = 0; let mut x19: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x18, &mut x19, 0x0, x1, (x17 & 0xfffffc2f)); let mut x20: u32 = 0; let mut x21: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x20, &mut x21, x19, x3, (x17 & 0xfffffffe)); let mut x22: u32 = 0; let mut x23: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x22, &mut x23, x21, x5, x17); let mut x24: u32 = 0; let mut x25: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x24, &mut x25, x23, x7, x17); let mut x26: u32 = 0; let mut x27: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x26, &mut x27, x25, x9, x17); let mut x28: u32 = 0; let mut x29: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x28, &mut x29, x27, x11, x17); let mut x30: u32 = 0; let mut x31: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x30, &mut x31, x29, x13, x17); let mut x32: u32 = 0; let mut x33: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x32, &mut x33, x31, x15, x17); out1[0] = x18; out1[1] = x20; out1[2] = x22; out1[3] = x24; out1[4] = x26; out1[5] = x28; out1[6] = x30; out1[7] = x32; } /// The function fiat_secp256k1_opp negates a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_opp(out1: &mut [u32; 8], arg1: &[u32; 8]) -> () { let mut x1: u32 = 0; let mut x2: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x1, &mut x2, 0x0, (0x0 as u32), (arg1[0])); let mut x3: u32 = 0; let mut x4: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x3, &mut x4, x2, (0x0 as u32), (arg1[1])); let mut x5: u32 = 0; let mut x6: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x5, &mut x6, x4, (0x0 as u32), (arg1[2])); let mut x7: u32 = 0; let mut x8: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x7, &mut x8, x6, (0x0 as u32), (arg1[3])); let mut x9: u32 = 0; let mut x10: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x9, &mut x10, x8, (0x0 as u32), (arg1[4])); let mut x11: u32 = 0; let mut x12: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x11, &mut x12, x10, (0x0 as u32), (arg1[5])); let mut x13: u32 = 0; let mut x14: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x13, &mut x14, x12, (0x0 as u32), (arg1[6])); let mut x15: u32 = 0; let mut x16: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x15, &mut x16, x14, (0x0 as u32), (arg1[7])); let mut x17: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x17, x16, (0x0 as u32), 0xffffffff); let mut x18: u32 = 0; let mut x19: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x18, &mut x19, 0x0, x1, (x17 & 0xfffffc2f)); let mut x20: u32 = 0; let mut x21: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x20, &mut x21, x19, x3, (x17 & 0xfffffffe)); let mut x22: u32 = 0; let mut x23: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x22, &mut x23, x21, x5, x17); let mut x24: u32 = 0; let mut x25: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x24, &mut x25, x23, x7, x17); let mut x26: u32 = 0; let mut x27: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x26, &mut x27, x25, x9, x17); let mut x28: u32 = 0; let mut x29: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x28, &mut x29, x27, x11, x17); let mut x30: u32 = 0; let mut x31: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x30, &mut x31, x29, x13, x17); let mut x32: u32 = 0; let mut x33: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x32, &mut x33, x31, x15, x17); out1[0] = x18; out1[1] = x20; out1[2] = x22; out1[3] = x24; out1[4] = x26; out1[5] = x28; out1[6] = x30; out1[7] = x32; } /// The function fiat_secp256k1_from_montgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^8) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_from_montgomery(out1: &mut [u3
{ let x1: u32 = (arg1[0]); let mut x2: u32 = 0; let mut x3: u32 = 0; fiat_secp256k1_mulx_u32(&mut x2, &mut x3, x1, 0xd2253531); let mut x4: u32 = 0; let mut x5: u32 = 0; fiat_secp256k1_mulx_u32(&mut x4, &mut x5, x2, 0xffffffff); let mut x6: u32 = 0; let mut x7: u32 = 0; fiat_secp256k1_mulx_u32(&mut x6, &mut x7, x2, 0xffffffff); let mut x8: u32 = 0; let mut x9: u32 = 0; fiat_secp256k1_mulx_u32(&mut x8, &mut x9, x2, 0xffffffff); let mut x10: u32 = 0; let mut x11: u32 = 0; fiat_secp256k1_mulx_u32(&mut x10, &mut x11, x2, 0xffffffff); let mut x12: u32 = 0; let mut x13: u32 = 0; fiat_secp256k1_mulx_u32(&mut x12, &mut x13, x2, 0xffffffff); let mut x14: u32 = 0; let mut x15: u32 = 0; fiat_secp256k1_mulx_u32(&mut x14, &mut x15, x2, 0xffffffff); let mut x16: u32 = 0; let mut x17: u32 = 0; fiat_secp256k1_mulx_u32(&mut x16, &mut x17, x2, 0xfffffffe); let mut x18: u32 = 0; let mut x19: u32 = 0; fiat_secp256k1_mulx_u32(&mut x18, &mut x19, x2, 0xfffffc2f); let mut x20: u32 = 0; let mut x21: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x20, &mut x21, 0x0, x19, x16); let mut x22: u32 = 0; let mut x23: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x22, &mut x23, x21, x17, x14); let mut x24: u32 = 0; let mut x25: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x24, &mut x25, x23, x15, x12); let mut x26: u32 = 0; let mut x27: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x26, &mut x27, x25, x13, x10); let mut x28: u32 = 0; let mut x29: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x28, &mut x29, x27, x11, x8); let mut x30: u32 = 0; let mut x31: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x30, &mut x31, x29, x9, x6); let mut x32: u32 = 0; let mut x33: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x32, &mut x33, x31, x7, x4); let mut x34: u32 = 0; let mut x35: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x34, &mut x35, 0x0, x1, x18); let mut x36: u32 = 0; let mut x37: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x36, &mut x37, x35, (0x0 as u32), x20); let mut x38: u32 = 0; let mut x39: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x38, &mut x39, x37, (0x0 as u32), x22); let mut x40: u32 = 0; let mut x41: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x40, &mut x41, x39, (0x0 as u32), x24); let mut x42: u32 = 0; let mut x43: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x42, &mut x43, x41, (0x0 as u32), x26); let mut x44: u32 = 0; let mut x45: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x44, &mut x45, x43, (0x0 as u32), x28); let mut x46: u32 = 0; let mut x47: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x46, &mut x47, x45, (0x0 as u32), x30); let mut x48: u32 = 0; let mut x49: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x48, &mut x49, x47, (0x0 as u32), x32); let mut x50: u32 = 0; let mut x51: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x50, &mut x51, x49, (0x0 as u32), ((x33 as u32) + x5)); let mut x52: u32 = 0; let mut x53: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x52, &mut x53, 0x0, x36, (arg1[1])); let mut x54: u32 = 0; let mut x55: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x54, &mut x55, x53, x38, (0x0 as u32)); let mut x56: u32 = 0; let mut x57: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x56, &mut x57, x55, x40, (0x0 as u32)); let mut x58: u32 = 0; let mut x59: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x58, &mut x59, x57, x42, (0x0 as u32)); let mut x60: u32 = 0; let mut x61: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x60, &mut x61, x59, x44, (0x0 as u32)); let mut x62: u32 = 0; let mut x63: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x62, &mut x63, x61, x46, (0x0 as u32)); let mut x64: u32 = 0; let mut x65: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x64, &mut x65, x63, x48, (0x0 as u32)); let mut x66: u32 = 0; let mut x67: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x66, &mut x67, x65, x50, (0x0 as u32)); let mut x68: u32 = 0; let mut x69: u32 = 0; fiat_secp256k1_mulx_u32(&mut x68, &mut x69, x52, 0xd2253531); let mut x70: u32 = 0; let mut x71: u32 = 0; fiat_secp256k1_mulx_u32(&mut x70, &mut x71, x68, 0xffffffff); let mut x72: u32 = 0; let mut x73: u32 = 0; fiat_secp256k1_mulx_u32(&mut x72, &mut x73, x68, 0xffffffff); let mut x74: u32 = 0; let mut x75: u32 = 0; fiat_secp256k1_mulx_u32(&mut x74, &mut x75, x68, 0xffffffff); let mut x76: u32 = 0; let mut x77: u32 = 0; fiat_secp256k1_mulx_u32(&mut x76, &mut x77, x68, 0xffffffff); let mut x78: u32 = 0; let mut x79: u32 = 0; fiat_secp256k1_mulx_u32(&mut x78, &mut x79, x68, 0xffffffff); let mut x80: u32 = 0; let mut x81: u32 = 0; fiat_secp256k1_mulx_u32(&mut x80, &mut x81, x68, 0xffffffff); let mut x82: u32 = 0; let mut x83: u32 = 0; fiat_secp256k1_mulx_u32(&mut x82, &mut x83, x68, 0xfffffffe); let mut x84: u32 = 0; let mut x85: u32 = 0; fiat_secp256k1_mulx_u32(&mut x84, &mut x85, x68, 0xfffffc2f); let mut x86: u32 = 0; let mut x87: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x86, &mut x87, 0x0, x85, x82); let mut x88: u32 = 0; let mut x89: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x88, &mut x89, x87, x83, x80); let mut x90: u32 = 0; let mut x91: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x90, &mut x91, x89, x81, x78); let mut x92: u32 = 0; let mut x93: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x92, &mut x93, x91, x79, x76); let mut x94: u32 = 0; let mut x95: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x94, &mut x95, x93, x77, x74); let mut x96: u32 = 0; let mut x97: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x96, &mut x97, x95, x75, x72); let mut x98: u32 = 0; let mut x99: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x98, &mut x99, x97, x73, x70); let mut x100: u32 = 0; let mut x101: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x100, &mut x101, 0x0, x52, x84); let mut x102: u32 = 0; let mut x103: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x102, &mut x103, x101, x54, x86); let mut x104: u32 = 0; let mut x105: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x104, &mut x105, x103, x56, x88); let mut x106: u32 = 0; let mut x107: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x106, &mut x107, x105, x58, x90); let mut x108: u32 = 0; let mut x109: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x108, &mut x109, x107, x60, x92); let mut x110: u32 = 0; let mut x111: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x110, &mut x111, x109, x62, x94); let mut x112: u32 = 0; let mut x113: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x112, &mut x113, x111, x64, x96); let mut x114: u32 = 0; let mut x115: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x114, &mut x115, x113, x66, x98); let mut x116: u32 = 0; let mut x117: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x116, &mut x117, x115, ((x67 as u32) + (x51 as u32)), ((x99 as u32) + x71)); let mut x118: u32 = 0; let mut x119: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x118, &mut x119, 0x0, x102, (arg1[2])); let mut x120: u32 = 0; let mut x121: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x120, &mut x121, x119, x104, (0x0 as u32)); let mut x122: u32 = 0; let mut x123: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x122, &mut x123, x121, x106, (0x0 as u32)); let mut x124: u32 = 0; let mut x125: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x124, &mut x125, x123, x108, (0x0 as u32)); let mut x126: u32 = 0; let mut x127: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x126, &mut x127, x125, x110, (0x0 as u32)); let mut x128: u32 = 0; let mut x129: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x128, &mut x129, x127, x112, (0x0 as u32)); let mut x130: u32 = 0; let mut x131: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x130, &mut x131, x129, x114, (0x0 as u32)); let mut x132: u32 = 0; let mut x133: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x132, &mut x133, x131, x116, (0x0 as u32)); let mut x134: u32 = 0; let mut x135: u32 = 0; fiat_secp256k1_mulx_u32(&mut x134, &mut x135, x118, 0xd2253531); let mut x136: u32 = 0; let mut x137: u32 = 0; fiat_secp256k1_mulx_u32(&mut x136, &mut x137, x134, 0xffffffff); let mut x138: u32 = 0; let mut x139: u32 = 0; fiat_secp256k1_mulx_u32(&mut x138, &mut x139, x134, 0xffffffff); let mut x140: u32 = 0; let mut x141: u32 = 0; fiat_secp256k1_mulx_u32(&mut x140, &mut x141, x134, 0xffffffff); let mut x142: u32 = 0; let mut x143: u32 = 0; fiat_secp256k1_mulx_u32(&mut x142, &mut x143, x134, 0xffffffff); let mut x144: u32 = 0; let mut x145: u32 = 0; fiat_secp256k1_mulx_u32(&mut x144, &mut x145, x134, 0xffffffff); let mut x146: u32 = 0; let mut x147: u32 = 0; fiat_secp256k1_mulx_u32(&mut x146, &mut x147, x134, 0xffffffff); let mut x148: u32 = 0; let mut x149: u32 = 0; fiat_secp256k1_mulx_u32(&mut x148, &mut x149, x134, 0xfffffffe); let mut x150: u32 = 0; let mut x151: u32 = 0; fiat_secp256k1_mulx_u32(&mut x150, &mut x151, x134, 0xfffffc2f); let mut x152: u32 = 0; let mut x153: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x152, &mut x153, 0x0, x151, x148); let mut x154: u32 = 0; let mut x155: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x154, &mut x155, x153, x149, x146); let mut x156: u32 = 0; let mut x157: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x156, &mut x157, x155, x147, x144); let mut x158: u32 = 0; let mut x159: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x158, &mut x159, x157, x145, x142); let mut x160: u32 = 0; let mut x161: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x160, &mut x161, x159, x143, x140); let mut x162: u32 = 0; let mut x163: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x162, &mut x163, x161, x141, x138); let mut x164: u32 = 0; let mut x165: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x164, &mut x165, x163, x139, x136); let mut x166: u32 = 0; let mut x167: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x166, &mut x167, 0x0, x118, x150); let mut x168: u32 = 0; let mut x169: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x168, &mut x169, x167, x120, x152); let mut x170: u32 = 0; let mut x171: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x170, &mut x171, x169, x122, x154); let mut x172: u32 = 0; let mut x173: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x172, &mut x173, x171, x124, x156); let mut x174: u32 = 0; let mut x175: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x174, &mut x175, x173, x126, x158); let mut x176: u32 = 0; let mut x177: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x176, &mut x177, x175, x128, x160); let mut x178: u32 = 0; let mut x179: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x178, &mut x179, x177, x130, x162); let mut x180: u32 = 0; let mut x181: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x180, &mut x181, x179, x132, x164); let mut x182: u32 = 0; let mut x183: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x182, &mut x183, x181, ((x133 as u32) + (x117 as u32)), ((x165 as u32) + x137)); let mut x184: u32 = 0; let mut x185: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x184, &mut x185, 0x0, x168, (arg1[3])); let mut x186: u32 = 0; let mut x187: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x186, &mut x187, x185, x170, (0x0 as u32)); let mut x188: u32 = 0; let mut x189: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x188, &mut x189, x187, x172, (0x0 as u32)); let mut x190: u32 = 0; let mut x191: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x190, &mut x191, x189, x174, (0x0 as u32)); let mut x192: u32 = 0; let mut x193: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x192, &mut x193, x191, x176, (0x0 as u32)); let mut x194: u32 = 0; let mut x195: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x194, &mut x195, x193, x178, (0x0 as u32)); let mut x196: u32 = 0; let mut x197: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x196, &mut x197, x195, x180, (0x0 as u32)); let mut x198: u32 = 0; let mut x199: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x198, &mut x199, x197, x182, (0x0 as u32)); let mut x200: u32 = 0; let mut x201: u32 = 0; fiat_secp256k1_mulx_u32(&mut x200, &mut x201, x184, 0xd2253531); let mut x202: u32 = 0; let mut x203: u32 = 0; fiat_secp256k1_mulx_u32(&mut x202, &mut x203, x200, 0xffffffff); let mut x204: u32 = 0; let mut x205: u32 = 0; fiat_secp256k1_mulx_u32(&mut x204, &mut x205, x200, 0xffffffff); let mut x206: u32 = 0; let mut x207: u32 = 0; fiat_secp256k1_mulx_u32(&mut x206, &mut x207, x200, 0xffffffff); let mut x208: u32 = 0; let mut x209: u32 = 0; fiat_secp256k1_mulx_u32(&mut x208, &mut x209, x200, 0xffffffff); let mut x210: u32 = 0; let mut x211: u32 = 0; fiat_secp256k1_mulx_u32(&mut x210, &mut x211, x200, 0xffffffff); let mut x212: u32 = 0; let mut x213: u32 = 0; fiat_secp256k1_mulx_u32(&mut x212, &mut x213, x200, 0xffffffff); let mut x214: u32 = 0; let mut x215: u32 = 0; fiat_secp256k1_mulx_u32(&mut x214, &mut x215, x200, 0xfffffffe); let mut x216: u32 = 0; let mut x217: u32 = 0; fiat_secp256k1_mulx_u32(&mut x216, &mut x217, x200, 0xfffffc2f); let mut x218: u32 = 0; let mut x219: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x218, &mut x219, 0x0, x217, x214); let mut x220: u32 = 0; let mut x221: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x220, &mut x221, x219, x215, x212); let mut x222: u32 = 0; let mut x223: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x222, &mut x223, x221, x213, x210); let mut x224: u32 = 0; let mut x225: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x224, &mut x225, x223, x211, x208); let mut x226: u32 = 0; let mut x227: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x226, &mut x227, x225, x209, x206); let mut x228: u32 = 0; let mut x229: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x228, &mut x229, x227, x207, x204); let mut x230: u32 = 0; let mut x231: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x230, &mut x231, x229, x205, x202); let mut x232: u32 = 0; let mut x233: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x232, &mut x233, 0x0, x184, x216); let mut x234: u32 = 0; let mut x235: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x234, &mut x235, x233, x186, x218); let mut x236: u32 = 0; let mut x237: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x236, &mut x237, x235, x188, x220); let mut x238: u32 = 0; let mut x239: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x238, &mut x239, x237, x190, x222); let mut x240: u32 = 0; let mut x241: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x240, &mut x241, x239, x192, x224); let mut x242: u32 = 0; let mut x243: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x242, &mut x243, x241, x194, x226); let mut x244: u32 = 0; let mut x245: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x244, &mut x245, x243, x196, x228); let mut x246: u32 = 0; let mut x247: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x246, &mut x247, x245, x198, x230); let mut x248: u32 = 0; let mut x249: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x248, &mut x249, x247, ((x199 as u32) + (x183 as u32)), ((x231 as u32) + x203)); let mut x250: u32 = 0; let mut x251: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x250, &mut x251, 0x0, x234, (arg1[4])); let mut x252: u32 = 0; let mut x253: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x252, &mut x253, x251, x236, (0x0 as u32)); let mut x254: u32 = 0; let mut x255: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x254, &mut x255, x253, x238, (0x0 as u32)); let mut x256: u32 = 0; let mut x257: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x256, &mut x257, x255, x240, (0x0 as u32)); let mut x258: u32 = 0; let mut x259: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x258, &mut x259, x257, x242, (0x0 as u32)); let mut x260: u32 = 0; let mut x261: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x260, &mut x261, x259, x244, (0x0 as u32)); let mut x262: u32 = 0; let mut x263: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x262, &mut x263, x261, x246, (0x0 as u32)); let mut x264: u32 = 0; let mut x265: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x264, &mut x265, x263, x248, (0x0 as u32)); let mut x266: u32 = 0; let mut x267: u32 = 0; fiat_secp256k1_mulx_u32(&mut x266, &mut x267, x250, 0xd2253531); let mut x268: u32 = 0; let mut x269: u32 = 0; fiat_secp256k1_mulx_u32(&mut x268, &mut x269, x266, 0xffffffff); let mut x270: u32 = 0; let mut x271: u32 = 0; fiat_secp256k1_mulx_u32(&mut x270, &mut x271, x266, 0xffffffff); let mut x272: u32 = 0; let mut x273: u32 = 0; fiat_secp256k1_mulx_u32(&mut x272, &mut x273, x266, 0xffffffff); let mut x274: u32 = 0; let mut x275: u32 = 0; fiat_secp256k1_mulx_u32(&mut x274, &mut x275, x266, 0xffffffff); let mut x276: u32 = 0; let mut x277: u32 = 0; fiat_secp256k1_mulx_u32(&mut x276, &mut x277, x266, 0xffffffff); let mut x278: u32 = 0; let mut x279: u32 = 0; fiat_secp256k1_mulx_u32(&mut x278, &mut x279, x266, 0xffffffff); let mut x280: u32 = 0; let mut x281: u32 = 0; fiat_secp256k1_mulx_u32(&mut x280, &mut x281, x266, 0xfffffffe); let mut x282: u32 = 0; let mut x283: u32 = 0; fiat_secp256k1_mulx_u32(&mut x282, &mut x283, x266, 0xfffffc2f); let mut x284: u32 = 0; let mut x285: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x284, &mut x285, 0x0, x283, x280); let mut x286: u32 = 0; let mut x287: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x286, &mut x287, x285, x281, x278); let mut x288: u32 = 0; let mut x289: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x288, &mut x289, x287, x279, x276); let mut x290: u32 = 0; let mut x291: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x290, &mut x291, x289, x277, x274); let mut x292: u32 = 0; let mut x293: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x292, &mut x293, x291, x275, x272); let mut x294: u32 = 0; let mut x295: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x294, &mut x295, x293, x273, x270); let mut x296: u32 = 0; let mut x297: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x296, &mut x297, x295, x271, x268); let mut x298: u32 = 0; let mut x299: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x298, &mut x299, 0x0, x250, x282); let mut x300: u32 = 0; let mut x301: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x300, &mut x301, x299, x252, x284); let mut x302: u32 = 0; let mut x303: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x302, &mut x303, x301, x254, x286); let mut x304: u32 = 0; let mut x305: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x304, &mut x305, x303, x256, x288); let mut x306: u32 = 0; let mut x307: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x306, &mut x307, x305, x258, x290); let mut x308: u32 = 0; let mut x309: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x308, &mut x309, x307, x260, x292); let mut x310: u32 = 0; let mut x311: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x310, &mut x311, x309, x262, x294); let mut x312: u32 = 0; let mut x313: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x312, &mut x313, x311, x264, x296); let mut x314: u32 = 0; let mut x315: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x314, &mut x315, x313, ((x265 as u32) + (x249 as u32)), ((x297 as u32) + x269)); let mut x316: u32 = 0; let mut x317: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x316, &mut x317, 0x0, x300, (arg1[5])); let mut x318: u32 = 0; let mut x319: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x318, &mut x319, x317, x302, (0x0 as u32)); let mut x320: u32 = 0; let mut x321: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x320, &mut x321, x319, x304, (0x0 as u32)); let mut x322: u32 = 0; let mut x323: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x322, &mut x323, x321, x306, (0x0 as u32)); let mut x324: u32 = 0; let mut x325: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x324, &mut x325, x323, x308, (0x0 as u32)); let mut x326: u32 = 0; let mut x327: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x326, &mut x327, x325, x310, (0x0 as u32)); let mut x328: u32 = 0; let mut x329: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x328, &mut x329, x327, x312, (0x0 as u32)); let mut x330: u32 = 0; let mut x331: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x330, &mut x331, x329, x314, (0x0 as u32)); let mut x332: u32 = 0; let mut x333: u32 = 0; fiat_secp256k1_mulx_u32(&mut x332, &mut x333, x316, 0xd2253531); let mut x334: u32 = 0; let mut x335: u32 = 0; fiat_secp256k1_mulx_u32(&mut x334, &mut x335, x332, 0xffffffff); let mut x336: u32 = 0; let mut x337: u32 = 0; fiat_secp256k1_mulx_u32(&mut x336, &mut x337, x332, 0xffffffff); let mut x338: u32 = 0; let mut x339: u32 = 0; fiat_secp256k1_mulx_u32(&mut x338, &mut x339, x332, 0xffffffff); let mut x340: u32 = 0; let mut x341: u32 = 0; fiat_secp256k1_mulx_u32(&mut x340, &mut x341, x332, 0xffffffff); let mut x342: u32 = 0; let mut x343: u32 = 0; fiat_secp256k1_mulx_u32(&mut x342, &mut x343, x332, 0xffffffff); let mut x344: u32 = 0; let mut x345: u32 = 0; fiat_secp256k1_mulx_u32(&mut x344, &mut x345, x332, 0xffffffff); let mut x346: u32 = 0; let mut x347: u32 = 0; fiat_secp256k1_mulx_u32(&mut x346, &mut x347, x332, 0xfffffffe); let mut x348: u32 = 0; let mut x349: u32 = 0; fiat_secp256k1_mulx_u32(&mut x348, &mut x349, x332, 0xfffffc2f); let mut x350: u32 = 0; let mut x351: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x350, &mut x351, 0x0, x349, x346); let mut x352: u32 = 0; let mut x353: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x352, &mut x353, x351, x347, x344); let mut x354: u32 = 0; let mut x355: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x354, &mut x355, x353, x345, x342); let mut x356: u32 = 0; let mut x357: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x356, &mut x357, x355, x343, x340); let mut x358: u32 = 0; let mut x359: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x358, &mut x359, x357, x341, x338); let mut x360: u32 = 0; let mut x361: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x360, &mut x361, x359, x339, x336); let mut x362: u32 = 0; let mut x363: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x362, &mut x363, x361, x337, x334); let mut x364: u32 = 0; let mut x365: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x364, &mut x365, 0x0, x316, x348); let mut x366: u32 = 0; let mut x367: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x366, &mut x367, x365, x318, x350); let mut x368: u32 = 0; let mut x369: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x368, &mut x369, x367, x320, x352); let mut x370: u32 = 0; let mut x371: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x370, &mut x371, x369, x322, x354); let mut x372: u32 = 0; let mut x373: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x372, &mut x373, x371, x324, x356); let mut x374: u32 = 0; let mut x375: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x374, &mut x375, x373, x326, x358); let mut x376: u32 = 0; let mut x377: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x376, &mut x377, x375, x328, x360); let mut x378: u32 = 0; let mut x379: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x378, &mut x379, x377, x330, x362); let mut x380: u32 = 0; let mut x381: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x380, &mut x381, x379, ((x331 as u32) + (x315 as u32)), ((x363 as u32) + x335)); let mut x382: u32 = 0; let mut x383: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x382, &mut x383, 0x0, x366, (arg1[6])); let mut x384: u32 = 0; let mut x385: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x384, &mut x385, x383, x368, (0x0 as u32)); let mut x386: u32 = 0; let mut x387: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x386, &mut x387, x385, x370, (0x0 as u32)); let mut x388: u32 = 0; let mut x389: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x388, &mut x389, x387, x372, (0x0 as u32)); let mut x390: u32 = 0; let mut x391: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x390, &mut x391, x389, x374, (0x0 as u32)); let mut x392: u32 = 0; let mut x393: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x392, &mut x393, x391, x376, (0x0 as u32)); let mut x394: u32 = 0; let mut x395: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x394, &mut x395, x393, x378, (0x0 as u32)); let mut x396: u32 = 0; let mut x397: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x396, &mut x397, x395, x380, (0x0 as u32)); let mut x398: u32 = 0; let mut x399: u32 = 0; fiat_secp256k1_mulx_u32(&mut x398, &mut x399, x382, 0xd2253531); let mut x400: u32 = 0; let mut x401: u32 = 0; fiat_secp256k1_mulx_u32(&mut x400, &mut x401, x398, 0xffffffff); let mut x402: u32 = 0; let mut x403: u32 = 0; fiat_secp256k1_mulx_u32(&mut x402, &mut x403, x398, 0xffffffff); let mut x404: u32 = 0; let mut x405: u32 = 0; fiat_secp256k1_mulx_u32(&mut x404, &mut x405, x398, 0xffffffff); let mut x406: u32 = 0; let mut x407: u32 = 0; fiat_secp256k1_mulx_u32(&mut x406, &mut x407, x398, 0xffffffff); let mut x408: u32 = 0; let mut x409: u32 = 0; fiat_secp256k1_mulx_u32(&mut x408, &mut x409, x398, 0xffffffff); let mut x410: u32 = 0; let mut x411: u32 = 0; fiat_secp256k1_mulx_u32(&mut x410, &mut x411, x398, 0xffffffff); let mut x412: u32 = 0; let mut x413: u32 = 0; fiat_secp256k1_mulx_u32(&mut x412, &mut x413, x398, 0xfffffffe); let mut x414: u32 = 0; let mut x415: u32 = 0; fiat_secp256k1_mulx_u32(&mut x414, &mut x415, x398, 0xfffffc2f); let mut x416: u32 = 0; let mut x417: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x416, &mut x417, 0x0, x415, x412); let mut x418: u32 = 0; let mut x419: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x418, &mut x419, x417, x413, x410); let mut x420: u32 = 0; let mut x421: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x420, &mut x421, x419, x411, x408); let mut x422: u32 = 0; let mut x423: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x422, &mut x423, x421, x409, x406); let mut x424: u32 = 0; let mut x425: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x424, &mut x425, x423, x407, x404); let mut x426: u32 = 0; let mut x427: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x426, &mut x427, x425, x405, x402); let mut x428: u32 = 0; let mut x429: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x428, &mut x429, x427, x403, x400); let mut x430: u32 = 0; let mut x431: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x430, &mut x431, 0x0, x382, x414); let mut x432: u32 = 0; let mut x433: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x432, &mut x433, x431, x384, x416); let mut x434: u32 = 0; let mut x435: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x434, &mut x435, x433, x386, x418); let mut x436: u32 = 0; let mut x437: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x436, &mut x437, x435, x388, x420); let mut x438: u32 = 0; let mut x439: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x438, &mut x439, x437, x390, x422); let mut x440: u32 = 0; let mut x441: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x440, &mut x441, x439, x392, x424); let mut x442: u32 = 0; let mut x443: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x442, &mut x443, x441, x394, x426); let mut x444: u32 = 0; let mut x445: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x444, &mut x445, x443, x396, x428); let mut x446: u32 = 0; let mut x447: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x446, &mut x447, x445, ((x397 as u32) + (x381 as u32)), ((x429 as u32) + x401)); let mut x448: u32 = 0; let mut x449: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x448, &mut x449, 0x0, x432, (arg1[7])); let mut x450: u32 = 0; let mut x451: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x450, &mut x451, x449, x434, (0x0 as u32)); let mut x452: u32 = 0; let mut x453: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x452, &mut x453, x451, x436, (0x0 as u32)); let mut x454: u32 = 0; let mut x455: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x454, &mut x455, x453, x438, (0x0 as u32)); let mut x456: u32 = 0; let mut x457: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x456, &mut x457, x455, x440, (0x0 as u32)); let mut x458: u32 = 0; let mut x459: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x458, &mut x459, x457, x442, (0x0 as u32)); let mut x460: u32 = 0; let mut x461: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x460, &mut x461, x459, x444, (0x0 as u32)); let mut x462: u32 = 0; let mut x463: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x462, &mut x463, x461, x446, (0x0 as u32)); let mut x464: u32 = 0; let mut x465: u32 = 0; fiat_secp256k1_mulx_u32(&mut x464, &mut x465, x448, 0xd2253531); let mut x466: u32 = 0; let mut x467: u32 = 0; fiat_secp256k1_mulx_u32(&mut x466, &mut x467, x464, 0xffffffff); let mut x468: u32 = 0; let mut x469: u32 = 0; fiat_secp256k1_mulx_u32(&mut x468, &mut x469, x464, 0xffffffff); let mut x470: u32 = 0; let mut x471: u32 = 0; fiat_secp256k1_mulx_u32(&mut x470, &mut x471, x464, 0xffffffff); let mut x472: u32 = 0; let mut x473: u32 = 0; fiat_secp256k1_mulx_u32(&mut x472, &mut x473, x464, 0xffffffff); let mut x474: u32 = 0; let mut x475: u32 = 0; fiat_secp256k1_mulx_u32(&mut x474, &mut x475, x464, 0xffffffff); let mut x476: u32 = 0; let mut x477: u32 = 0; fiat_secp256k1_mulx_u32(&mut x476, &mut x477, x464, 0xffffffff); let mut x478: u32 = 0; let mut x479: u32 = 0; fiat_secp256k1_mulx_u32(&mut x478, &mut x479, x464, 0xfffffffe); let mut x480: u32 = 0; let mut x481: u32 = 0; fiat_secp256k1_mulx_u32(&mut x480, &mut x481, x464, 0xfffffc2f); let mut x482: u32 = 0; let mut x483: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x482, &mut x483, 0x0, x481, x478); let mut x484: u32 = 0; let mut x485: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x484, &mut x485, x483, x479, x476); let mut x486: u32 = 0; let mut x487: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x486, &mut x487, x485, x477, x474); let mut x488: u32 = 0; let mut x489: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x488, &mut x489, x487, x475, x472); let mut x490: u32 = 0; let mut x491: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x490, &mut x491, x489, x473, x470); let mut x492: u32 = 0; let mut x493: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x492, &mut x493, x491, x471, x468); let mut x494: u32 = 0; let mut x495: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x494, &mut x495, x493, x469, x466); let mut x496: u32 = 0; let mut x497: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x496, &mut x497, 0x0, x448, x480); let mut x498: u32 = 0; let mut x499: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x498, &mut x499, x497, x450, x482); let mut x500: u32 = 0; let mut x501: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x500, &mut x501, x499, x452, x484); let mut x502: u32 = 0; let mut x503: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x502, &mut x503, x501, x454, x486); let mut x504: u32 = 0; let mut x505: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x504, &mut x505, x503, x456, x488); let mut x506: u32 = 0; let mut x507: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x506, &mut x507, x505, x458, x490); let mut x508: u32 = 0; let mut x509: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x508, &mut x509, x507, x460, x492); let mut x510: u32 = 0; let mut x511: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x510, &mut x511, x509, x462, x494); let mut x512: u32 = 0; let mut x513: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x512, &mut x513, x511, ((x463 as u32) + (x447 as u32)), ((x495 as u32) + x467)); let mut x514: u32 = 0; let mut x515: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x514, &mut x515, 0x0, x498, 0xfffffc2f); let mut x516: u32 = 0; let mut x517: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x516, &mut x517, x515, x500, 0xfffffffe); let mut x518: u32 = 0; let mut x519: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x518, &mut x519, x517, x502, 0xffffffff); let mut x520: u32 = 0; let mut x521: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x520, &mut x521, x519, x504, 0xffffffff); let mut x522: u32 = 0; let mut x523: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x522, &mut x523, x521, x506, 0xffffffff); let mut x524: u32 = 0; let mut x525: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x524, &mut x525, x523, x508, 0xffffffff); let mut x526: u32 = 0; let mut x527: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x526, &mut x527, x525, x510, 0xffffffff); let mut x528: u32 = 0; let mut x529: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x528, &mut x529, x527, x512, 0xffffffff); let mut x530: u32 = 0; let mut x531: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x530, &mut x531, x529, (x513 as u32), (0x0 as u32)); let mut x532: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x532, x531, x514, x498); let mut x533: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x533, x531, x516, x500); let mut x534: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x534, x531, x518, x502); let mut x535: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x535, x531, x520, x504); let mut x536: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x536, x531, x522, x506); let mut x537: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x537, x531, x524, x508); let mut x538: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x538, x531, x526, x510); let mut x539: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x539, x531, x528, x512); out1[0] = x532; out1[1] = x533; out1[2] = x534; out1[3] = x535; out1[4] = x536; out1[5] = x537; out1[6] = x538; out1[7] = x539; } /// The function fiat_secp256k1_to_montgomery translates a field element into the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_to_montgomery(out1: &mut [u32; 8], arg1: &[u32; 8]) -> () { let x1: u32 = (arg1[1]); let x2: u32 = (arg1[2]); let x3: u32 = (arg1[3]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[5]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[7]); let x8: u32 = (arg1[0]); let mut x9: u32 = 0; let mut x10: u32 = 0; fiat_secp256k1_mulx_u32(&mut x9, &mut x10, x8, 0x7a2); let mut x11: u32 = 0; let mut x12: u32 = 0; fiat_secp256k1_mulx_u32(&mut x11, &mut x12, x8, 0xe90a1); let mut x13: u32 = 0; let mut x14: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x13, &mut x14, 0x0, x12, x9); let mut x15: u32 = 0; let mut x16: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x15, &mut x16, x14, x10, x8); let mut x17: u32 = 0; let mut x18: u32 = 0; fiat_secp256k1_mulx_u32(&mut x17, &mut x18, x11, 0xd2253531); let mut x19: u32 = 0; let mut x20: u32 = 0; fiat_secp256k1_mulx_u32(&mut x19, &mut x20, x17, 0xffffffff); let mut x21: u32 = 0; let mut x22: u32 = 0; fiat_secp256k1_mulx_u32(&mut x21, &mut x22, x17, 0xffffffff); let mut x23: u32 = 0; let mut x24: u32 = 0; fiat_secp256k1_mulx_u32(&mut x23, &mut x24, x17, 0xffffffff); let mut x25: u32 = 0; let mut x26: u32 = 0; fiat_secp256k1_mulx_u32(&mut x25, &mut x26, x17, 0xffffffff); let mut x27: u32 = 0; let mut x28: u32 = 0; fiat_secp256k1_mulx_u32(&mut x27, &mut x28, x17, 0xffffffff); let mut x29: u32 = 0; let mut x30: u32 = 0; fiat_secp256k1_mulx_u32(&mut x29, &mut x30, x17, 0xffffffff); let mut x31: u32 = 0; let mut x32: u32 = 0; fiat_secp256k1_mulx_u32(&mut x31, &mut x32, x17, 0xfffffffe); let mut x33: u32 = 0; let mut x34: u32 = 0; fiat_secp256k1_mulx_u32(&mut x33, &mut x34, x17, 0xfffffc2f); let mut x35: u32 = 0; let mut x36: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x35, &mut x36, 0x0, x34, x31); let mut x37: u32 = 0; let mut x38: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x37, &mut x38, x36, x32, x29); let mut x39: u32 = 0; let mut x40: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x39, &mut x40, x38, x30, x27); let mut x41: u32 = 0; let mut x42: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x41, &mut x42, x40, x28, x25); let mut x43: u32 = 0; let mut x44: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x43, &mut x44, x42, x26, x23); let mut x45: u32 = 0; let mut x46: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x45, &mut x46, x44, x24, x21); let mut x47: u32 = 0; let mut x48: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x47, &mut x48, x46, x22, x19); let mut x49: u32 = 0; let mut x50: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x49, &mut x50, 0x0, x11, x33); let mut x51: u32 = 0; let mut x52: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x51, &mut x52, x50, x13, x35); let mut x53: u32 = 0; let mut x54: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x53, &mut x54, x52, x15, x37); let mut x55: u32 = 0; let mut x56: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x55, &mut x56, x54, (x16 as u32), x39); let mut x57: u32 = 0; let mut x58: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x57, &mut x58, x56, (0x0 as u32), x41); let mut x59: u32 = 0; let mut x60: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x59, &mut x60, x58, (0x0 as u32), x43); let mut x61: u32 = 0; let mut x62: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x61, &mut x62, x60, (0x0 as u32), x45); let mut x63: u32 = 0; let mut x64: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x63, &mut x64, x62, (0x0 as u32), x47); let mut x65: u32 = 0; let mut x66: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x65, &mut x66, x64, (0x0 as u32), ((x48 as u32) + x20)); let mut x67: u32 = 0; let mut x68: u32 = 0; fiat_secp256k1_mulx_u32(&mut x67, &mut x68, x1, 0x7a2); let mut x69: u32 = 0; let mut x70: u32 = 0; fiat_secp256k1_mulx_u32(&mut x69, &mut x70, x1, 0xe90a1); let mut x71: u32 = 0; let mut x72: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x71, &mut x72, 0x0, x70, x67); let mut x73: u32 = 0; let mut x74: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x73, &mut x74, x72, x68, x1); let mut x75: u32 = 0; let mut x76: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x75, &mut x76, 0x0, x51, x69); let mut x77: u32 = 0; let mut x78: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x77, &mut x78, x76, x53, x71); let mut x79: u32 = 0; let mut x80: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x79, &mut x80, x78, x55, x73); let mut x81: u32 = 0; let mut x82: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x81, &mut x82, x80, x57, (x74 as u32)); let mut x83: u32 = 0; let mut x84: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x83, &mut x84, x82, x59, (0x0 as u32)); let mut x85: u32 = 0; let mut x86: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x85, &mut x86, x84, x61, (0x0 as u32)); let mut x87: u32 = 0; let mut x88: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x87, &mut x88, x86, x63, (0x0 as u32)); let mut x89: u32 = 0; let mut x90: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x89, &mut x90, x88, x65, (0x0 as u32)); let mut x91: u32 = 0; let mut x92: u32 = 0; fiat_secp256k1_mulx_u32(&mut x91, &mut x92, x75, 0xd2253531); let mut x93: u32 = 0; let mut x94: u32 = 0; fiat_secp256k1_mulx_u32(&mut x93, &mut x94, x91, 0xffffffff); let mut x95: u32 = 0; let mut x96: u32 = 0; fiat_secp256k1_mulx_u32(&mut x95, &mut x96, x91, 0xffffffff); let mut x97: u32 = 0; let mut x98: u32 = 0; fiat_secp256k1_mulx_u32(&mut x97, &mut x98, x91, 0xffffffff); let mut x99: u32 = 0; let mut x100: u32 = 0; fiat_secp256k1_mulx_u32(&mut x99, &mut x100, x91, 0xffffffff); let mut x101: u32 = 0; let mut x102: u32 = 0; fiat_secp256k1_mulx_u32(&mut x101, &mut x102, x91, 0xffffffff); let mut x103: u32 = 0; let mut x104: u32 = 0; fiat_secp256k1_mulx_u32(&mut x103, &mut x104, x91, 0xffffffff); let mut x105: u32 = 0; let mut x106: u32 = 0; fiat_secp256k1_mulx_u32(&mut x105, &mut x106, x91, 0xfffffffe); let mut x107: u32 = 0; let mut x108: u32 = 0; fiat_secp256k1_mulx_u32(&mut x107, &mut x108, x91, 0xfffffc2f); let mut x109: u32 = 0; let mut x110: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x109, &mut x110, 0x0, x108, x105); let mut x111: u32 = 0; let mut x112: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x111, &mut x112, x110, x106, x103); let mut x113: u32 = 0; let mut x114: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x113, &mut x114, x112, x104, x101); let mut x115: u32 = 0; let mut x116: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x115, &mut x116, x114, x102, x99); let mut x117: u32 = 0; let mut x118: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x117, &mut x118, x116, x100, x97); let mut x119: u32 = 0; let mut x120: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x119, &mut x120, x118, x98, x95); let mut x121: u32 = 0; let mut x122: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x121, &mut x122, x120, x96, x93); let mut x123: u32 = 0; let mut x124: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x123, &mut x124, 0x0, x75, x107); let mut x125: u32 = 0; let mut x126: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x125, &mut x126, x124, x77, x109); let mut x127: u32 = 0; let mut x128: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x127, &mut x128, x126, x79, x111); let mut x129: u32 = 0; let mut x130: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x129, &mut x130, x128, x81, x113); let mut x131: u32 = 0; let mut x132: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x131, &mut x132, x130, x83, x115); let mut x133: u32 = 0; let mut x134: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x133, &mut x134, x132, x85, x117); let mut x135: u32 = 0; let mut x136: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x135, &mut x136, x134, x87, x119); let mut x137: u32 = 0; let mut x138: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x137, &mut x138, x136, x89, x121); let mut x139: u32 = 0; let mut x140: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x139, &mut x140, x138, ((x90 as u32) + (x66 as u32)), ((x122 as u32) + x94)); let mut x141: u32 = 0; let mut x142: u32 = 0; fiat_secp256k1_mulx_u32(&mut x141, &mut x142, x2, 0x7a2); let mut x143: u32 = 0; let mut x144: u32 = 0; fiat_secp256k1_mulx_u32(&mut x143, &mut x144, x2, 0xe90a1); let mut x145: u32 = 0; let mut x146: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x145, &mut x146, 0x0, x144, x141); let mut x147: u32 = 0; let mut x148: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x147, &mut x148, x146, x142, x2); let mut x149: u32 = 0; let mut x150: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x149, &mut x150, 0x0, x125, x143); let mut x151: u32 = 0; let mut x152: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x151, &mut x152, x150, x127, x145); let mut x153: u32 = 0; let mut x154: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x153, &mut x154, x152, x129, x147); let mut x155: u32 = 0; let mut x156: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x155, &mut x156, x154, x131, (x148 as u32)); let mut x157: u32 = 0; let mut x158: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x157, &mut x158, x156, x133, (0x0 as u32)); let mut x159: u32 = 0; let mut x160: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x159, &mut x160, x158, x135, (0x0 as u32)); let mut x161: u32 = 0; let mut x162: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x161, &mut x162, x160, x137, (0x0 as u32)); let mut x163: u32 = 0; let mut x164: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x163, &mut x164, x162, x139, (0x0 as u32)); let mut x165: u32 = 0; let mut x166: u32 = 0; fiat_secp256k1_mulx_u32(&mut x165, &mut x166, x149, 0xd2253531); let mut x167: u32 = 0; let mut x168: u32 = 0; fiat_secp256k1_mulx_u32(&mut x167, &mut x168, x165, 0xffffffff); let mut x169: u32 = 0; let mut x170: u32 = 0; fiat_secp256k1_mulx_u32(&mut x169, &mut x170, x165, 0xffffffff); let mut x171: u32 = 0; let mut x172: u32 = 0; fiat_secp256k1_mulx_u32(&mut x171, &mut x172, x165, 0xffffffff); let mut x173: u32 = 0; let mut x174: u32 = 0; fiat_secp256k1_mulx_u32(&mut x173, &mut x174, x165, 0xffffffff); let mut x175: u32 = 0; let mut x176: u32 = 0; fiat_secp256k1_mulx_u32(&mut x175, &mut x176, x165, 0xffffffff); let mut x177: u32 = 0; let mut x178: u32 = 0; fiat_secp256k1_mulx_u32(&mut x177, &mut x178, x165, 0xffffffff); let mut x179: u32 = 0; let mut x180: u32 = 0; fiat_secp256k1_mulx_u32(&mut x179, &mut x180, x165, 0xfffffffe); let mut x181: u32 = 0; let mut x182: u32 = 0; fiat_secp256k1_mulx_u32(&mut x181, &mut x182, x165, 0xfffffc2f); let mut x183: u32 = 0; let mut x184: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x183, &mut x184, 0x0, x182, x179); let mut x185: u32 = 0; let mut x186: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x185, &mut x186, x184, x180, x177); let mut x187: u32 = 0; let mut x188: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x187, &mut x188, x186, x178, x175); let mut x189: u32 = 0; let mut x190: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x189, &mut x190, x188, x176, x173); let mut x191: u32 = 0; let mut x192: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x191, &mut x192, x190, x174, x171); let mut x193: u32 = 0; let mut x194: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x193, &mut x194, x192, x172, x169); let mut x195: u32 = 0; let mut x196: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x195, &mut x196, x194, x170, x167); let mut x197: u32 = 0; let mut x198: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x197, &mut x198, 0x0, x149, x181); let mut x199: u32 = 0; let mut x200: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x199, &mut x200, x198, x151, x183); let mut x201: u32 = 0; let mut x202: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x201, &mut x202, x200, x153, x185); let mut x203: u32 = 0; let mut x204: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x203, &mut x204, x202, x155, x187); let mut x205: u32 = 0; let mut x206: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x205, &mut x206, x204, x157, x189); let mut x207: u32 = 0; let mut x208: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x207, &mut x208, x206, x159, x191); let mut x209: u32 = 0; let mut x210: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x209, &mut x210, x208, x161, x193); let mut x211: u32 = 0; let mut x212: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x211, &mut x212, x210, x163, x195); let mut x213: u32 = 0; let mut x214: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x213, &mut x214, x212, ((x164 as u32) + (x140 as u32)), ((x196 as u32) + x168)); let mut x215: u32 = 0; let mut x216: u32 = 0; fiat_secp256k1_mulx_u32(&mut x215, &mut x216, x3, 0x7a2); let mut x217: u32 = 0; let mut x218: u32 = 0; fiat_secp256k1_mulx_u32(&mut x217, &mut x218, x3, 0xe90a1); let mut x219: u32 = 0; let mut x220: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x219, &mut x220, 0x0, x218, x215); let mut x221: u32 = 0; let mut x222: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x221, &mut x222, x220, x216, x3); let mut x223: u32 = 0; let mut x224: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x223, &mut x224, 0x0, x199, x217); let mut x225: u32 = 0; let mut x226: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x225, &mut x226, x224, x201, x219); let mut x227: u32 = 0; let mut x228: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x227, &mut x228, x226, x203, x221); let mut x229: u32 = 0; let mut x230: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x229, &mut x230, x228, x205, (x222 as u32)); let mut x231: u32 = 0; let mut x232: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x231, &mut x232, x230, x207, (0x0 as u32)); let mut x233: u32 = 0; let mut x234: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x233, &mut x234, x232, x209, (0x0 as u32)); let mut x235: u32 = 0; let mut x236: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x235, &mut x236, x234, x211, (0x0 as u32)); let mut x237: u32 = 0; let mut x238: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x237, &mut x238, x236, x213, (0x0 as u32)); let mut x239: u32 = 0; let mut x240: u32 = 0; fiat_secp256k1_mulx_u32(&mut x239, &mut x240, x223, 0xd2253531); let mut x241: u32 = 0; let mut x242: u32 = 0; fiat_secp256k1_mulx_u32(&mut x241, &mut x242, x239, 0xffffffff); let mut x243: u32 = 0; let mut x244: u32 = 0; fiat_secp256k1_mulx_u32(&mut x243, &mut x244, x239, 0xffffffff); let mut x245: u32 = 0; let mut x246: u32 = 0; fiat_secp256k1_mulx_u32(&mut x245, &mut x246, x239, 0xffffffff); let mut x247: u32 = 0; let mut x248: u32 = 0; fiat_secp256k1_mulx_u32(&mut x247, &mut x248, x239, 0xffffffff); let mut x249: u32 = 0; let mut x250: u32 = 0; fiat_secp256k1_mulx_u32(&mut x249, &mut x250, x239, 0xffffffff); let mut x251: u32 = 0; let mut x252: u32 = 0; fiat_secp256k1_mulx_u32(&mut x251, &mut x252, x239, 0xffffffff); let mut x253: u32 = 0; let mut x254: u32 = 0; fiat_secp256k1_mulx_u32(&mut x253, &mut x254, x239, 0xfffffffe); let mut x255: u32 = 0; let mut x256: u32 = 0; fiat_secp256k1_mulx_u32(&mut x255, &mut x256, x239, 0xfffffc2f); let mut x257: u32 = 0; let mut x258: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x257, &mut x258, 0x0, x256, x253); let mut x259: u32 = 0; let mut x260: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x259, &mut x260, x258, x254, x251); let mut x261: u32 = 0; let mut x262: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x261, &mut x262, x260, x252, x249); let mut x263: u32 = 0; let mut x264: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x263, &mut x264, x262, x250, x247); let mut x265: u32 = 0; let mut x266: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x265, &mut x266, x264, x248, x245); let mut x267: u32 = 0; let mut x268: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x267, &mut x268, x266, x246, x243); let mut x269: u32 = 0; let mut x270: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x269, &mut x270, x268, x244, x241); let mut x271: u32 = 0; let mut x272: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x271, &mut x272, 0x0, x223, x255); let mut x273: u32 = 0; let mut x274: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x273, &mut x274, x272, x225, x257); let mut x275: u32 = 0; let mut x276: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x275, &mut x276, x274, x227, x259); let mut x277: u32 = 0; let mut x278: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x277, &mut x278, x276, x229, x261); let mut x279: u32 = 0; let mut x280: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x279, &mut x280, x278, x231, x263); let mut x281: u32 = 0; let mut x282: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x281, &mut x282, x280, x233, x265); let mut x283: u32 = 0; let mut x284: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x283, &mut x284, x282, x235, x267); let mut x285: u32 = 0; let mut x286: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x285, &mut x286, x284, x237, x269); let mut x287: u32 = 0; let mut x288: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x287, &mut x288, x286, ((x238 as u32) + (x214 as u32)), ((x270 as u32) + x242)); let mut x289: u32 = 0; let mut x290: u32 = 0; fiat_secp256k1_mulx_u32(&mut x289, &mut x290, x4, 0x7a2); let mut x291: u32 = 0; let mut x292: u32 = 0; fiat_secp256k1_mulx_u32(&mut x291, &mut x292, x4, 0xe90a1); let mut x293: u32 = 0; let mut x294: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x293, &mut x294, 0x0, x292, x289); let mut x295: u32 = 0; let mut x296: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x295, &mut x296, x294, x290, x4); let mut x297: u32 = 0; let mut x298: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x297, &mut x298, 0x0, x273, x291); let mut x299: u32 = 0; let mut x300: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x299, &mut x300, x298, x275, x293); let mut x301: u32 = 0; let mut x302: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x301, &mut x302, x300, x277, x295); let mut x303: u32 = 0; let mut x304: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x303, &mut x304, x302, x279, (x296 as u32)); let mut x305: u32 = 0; let mut x306: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x305, &mut x306, x304, x281, (0x0 as u32)); let mut x307: u32 = 0; let mut x308: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x307, &mut x308, x306, x283, (0x0 as u32)); let mut x309: u32 = 0; let mut x310: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x309, &mut x310, x308, x285, (0x0 as u32)); let mut x311: u32 = 0; let mut x312: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x311, &mut x312, x310, x287, (0x0 as u32)); let mut x313: u32 = 0; let mut x314: u32 = 0; fiat_secp256k1_mulx_u32(&mut x313, &mut x314, x297, 0xd2253531); let mut x315: u32 = 0; let mut x316: u32 = 0; fiat_secp256k1_mulx_u32(&mut x315, &mut x316, x313, 0xffffffff); let mut x317: u32 = 0; let mut x318: u32 = 0; fiat_secp256k1_mulx_u32(&mut x317, &mut x318, x313, 0xffffffff); let mut x319: u32 = 0; let mut x320: u32 = 0; fiat_secp256k1_mulx_u32(&mut x319, &mut x320, x313, 0xffffffff); let mut x321: u32 = 0; let mut x322: u32 = 0; fiat_secp256k1_mulx_u32(&mut x321, &mut x322, x313, 0xffffffff); let mut x323: u32 = 0; let mut x324: u32 = 0; fiat_secp256k1_mulx_u32(&mut x323, &mut x324, x313, 0xffffffff); let mut x325: u32 = 0; let mut x326: u32 = 0; fiat_secp256k1_mulx_u32(&mut x325, &mut x326, x313, 0xffffffff); let mut x327: u32 = 0; let mut x328: u32 = 0; fiat_secp256k1_mulx_u32(&mut x327, &mut x328, x313, 0xfffffffe); let mut x329: u32 = 0; let mut x330: u32 = 0; fiat_secp256k1_mulx_u32(&mut x329, &mut x330, x313, 0xfffffc2f); let mut x331: u32 = 0; let mut x332: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x331, &mut x332, 0x0, x330, x327); let mut x333: u32 = 0; let mut x334: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x333, &mut x334, x332, x328, x325); let mut x335: u32 = 0; let mut x336: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x335, &mut x336, x334, x326, x323); let mut x337: u32 = 0; let mut x338: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x337, &mut x338, x336, x324, x321); let mut x339: u32 = 0; let mut x340: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x339, &mut x340, x338, x322, x319); let mut x341: u32 = 0; let mut x342: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x341, &mut x342, x340, x320, x317); let mut x343: u32 = 0; let mut x344: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x343, &mut x344, x342, x318, x315); let mut x345: u32 = 0; let mut x346: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x345, &mut x346, 0x0, x297, x329); let mut x347: u32 = 0; let mut x348: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x347, &mut x348, x346, x299, x331); let mut x349: u32 = 0; let mut x350: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x349, &mut x350, x348, x301, x333); let mut x351: u32 = 0; let mut x352: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x351, &mut x352, x350, x303, x335); let mut x353: u32 = 0; let mut x354: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x353, &mut x354, x352, x305, x337); let mut x355: u32 = 0; let mut x356: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x355, &mut x356, x354, x307, x339); let mut x357: u32 = 0; let mut x358: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x357, &mut x358, x356, x309, x341); let mut x359: u32 = 0; let mut x360: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x359, &mut x360, x358, x311, x343); let mut x361: u32 = 0; let mut x362: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x361, &mut x362, x360, ((x312 as u32) + (x288 as u32)), ((x344 as u32) + x316)); let mut x363: u32 = 0; let mut x364: u32 = 0; fiat_secp256k1_mulx_u32(&mut x363, &mut x364, x5, 0x7a2); let mut x365: u32 = 0; let mut x366: u32 = 0; fiat_secp256k1_mulx_u32(&mut x365, &mut x366, x5, 0xe90a1); let mut x367: u32 = 0; let mut x368: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x367, &mut x368, 0x0, x366, x363); let mut x369: u32 = 0; let mut x370: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x369, &mut x370, x368, x364, x5); let mut x371: u32 = 0; let mut x372: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x371, &mut x372, 0x0, x347, x365); let mut x373: u32 = 0; let mut x374: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x373, &mut x374, x372, x349, x367); let mut x375: u32 = 0; let mut x376: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x375, &mut x376, x374, x351, x369); let mut x377: u32 = 0; let mut x378: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x377, &mut x378, x376, x353, (x370 as u32)); let mut x379: u32 = 0; let mut x380: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x379, &mut x380, x378, x355, (0x0 as u32)); let mut x381: u32 = 0; let mut x382: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x381, &mut x382, x380, x357, (0x0 as u32)); let mut x383: u32 = 0; let mut x384: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x383, &mut x384, x382, x359, (0x0 as u32)); let mut x385: u32 = 0; let mut x386: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x385, &mut x386, x384, x361, (0x0 as u32)); let mut x387: u32 = 0; let mut x388: u32 = 0; fiat_secp256k1_mulx_u32(&mut x387, &mut x388, x371, 0xd2253531); let mut x389: u32 = 0; let mut x390: u32 = 0; fiat_secp256k1_mulx_u32(&mut x389, &mut x390, x387, 0xffffffff); let mut x391: u32 = 0; let mut x392: u32 = 0; fiat_secp256k1_mulx_u32(&mut x391, &mut x392, x387, 0xffffffff); let mut x393: u32 = 0; let mut x394: u32 = 0; fiat_secp256k1_mulx_u32(&mut x393, &mut x394, x387, 0xffffffff); let mut x395: u32 = 0; let mut x396: u32 = 0; fiat_secp256k1_mulx_u32(&mut x395, &mut x396, x387, 0xffffffff); let mut x397: u32 = 0; let mut x398: u32 = 0; fiat_secp256k1_mulx_u32(&mut x397, &mut x398, x387, 0xffffffff); let mut x399: u32 = 0; let mut x400: u32 = 0; fiat_secp256k1_mulx_u32(&mut x399, &mut x400, x387, 0xffffffff); let mut x401: u32 = 0; let mut x402: u32 = 0; fiat_secp256k1_mulx_u32(&mut x401, &mut x402, x387, 0xfffffffe); let mut x403: u32 = 0; let mut x404: u32 = 0; fiat_secp256k1_mulx_u32(&mut x403, &mut x404, x387, 0xfffffc2f); let mut x405: u32 = 0; let mut x406: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x405, &mut x406, 0x0, x404, x401); let mut x407: u32 = 0; let mut x408: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x407, &mut x408, x406, x402, x399); let mut x409: u32 = 0; let mut x410: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x409, &mut x410, x408, x400, x397); let mut x411: u32 = 0; let mut x412: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x411, &mut x412, x410, x398, x395); let mut x413: u32 = 0; let mut x414: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x413, &mut x414, x412, x396, x393); let mut x415: u32 = 0; let mut x416: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x415, &mut x416, x414, x394, x391); let mut x417: u32 = 0; let mut x418: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x417, &mut x418, x416, x392, x389); let mut x419: u32 = 0; let mut x420: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x419, &mut x420, 0x0, x371, x403); let mut x421: u32 = 0; let mut x422: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x421, &mut x422, x420, x373, x405); let mut x423: u32 = 0; let mut x424: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x423, &mut x424, x422, x375, x407); let mut x425: u32 = 0; let mut x426: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x425, &mut x426, x424, x377, x409); let mut x427: u32 = 0; let mut x428: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x427, &mut x428, x426, x379, x411); let mut x429: u32 = 0; let mut x430: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x429, &mut x430, x428, x381, x413); let mut x431: u32 = 0; let mut x432: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x431, &mut x432, x430, x383, x415); let mut x433: u32 = 0; let mut x434: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x433, &mut x434, x432, x385, x417); let mut x435: u32 = 0; let mut x436: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x435, &mut x436, x434, ((x386 as u32) + (x362 as u32)), ((x418 as u32) + x390)); let mut x437: u32 = 0; let mut x438: u32 = 0; fiat_secp256k1_mulx_u32(&mut x437, &mut x438, x6, 0x7a2); let mut x439: u32 = 0; let mut x440: u32 = 0; fiat_secp256k1_mulx_u32(&mut x439, &mut x440, x6, 0xe90a1); let mut x441: u32 = 0; let mut x442: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x441, &mut x442, 0x0, x440, x437); let mut x443: u32 = 0; let mut x444: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x443, &mut x444, x442, x438, x6); let mut x445: u32 = 0; let mut x446: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x445, &mut x446, 0x0, x421, x439); let mut x447: u32 = 0; let mut x448: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x447, &mut x448, x446, x423, x441); let mut x449: u32 = 0; let mut x450: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x449, &mut x450, x448, x425, x443); let mut x451: u32 = 0; let mut x452: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x451, &mut x452, x450, x427, (x444 as u32)); let mut x453: u32 = 0; let mut x454: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x453, &mut x454, x452, x429, (0x0 as u32)); let mut x455: u32 = 0; let mut x456: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x455, &mut x456, x454, x431, (0x0 as u32)); let mut x457: u32 = 0; let mut x458: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x457, &mut x458, x456, x433, (0x0 as u32)); let mut x459: u32 = 0; let mut x460: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x459, &mut x460, x458, x435, (0x0 as u32)); let mut x461: u32 = 0; let mut x462: u32 = 0; fiat_secp256k1_mulx_u32(&mut x461, &mut x462, x445, 0xd2253531); let mut x463: u32 = 0; let mut x464: u32 = 0; fiat_secp256k1_mulx_u32(&mut x463, &mut x464, x461, 0xffffffff); let mut x465: u32 = 0; let mut x466: u32 = 0; fiat_secp256k1_mulx_u32(&mut x465, &mut x466, x461, 0xffffffff); let mut x467: u32 = 0; let mut x468: u32 = 0; fiat_secp256k1_mulx_u32(&mut x467, &mut x468, x461, 0xffffffff); let mut x469: u32 = 0; let mut x470: u32 = 0; fiat_secp256k1_mulx_u32(&mut x469, &mut x470, x461, 0xffffffff); let mut x471: u32 = 0; let mut x472: u32 = 0; fiat_secp256k1_mulx_u32(&mut x471, &mut x472, x461, 0xffffffff); let mut x473: u32 = 0; let mut x474: u32 = 0; fiat_secp256k1_mulx_u32(&mut x473, &mut x474, x461, 0xffffffff); let mut x475: u32 = 0; let mut x476: u32 = 0; fiat_secp256k1_mulx_u32(&mut x475, &mut x476, x461, 0xfffffffe); let mut x477: u32 = 0; let mut x478: u32 = 0; fiat_secp256k1_mulx_u32(&mut x477, &mut x478, x461, 0xfffffc2f); let mut x479: u32 = 0; let mut x480: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x479, &mut x480, 0x0, x478, x475); let mut x481: u32 = 0; let mut x482: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x481, &mut x482, x480, x476, x473); let mut x483: u32 = 0; let mut x484: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x483, &mut x484, x482, x474, x471); let mut x485: u32 = 0; let mut x486: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x485, &mut x486, x484, x472, x469); let mut x487: u32 = 0; let mut x488: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x487, &mut x488, x486, x470, x467); let mut x489: u32 = 0; let mut x490: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x489, &mut x490, x488, x468, x465); let mut x491: u32 = 0; let mut x492: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x491, &mut x492, x490, x466, x463); let mut x493: u32 = 0; let mut x494: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x493, &mut x494, 0x0, x445, x477); let mut x495: u32 = 0; let mut x496: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x495, &mut x496, x494, x447, x479); let mut x497: u32 = 0; let mut x498: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x497, &mut x498, x496, x449, x481); let mut x499: u32 = 0; let mut x500: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x499, &mut x500, x498, x451, x483); let mut x501: u32 = 0; let mut x502: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x501, &mut x502, x500, x453, x485); let mut x503: u32 = 0; let mut x504: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x503, &mut x504, x502, x455, x487); let mut x505: u32 = 0; let mut x506: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x505, &mut x506, x504, x457, x489); let mut x507: u32 = 0; let mut x508: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x507, &mut x508, x506, x459, x491); let mut x509: u32 = 0; let mut x510: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x509, &mut x510, x508, ((x460 as u32) + (x436 as u32)), ((x492 as u32) + x464)); let mut x511: u32 = 0; let mut x512: u32 = 0; fiat_secp256k1_mulx_u32(&mut x511, &mut x512, x7, 0x7a2); let mut x513: u32 = 0; let mut x514: u32 = 0; fiat_secp256k1_mulx_u32(&mut x513, &mut x514, x7, 0xe90a1); let mut x515: u32 = 0; let mut x516: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x515, &mut x516, 0x0, x514, x511); let mut x517: u32 = 0; let mut x518: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x517, &mut x518, x516, x512, x7); let mut x519: u32 = 0; let mut x520: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x519, &mut x520, 0x0, x495, x513); let mut x521: u32 = 0; let mut x522: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x521, &mut x522, x520, x497, x515); let mut x523: u32 = 0; let mut x524: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x523, &mut x524, x522, x499, x517); let mut x525: u32 = 0; let mut x526: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x525, &mut x526, x524, x501, (x518 as u32)); let mut x527: u32 = 0; let mut x528: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x527, &mut x528, x526, x503, (0x0 as u32)); let mut x529: u32 = 0; let mut x530: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x529, &mut x530, x528, x505, (0x0 as u32)); let mut x531: u32 = 0; let mut x532: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x531, &mut x532, x530, x507, (0x0 as u32)); let mut x533: u32 = 0; let mut x534: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x533, &mut x534, x532, x509, (0x0 as u32)); let mut x535: u32 = 0; let mut x536: u32 = 0; fiat_secp256k1_mulx_u32(&mut x535, &mut x536, x519, 0xd2253531); let mut x537: u32 = 0; let mut x538: u32 = 0; fiat_secp256k1_mulx_u32(&mut x537, &mut x538, x535, 0xffffffff); let mut x539: u32 = 0; let mut x540: u32 = 0; fiat_secp256k1_mulx_u32(&mut x539, &mut x540, x535, 0xffffffff); let mut x541: u32 = 0; let mut x542: u32 = 0; fiat_secp256k1_mulx_u32(&mut x541, &mut x542, x535, 0xffffffff); let mut x543: u32 = 0; let mut x544: u32 = 0; fiat_secp256k1_mulx_u32(&mut x543, &mut x544, x535, 0xffffffff); let mut x545: u32 = 0; let mut x546: u32 = 0; fiat_secp256k1_mulx_u32(&mut x545, &mut x546, x535, 0xffffffff); let mut x547: u32 = 0; let mut x548: u32 = 0; fiat_secp256k1_mulx_u32(&mut x547, &mut x548, x535, 0xffffffff); let mut x549: u32 = 0; let mut x550: u32 = 0; fiat_secp256k1_mulx_u32(&mut x549, &mut x550, x535, 0xfffffffe); let mut x551: u32 = 0; let mut x552: u32 = 0; fiat_secp256k1_mulx_u32(&mut x551, &mut x552, x535, 0xfffffc2f); let mut x553: u32 = 0; let mut x554: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x553, &mut x554, 0x0, x552, x549); let mut x555: u32 = 0; let mut x556: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x555, &mut x556, x554, x550, x547); let mut x557: u32 = 0; let mut x558: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x557, &mut x558, x556, x548, x545); let mut x559: u32 = 0; let mut x560: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x559, &mut x560, x558, x546, x543); let mut x561: u32 = 0; let mut x562: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x561, &mut x562, x560, x544, x541); let mut x563: u32 = 0; let mut x564: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x563, &mut x564, x562, x542, x539); let mut x565: u32 = 0; let mut x566: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x565, &mut x566, x564, x540, x537); let mut x567: u32 = 0; let mut x568: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x567, &mut x568, 0x0, x519, x551); let mut x569: u32 = 0; let mut x570: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x569, &mut x570, x568, x521, x553); let mut x571: u32 = 0; let mut x572: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x571, &mut x572, x570, x523, x555); let mut x573: u32 = 0; let mut x574: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x573, &mut x574, x572, x525, x557); let mut x575: u32 = 0; let mut x576: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x575, &mut x576, x574, x527, x559); let mut x577: u32 = 0; let mut x578: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x577, &mut x578, x576, x529, x561); let mut x579: u32 = 0; let mut x580: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x579, &mut x580, x578, x531, x563); let mut x581: u32 = 0; let mut x582: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x581, &mut x582, x580, x533, x565); let mut x583: u32 = 0; let mut x584: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x583, &mut x584, x582, ((x534 as u32) + (x510 as u32)), ((x566 as u32) + x538)); let mut x585: u32 = 0; let mut x586: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x585, &mut x586, 0x0, x569, 0xfffffc2f); let mut x587: u32 = 0; let mut x588: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x587, &mut x588, x586, x571, 0xfffffffe); let mut x589: u32 = 0; let mut x590: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x589, &mut x590, x588, x573, 0xffffffff); let mut x591: u32 = 0; let mut x592: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x591, &mut x592, x590, x575, 0xffffffff); let mut x593: u32 = 0; let mut x594: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x593, &mut x594, x592, x577, 0xffffffff); let mut x595: u32 = 0; let mut x596: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x595, &mut x596, x594, x579, 0xffffffff); let mut x597: u32 = 0; let mut x598: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x597, &mut x598, x596, x581, 0xffffffff); let mut x599: u32 = 0; let mut x600: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x599, &mut x600, x598, x583, 0xffffffff); let mut x601: u32 = 0; let mut x602: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x601, &mut x602, x600, (x584 as u32), (0x0 as u32)); let mut x603: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x603, x602, x585, x569); let mut x604: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x604, x602, x587, x571); let mut x605: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x605, x602, x589, x573); let mut x606: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x606, x602, x591, x575); let mut x607: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x607, x602, x593, x577); let mut x608: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x608, x602, x595, x579); let mut x609: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x609, x602, x597, x581); let mut x610: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x610, x602, x599, x583); out1[0] = x603; out1[1] = x604; out1[2] = x605; out1[3] = x606; out1[4] = x607; out1[5] = x608; out1[6] = x609; out1[7] = x610; } /// The function fiat_secp256k1_nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] #[inline] pub fn fiat_secp256k1_nonzero(out1: &mut u32, arg1: &[u32; 8]) -> () { let x1: u32 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | ((arg1[6]) | (arg1[7])))))))); *out1 = x1; } /// The function fiat_secp256k1_selectznz is a multi-limb conditional select. /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_selectznz(out1: &mut [u32; 8], arg1: fiat_secp256k1_u1, arg2: &[u32; 8], arg3: &[u32; 8]) -> () { let mut x1: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x1, arg1, (arg2[0]), (arg3[0])); let mut x2: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x2, arg1, (arg2[1]), (arg3[1])); let mut x3: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x3, arg1, (arg2[2]), (arg3[2])); let mut x4: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x4, arg1, (arg2[3]), (arg3[3])); let mut x5: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x5, arg1, (arg2[4]), (arg3[4])); let mut x6: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x6, arg1, (arg2[5]), (arg3[5])); let mut x7: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x7, arg1, (arg2[6]), (arg3[6])); let mut x8: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x8, arg1, (arg2[7]), (arg3[7])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; } /// The function fiat_secp256k1_to_bytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] #[inline] pub fn fiat_secp256k1_to_bytes(out1: &mut [u8; 32], arg1: &[u32; 8]) -> () { let x1: u32 = (arg1[7]); let x2: u32 = (arg1[6]); let x3: u32 = (arg1[5]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[3]); let x6: u32 = (arg1[2]); let x7: u32 = (arg1[1]); let x8: u32 = (arg1[0]); let x9: u8 = ((x8 & (0xff as u32)) as u8); let x10: u32 = (x8 >> 8); let x11: u8 = ((x10 & (0xff as u32)) as u8); let x12: u32 = (x10 >> 8); let x13: u8 = ((x12 & (0xff as u32)) as u8); let x14: u8 = ((x12 >> 8) as u8); let x15: u8 = ((x7 & (0xff as u32)) as u8); let x16: u32 = (x7 >> 8); let x17: u8 = ((x16 & (0xff as u32)) as u8); let x18: u32 = (x16 >> 8); let x19: u8 = ((x18 & (0xff as u32)) as u8); let x20: u8 = ((x18 >> 8) as u8); let x21: u8 = ((x6 & (0xff as u32)) as u8); let x22: u32 = (x6 >> 8); let x23: u8 = ((x22 & (0xff as u32)) as u8); let x24: u32 = (x22 >> 8); let x25: u8 = ((x24 & (0xff as u32)) as u8); let x26: u8 = ((x24 >> 8) as u8); let x27: u8 = ((x5 & (0xff as u32)) as u8); let x28: u32 = (x5 >> 8); let x29: u8 = ((x28 & (0xff as u32)) as u8); let x30: u32 = (x28 >> 8); let x31: u8 = ((x30 & (0xff as u32)) as u8); let x32: u8 = ((x30 >> 8) as u8); let x33: u8 = ((x4 & (0xff as u32)) as u8); let x34: u32 = (x4 >> 8); let x35: u8 = ((x34 & (0xff as u32)) as u8); let x36: u32 = (x34 >> 8); let x37: u8 = ((x36 & (0xff as u32)) as u8); let x38: u8 = ((x36 >> 8) as u8); let x39: u8 = ((x3 & (0xff as u32)) as u8); let x40: u32 = (x3 >> 8); let x41: u8 = ((x40 & (0xff as u32)) as u8); let x42: u32 = (x40 >> 8); let x43: u8 = ((x42 & (0xff as u32)) as u8); let x44: u8 = ((x42 >> 8) as u8); let x45: u8 = ((x2 & (0xff as u32)) as u8); let x46: u32 = (x2 >> 8); let x47: u8 = ((x46 & (0xff as u32)) as u8); let x48: u32 = (x46 >> 8); let x49: u8 = ((x48 & (0xff as u32)) as u8); let x50: u8 = ((x48 >> 8) as u8); let x51: u8 = ((x1 & (0xff as u32)) as u8); let x52: u32 = (x1 >> 8); let x53: u8 = ((x52 & (0xff as u32)) as u8); let x54: u32 = (x52 >> 8); let x55: u8 = ((x54 & (0xff as u32)) as u8); let x56: u8 = ((x54 >> 8) as u8); out1[0] = x9; out1[1] = x11; out1[2] = x13; out1[3] = x14; out1[4] = x15; out1[5] = x17; out1[6] = x19; out1[7] = x20; out1[8] = x21; out1[9] = x23; out1[10] = x25; out1[11] = x26; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x38; out1[20] = x39; out1[21] = x41; out1[22] = x43; out1[23] = x44; out1[24] = x45; out1[25] = x47; out1[26] = x49; out1[27] = x50; out1[28] = x51; out1[29] = x53; out1[30] = x55; out1[31] = x56; } /// The function fiat_secp256k1_from_bytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_from_bytes(out1: &mut [u32; 8], arg1: &[u8; 32]) -> () { let x1: u32 = (((arg1[31]) as u32) << 24); let x2: u32 = (((arg1[30]) as u32) << 16); let x3: u32 = (((arg1[29]) as u32) << 8); let x4: u8 = (arg1[28]); let x5: u32 = (((arg1[27]) as u32) << 24); let x6: u32 = (((arg1[26]) as u32) << 16); let x7: u32 = (((arg1[25]) as u32) << 8); let x8: u8 = (arg1[24]); let x9: u32 = (((arg1[23]) as u32) << 24); let x10: u32 = (((arg1[22]) as u32) << 16); let x11: u32 = (((arg1[21]) as u32) << 8); let x12: u8 = (arg1[20]); let x13: u32 = (((arg1[19]) as u32) << 24); let x14: u32 = (((arg1[18]) as u32) << 16); let x15: u32 = (((arg1[17]) as u32) << 8); let x16: u8 = (arg1[16]); let x17: u32 = (((arg1[15]) as u32) << 24); let x18: u32 = (((arg1[14]) as u32) << 16); let x19: u32 = (((arg1[13]) as u32) << 8); let x20: u8 = (arg1[12]); let x21: u32 = (((arg1[11]) as u32) << 24); let x22: u32 = (((arg1[10]) as u32) << 16); let x23: u32 = (((arg1[9]) as u32) << 8); let x24: u8 = (arg1[8]); let x25: u32 = (((arg1[7]) as u32) << 24); let x26: u32 = (((arg1[6]) as u32) << 16); let x27: u32 = (((arg1[5]) as u32) << 8); let x28: u8 = (arg1[4]); let x29: u32 = (((arg1[3]) as u32) << 24); let x30: u32 = (((arg1[2]) as u32) << 16); let x31: u32 = (((arg1[1]) as u32) << 8); let x32: u8 = (arg1[0]); let x33: u32 = (x31 + (x32 as u32)); let x34: u32 = (x30 + x33); let x35: u32 = (x29 + x34); let x36: u32 = (x27 + (x28 as u32)); let x37: u32 = (x26 + x36); let x38: u32 = (x25 + x37); let x39: u32 = (x23 + (x24 as u32)); let x40: u32 = (x22 + x39); let x41: u32 = (x21 + x40); let x42: u32 = (x19 + (x20 as u32)); let x43: u32 = (x18 + x42); let x44: u32 = (x17 + x43); let x45: u32 = (x15 + (x16 as u32)); let x46: u32 = (x14 + x45); let x47: u32 = (x13 + x46); let x48: u32 = (x11 + (x12 as u32)); let x49: u32 = (x10 + x48); let x50: u32 = (x9 + x49); let x51: u32 = (x7 + (x8 as u32)); let x52: u32 = (x6 + x51); let x53: u32 = (x5 + x52); let x54: u32 = (x3 + (x4 as u32)); let x55: u32 = (x2 + x54); let x56: u32 = (x1 + x55); out1[0] = x35; out1[1] = x38; out1[2] = x41; out1[3] = x44; out1[4] = x47; out1[5] = x50; out1[6] = x53; out1[7] = x56; } /// The function fiat_secp256k1_set_one returns the field element one in the Montgomery domain. /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_set_one(out1: &mut [u32; 8]) -> () { out1[0] = 0x3d1; out1[1] = (0x1 as u32); out1[2] = (0x0 as u32); out1[3] = (0x0 as u32); out1[4] = (0x0 as u32); out1[5] = (0x0 as u32); out1[6] = (0x0 as u32); out1[7] = (0x0 as u32); } /// The function fiat_secp256k1_msat returns the saturated representation of the prime modulus. /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_msat(out1: &mut [u32; 9]) -> () { out1[0] = 0xfffffc2f; out1[1] = 0xfffffffe; out1[2] = 0xffffffff; out1[3] = 0xffffffff; out1[4] = 0xffffffff; out1[5] = 0xffffffff; out1[6] = 0xffffffff; out1[7] = 0xffffffff; out1[8] = (0x0 as u32); } /// The function fiat_secp256k1_divstep computes a divstep. /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_divstep(out1: &mut u32, out2: &mut [u32; 9], out3: &mut [u32; 9], out4: &mut [u32; 8], out5: &mut [u32; 8], arg1: u32, arg2: &[u32; 9], arg3: &[u32; 9], arg4: &[u32; 8], arg5: &[u32; 8]) -> () { let mut x1: u32 = 0; let mut x2: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x1, &mut x2, 0x0, (!arg1), (0x1 as u32)); let x3: fiat_secp256k1_u1 = (((x1 >> 31) as fiat_secp256k1_u1) & (((arg3[0]) & (0x1 as u32)) as fiat_secp256k1_u1)); let mut x4: u32 = 0; let mut x5: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x4, &mut x5, 0x0, (!arg1), (0x1 as u32)); let mut x6: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x6, x3, arg1, x4); let mut x7: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x7, x3, (arg2[0]), (arg3[0])); let mut x8: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x8, x3, (arg2[1]), (arg3[1])); let mut x9: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x9, x3, (arg2[2]), (arg3[2])); let mut x10: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x10, x3, (arg2[3]), (arg3[3])); let mut x11: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x11, x3, (arg2[4]), (arg3[4])); let mut x12: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x12, x3, (arg2[5]), (arg3[5])); let mut x13: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x13, x3, (arg2[6]), (arg3[6])); let mut x14: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x14, x3, (arg2[7]), (arg3[7])); let mut x15: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x15, x3, (arg2[8]), (arg3[8])); let mut x16: u32 = 0; let mut x17: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x16, &mut x17, 0x0, (0x1 as u32), (!(arg2[0]))); let mut x18: u32 = 0; let mut x19: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x18, &mut x19, x17, (0x0 as u32), (!(arg2[1]))); let mut x20: u32 = 0; let mut x21: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x20, &mut x21, x19, (0x0 as u32), (!(arg2[2]))); let mut x22: u32 = 0; let mut x23: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x22, &mut x23, x21, (0x0 as u32), (!(arg2[3]))); let mut x24: u32 = 0; let mut x25: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x24, &mut x25, x23, (0x0 as u32), (!(arg2[4]))); let mut x26: u32 = 0; let mut x27: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x26, &mut x27, x25, (0x0 as u32), (!(arg2[5]))); let mut x28: u32 = 0; let mut x29: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x28, &mut x29, x27, (0x0 as u32), (!(arg2[6]))); let mut x30: u32 = 0; let mut x31: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x30, &mut x31, x29, (0x0 as u32), (!(arg2[7]))); let mut x32: u32 = 0; let mut x33: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x32, &mut x33, x31, (0x0 as u32), (!(arg2[8]))); let mut x34: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x34, x3, (arg3[0]), x16); let mut x35: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x35, x3, (arg3[1]), x18); let mut x36: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x36, x3, (arg3[2]), x20); let mut x37: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x37, x3, (arg3[3]), x22); let mut x38: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x38, x3, (arg3[4]), x24); let mut x39: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x39, x3, (arg3[5]), x26); let mut x40: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x40, x3, (arg3[6]), x28); let mut x41: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x41, x3, (arg3[7]), x30); let mut x42: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x42, x3, (arg3[8]), x32); let mut x43: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x43, x3, (arg4[0]), (arg5[0])); let mut x44: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x44, x3, (arg4[1]), (arg5[1])); let mut x45: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x45, x3, (arg4[2]), (arg5[2])); let mut x46: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x46, x3, (arg4[3]), (arg5[3])); let mut x47: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x47, x3, (arg4[4]), (arg5[4])); let mut x48: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x48, x3, (arg4[5]), (arg5[5])); let mut x49: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x49, x3, (arg4[6]), (arg5[6])); let mut x50: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x50, x3, (arg4[7]), (arg5[7])); let mut x51: u32 = 0; let mut x52: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x51, &mut x52, 0x0, x43, x43); let mut x53: u32 = 0; let mut x54: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x53, &mut x54, x52, x44, x44); let mut x55: u32 = 0; let mut x56: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x55, &mut x56, x54, x45, x45); let mut x57: u32 = 0; let mut x58: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x57, &mut x58, x56, x46, x46); let mut x59: u32 = 0; let mut x60: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x59, &mut x60, x58, x47, x47); let mut x61: u32 = 0; let mut x62: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x61, &mut x62, x60, x48, x48); let mut x63: u32 = 0; let mut x64: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x63, &mut x64, x62, x49, x49); let mut x65: u32 = 0; let mut x66: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x65, &mut x66, x64, x50, x50); let mut x67: u32 = 0; let mut x68: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x67, &mut x68, 0x0, x51, 0xfffffc2f); let mut x69: u32 = 0; let mut x70: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x69, &mut x70, x68, x53, 0xfffffffe); let mut x71: u32 = 0; let mut x72: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x71, &mut x72, x70, x55, 0xffffffff); let mut x73: u32 = 0; let mut x74: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x73, &mut x74, x72, x57, 0xffffffff); let mut x75: u32 = 0; let mut x76: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x75, &mut x76, x74, x59, 0xffffffff); let mut x77: u32 = 0; let mut x78: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x77, &mut x78, x76, x61, 0xffffffff); let mut x79: u32 = 0; let mut x80: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x79, &mut x80, x78, x63, 0xffffffff); let mut x81: u32 = 0; let mut x82: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x81, &mut x82, x80, x65, 0xffffffff); let mut x83: u32 = 0; let mut x84: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x83, &mut x84, x82, (x66 as u32), (0x0 as u32)); let x85: u32 = (arg4[7]); let x86: u32 = (arg4[6]); let x87: u32 = (arg4[5]); let x88: u32 = (arg4[4]); let x89: u32 = (arg4[3]); let x90: u32 = (arg4[2]); let x91: u32 = (arg4[1]); let x92: u32 = (arg4[0]); let mut x93: u32 = 0; let mut x94: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x93, &mut x94, 0x0, (0x0 as u32), x92); let mut x95: u32 = 0; let mut x96: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x95, &mut x96, x94, (0x0 as u32), x91); let mut x97: u32 = 0; let mut x98: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x97, &mut x98, x96, (0x0 as u32), x90); let mut x99: u32 = 0; let mut x100: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x99, &mut x100, x98, (0x0 as u32), x89); let mut x101: u32 = 0; let mut x102: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x101, &mut x102, x100, (0x0 as u32), x88); let mut x103: u32 = 0; let mut x104: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x103, &mut x104, x102, (0x0 as u32), x87); let mut x105: u32 = 0; let mut x106: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x105, &mut x106, x104, (0x0 as u32), x86); let mut x107: u32 = 0; let mut x108: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x107, &mut x108, x106, (0x0 as u32), x85); let mut x109: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x109, x108, (0x0 as u32), 0xffffffff); let mut x110: u32 = 0; let mut x111: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x110, &mut x111, 0x0, x93, (x109 & 0xfffffc2f)); let mut x112: u32 = 0; let mut x113: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x112, &mut x113, x111, x95, (x109 & 0xfffffffe)); let mut x114: u32 = 0; let mut x115: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x114, &mut x115, x113, x97, x109); let mut x116: u32 = 0; let mut x117: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x116, &mut x117, x115, x99, x109); let mut x118: u32 = 0; let mut x119: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x118, &mut x119, x117, x101, x109); let mut x120: u32 = 0; let mut x121: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x120, &mut x121, x119, x103, x109); let mut x122: u32 = 0; let mut x123: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x122, &mut x123, x121, x105, x109); let mut x124: u32 = 0; let mut x125: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x124, &mut x125, x123, x107, x109); let mut x126: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x126, x3, (arg5[0]), x110); let mut x127: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x127, x3, (arg5[1]), x112); let mut x128: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x128, x3, (arg5[2]), x114); let mut x129: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x129, x3, (arg5[3]), x116); let mut x130: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x130, x3, (arg5[4]), x118); let mut x131: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x131, x3, (arg5[5]), x120); let mut x132: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x132, x3, (arg5[6]), x122); let mut x133: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x133, x3, (arg5[7]), x124); let x134: fiat_secp256k1_u1 = ((x34 & (0x1 as u32)) as fiat_secp256k1_u1); let mut x135: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x135, x134, (0x0 as u32), x7); let mut x136: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x136, x134, (0x0 as u32), x8); let mut x137: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x137, x134, (0x0 as u32), x9); let mut x138: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x138, x134, (0x0 as u32), x10); let mut x139: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x139, x134, (0x0 as u32), x11); let mut x140: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x140, x134, (0x0 as u32), x12); let mut x141: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x141, x134, (0x0 as u32), x13); let mut x142: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x142, x134, (0x0 as u32), x14); let mut x143: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x143, x134, (0x0 as u32), x15); let mut x144: u32 = 0; let mut x145: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x144, &mut x145, 0x0, x34, x135); let mut x146: u32 = 0; let mut x147: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x146, &mut x147, x145, x35, x136); let mut x148: u32 = 0; let mut x149: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x148, &mut x149, x147, x36, x137); let mut x150: u32 = 0; let mut x151: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x150, &mut x151, x149, x37, x138); let mut x152: u32 = 0; let mut x153: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x152, &mut x153, x151, x38, x139); let mut x154: u32 = 0; let mut x155: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x154, &mut x155, x153, x39, x140); let mut x156: u32 = 0; let mut x157: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x156, &mut x157, x155, x40, x141); let mut x158: u32 = 0; let mut x159: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x158, &mut x159, x157, x41, x142); let mut x160: u32 = 0; let mut x161: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x160, &mut x161, x159, x42, x143); let mut x162: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x162, x134, (0x0 as u32), x43); let mut x163: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x163, x134, (0x0 as u32), x44); let mut x164: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x164, x134, (0x0 as u32), x45); let mut x165: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x165, x134, (0x0 as u32), x46); let mut x166: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x166, x134, (0x0 as u32), x47); let mut x167: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x167, x134, (0x0 as u32), x48); let mut x168: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x168, x134, (0x0 as u32), x49); let mut x169: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x169, x134, (0x0 as u32), x50); let mut x170: u32 = 0; let mut x171: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x170, &mut x171, 0x0, x126, x162); let mut x172: u32 = 0; let mut x173: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x172, &mut x173, x171, x127, x163); let mut x174: u32 = 0; let mut x175: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x174, &mut x175, x173, x128, x164); let mut x176: u32 = 0; let mut x177: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x176, &mut x177, x175, x129, x165); let mut x178: u32 = 0; let mut x179: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x178, &mut x179, x177, x130, x166); let mut x180: u32 = 0; let mut x181: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x180, &mut x181, x179, x131, x167); let mut x182: u32 = 0; let mut x183: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x182, &mut x183, x181, x132, x168); let mut x184: u32 = 0; let mut x185: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x184, &mut x185, x183, x133, x169); let mut x186: u32 = 0; let mut x187: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x186, &mut x187, 0x0, x170, 0xfffffc2f); let mut x188: u32 = 0; let mut x189: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x188, &mut x189, x187, x172, 0xfffffffe); let mut x190: u32 = 0; let mut x191: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x190, &mut x191, x189, x174, 0xffffffff); let mut x192: u32 = 0; let mut x193: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x192, &mut x193, x191, x176, 0xffffffff); let mut x194: u32 = 0; let mut x195: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x194, &mut x195, x193, x178, 0xffffffff); let mut x196: u32 = 0; let mut x197: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x196, &mut x197, x195, x180, 0xffffffff); let mut x198: u32 = 0; let mut x199: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x198, &mut x199, x197, x182, 0xffffffff); let mut x200: u32 = 0; let mut x201: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x200, &mut x201, x199, x184, 0xffffffff); let mut x202: u32 = 0; let mut x203: fiat_secp256k1_u1 = 0; fiat_secp256k1_subborrowx_u32(&mut x202, &mut x203, x201, (x185 as u32), (0x0 as u32)); let mut x204: u32 = 0; let mut x205: fiat_secp256k1_u1 = 0; fiat_secp256k1_addcarryx_u32(&mut x204, &mut x205, 0x0, x6, (0x1 as u32)); let x206: u32 = ((x144 >> 1) | ((x146 << 31) & 0xffffffff)); let x207: u32 = ((x146 >> 1) | ((x148 << 31) & 0xffffffff)); let x208: u32 = ((x148 >> 1) | ((x150 << 31) & 0xffffffff)); let x209: u32 = ((x150 >> 1) | ((x152 << 31) & 0xffffffff)); let x210: u32 = ((x152 >> 1) | ((x154 << 31) & 0xffffffff)); let x211: u32 = ((x154 >> 1) | ((x156 << 31) & 0xffffffff)); let x212: u32 = ((x156 >> 1) | ((x158 << 31) & 0xffffffff)); let x213: u32 = ((x158 >> 1) | ((x160 << 31) & 0xffffffff)); let x214: u32 = ((x160 & 0x80000000) | (x160 >> 1)); let mut x215: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x215, x84, x67, x51); let mut x216: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x216, x84, x69, x53); let mut x217: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x217, x84, x71, x55); let mut x218: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x218, x84, x73, x57); let mut x219: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x219, x84, x75, x59); let mut x220: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x220, x84, x77, x61); let mut x221: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x221, x84, x79, x63); let mut x222: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x222, x84, x81, x65); let mut x223: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x223, x203, x186, x170); let mut x224: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x224, x203, x188, x172); let mut x225: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x225, x203, x190, x174); let mut x226: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x226, x203, x192, x176); let mut x227: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x227, x203, x194, x178); let mut x228: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x228, x203, x196, x180); let mut x229: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x229, x203, x198, x182); let mut x230: u32 = 0; fiat_secp256k1_cmovznz_u32(&mut x230, x203, x200, x184); *out1 = x204; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out2[5] = x12; out2[6] = x13; out2[7] = x14; out2[8] = x15; out3[0] = x206; out3[1] = x207; out3[2] = x208; out3[3] = x209; out3[4] = x210; out3[5] = x211; out3[6] = x212; out3[7] = x213; out3[8] = x214; out4[0] = x215; out4[1] = x216; out4[2] = x217; out4[3] = x218; out4[4] = x219; out4[5] = x220; out4[6] = x221; out4[7] = x222; out5[0] = x223; out5[1] = x224; out5[2] = x225; out5[3] = x226; out5[4] = x227; out5[5] = x228; out5[6] = x229; out5[7] = x230; } /// The function fiat_secp256k1_divstep_precomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_secp256k1_divstep_precomp(out1: &mut [u32; 8]) -> () { out1[0] = 0x31525e0a; out1[1] = 0xf201a418; out1[2] = 0xcd648d85; out1[3] = 0x9953f9dd; out1[4] = 0x3db210a9; out1[5] = 0xe8602946; out1[6] = 0x4b03709; out1[7] = 0x24fb8a31; }
2; 8], arg1: &[u32; 8]) -> ()
app-root.tsx
import { Component, State, Listen, h } from '@stencil/core'; import i18next, { initialLanguage, LANGUAGES } from '../../global/utils/i18n'; import { ROUTES, IS_DEV } from '../../global/constants'; import { IS_CHARITE } from '../../global/layouts'; import { TRACKING_IS_ENABLED } from '../../global/custom'; import settings from '../../global/utils/settings'; import { Language } from '@d4l/web-components-library/dist/types/components/LanguageSwitcher/language-switcher'; const dnt = navigator.doNotTrack === '1'; @Component({ tag: 'app-root', styleUrl: 'app-root.css', }) export class AppRoot { private connectTranslationsEl: HTMLConnectTranslationsElement; @State() language: Language; @State() appMessage: any = null; @State() showLogoHeader: boolean = false; @State() hasMadeCookieChoice: boolean; @Listen('changedLanguage', { target: 'window', }) async changedLanguageHandler(event: CustomEvent) { const { detail: language } = event; document.body.parentElement.setAttribute('lang', language.code); this.language = language; } getLanguageByCode(languageCode: Language['code']) { return LANGUAGES.find(({ code }) => code === languageCode); } @Listen('newAppMessage', { target: 'document', passive: true }) handleAppMessage(event: CustomEvent) { this.appMessage = null; setTimeout(() => { this.appMessage = { type: event.detail.type, text: event.detail.text, }; }, 0); } @Listen('showLogoHeader') showLogoHeaderListener(event: CustomEvent) { this.showLogoHeader = event.detail.show; } saveSettings = ({ acceptCookies, acceptTracking }) => { settings.acceptsCookies = acceptCookies; settings.acceptsTracking = acceptCookies && acceptTracking; this.hasMadeCookieChoice = true; this.trackConsentIfGiven(); }; trackConsentIfGiven() { if (settings.acceptsTracking) { // @ts-ignore window._paq.push(['setConsentGiven']); } } async componentWillLoad() { this.language = this.getLanguageByCode(await initialLanguage); this.hasMadeCookieChoice = IS_DEV || settings.hasMadeCookieChoice; } componentDidLoad() { this.connectTranslationsEl.changedLanguageHandler(this.language); this.trackConsentIfGiven(); } render() { const { language, appMessage, showLogoHeader, saveSettings, hasMadeCookieChoice, } = this; return ( <connect-translations ref={el => (this.connectTranslationsEl = el)}> <div class={`app-message ease-in-top ${ appMessage ? 'ease-in-top--active' : '' }`} > {appMessage && ( <d4l-snack-bar type={appMessage.type} data-test="snackBar" data-test-context={appMessage.type} > <div slot="snack-bar-icon"> <d4l-icon-info classes="icon--small" /> </div> <div class="app-message__content" slot="snack-bar-content"> {appMessage.text} </div> <div class="app-message__controls" slot="snack-bar-controls"> <d4l-button data-test="snackBarClose" classes="button--text button--uppercase" text="Dismiss" handleClick={() => (this.appMessage = null)} /> </div> </d4l-snack-bar> )} </div> {TRACKING_IS_ENABLED && !hasMadeCookieChoice && !dnt && ( <d4l-cookie-bar classes="cookie-bar app__cookie-bar" acceptText={i18next.t('cookie_bar_accept')} rejectText={i18next.t('cookie_bar_reject')} handleAccept={() => saveSettings({ acceptCookies: true, acceptTracking: !dnt }) } handleReject={() => saveSettings({ acceptCookies: false, acceptTracking: !dnt }) } > <div class="cookie-bar__content" slot="cookie-bar-text"> {i18next.t('cookie_bar_text')}{' '} <stencil-route-link url={ROUTES.DATA_PRIVACY}> {i18next.t('cookie_bar_data_privacy')} </stencil-route-link> </div> </d4l-cookie-bar> )} {showLogoHeader && !IS_CHARITE && ( <ia-logo-component classes="logo-component--collaboration" /> )} <header class="c-header"> {showLogoHeader && IS_CHARITE && ( <div class="app__logo-container"> <ia-logo-charite /> <ia-logo-d4l /> </div> )} {!showLogoHeader && ( <stencil-route-link url="/" anchorTitle="Home link" anchorClass="u-display-block c-logo" > {/* <h1>CovApp</h1> */} <h1>HallucinationsApp</h1> </stencil-route-link> )} <d4l-language-switcher languages={LANGUAGES} activeLanguage={language} class="u-margin-left--auto" /> </header> <main> <stencil-router> <stencil-route-switch scrollTopOffset={0.1}> <stencil-route url="/" component="ia-start" exact /> <stencil-route url={ROUTES.QUESTIONNAIRE} component="ia-questionnaire" /> <stencil-route url={ROUTES.SUMMARY} component="ia-summary" /> <stencil-route url={ROUTES.IMPRINT} component="ia-imprint" /> <stencil-route url={ROUTES.LEGAL} component="ia-legal" /> <stencil-route url={ROUTES.DISCLAIMER} component="ia-disclaimer" /> <stencil-route url={ROUTES.FAQ} component="ia-faq" />
<stencil-route url={ROUTES.DATA_PRIVACY} component="ia-data-privacy" /> <stencil-route component="ia-start" /> </stencil-route-switch> </stencil-router> </main> {/* <footer class="c-footer"> <ul class="u-list-reset"> <li> <stencil-route-link anchorClass="o-link o-link--gray" url={ROUTES.IMPRINT} > {i18next.t('app_root_imprint_link')} </stencil-route-link> </li> <li> <stencil-route-link anchorClass="o-link o-link--gray" url={ROUTES.LEGAL} > {i18next.t('app_root_legal_link')} </stencil-route-link> </li> <li> <stencil-route-link anchorClass="o-link o-link--gray" url={ROUTES.FAQ}> {i18next.t('app_root_faq_link')} </stencil-route-link> </li> <li> <stencil-route-link anchorClass="o-link o-link--gray" url={ROUTES.DATA_PRIVACY} > {i18next.t('app_root_data_privacy_link')} </stencil-route-link> </li> </ul> <p> © {new Date().getFullYear()} {i18next.t('app_root_all_rights_reserved')} </p> </footer> */} </connect-translations> ); } }
sleep.go
package main import "time"
func main() { time.Sleep(1 * time.Second) println("Started") go periodic() time.Sleep(5 * time.Second) //wait for a while so we can observe what ticker does } func periodic(){ for { println("tick") time.Sleep(1 * time.Second) } }
voice_stream.rs
use std::future::Future; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; use crate::client::Client; use crate::message::{ Client as MsgClient, Coalition, GameMessage, Message, MsgType, Radio, RadioInfo, }; use crate::messages_codec::MessagesCodec; use crate::voice_codec::*; use futures::channel::mpsc; use futures::future::{self, Either, FutureExt, TryFutureExt}; use futures::sink::{Sink, SinkExt}; use futures::stream::{SplitSink, SplitStream, Stream, StreamExt}; use tokio::net::{TcpStream, UdpSocket}; use tokio::time::delay_for; use tokio_util::codec::Framed; use tokio_util::udp::UdpFramed; const SRS_VERSION: &str = "1.7.0.0"; pub struct
{ voice_sink: mpsc::Sender<Packet>, voice_stream: SplitStream<UdpFramed<VoiceCodec>>, heartbeat: Pin<Box<dyn Send + Future<Output = Result<(), anyhow::Error>>>>, client: Client, packet_id: u64, } impl VoiceStream { pub async fn new( client: Client, addr: SocketAddr, game_source: Option<mpsc::UnboundedReceiver<GameMessage>>, ) -> Result<Self, io::Error> { let recv_voice = game_source.is_some(); let tcp = TcpStream::connect(addr).await?; let (sink, stream) = Framed::new(tcp, MessagesCodec::new()).split(); let a = Box::pin(recv_updates(stream)); let b = Box::pin(send_updates(client.clone(), sink, game_source)); let local_addr: SocketAddr = "0.0.0.0:0".parse().unwrap(); let udp = UdpSocket::bind(local_addr).await?; udp.connect(addr).await?; let (sink, stream) = UdpFramed::new(udp, VoiceCodec::new()).split(); let (tx, rx) = mpsc::channel(32); let c = Box::pin(send_voice_pings(client.clone(), tx.clone(), recv_voice)); let d = Box::pin(forward_packets(rx, sink, addr)); let ab = future::try_select(a, b) .map_ok(|_| ()) .map_err(|err| match err { Either::Left((err, _)) => err, Either::Right((err, _)) => err, }); let cd = future::try_select(c, d) .map_ok(|_| ()) .map_err(|err| match err { Either::Left((err, _)) => err, Either::Right((err, _)) => err, }); let heartbeat = future::try_select(ab, cd) .map_ok(|_| ()) .map_err(|err| match err { Either::Left((err, _)) => err, Either::Right((err, _)) => err, }); Ok(VoiceStream { voice_stream: stream, voice_sink: tx, heartbeat: Box::pin(heartbeat), client, packet_id: 1, }) } } impl Stream for VoiceStream { type Item = Result<VoicePacket, anyhow::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let s = self.get_mut(); match s.voice_stream.poll_next_unpin(cx) { Poll::Pending => {} Poll::Ready(None) => { return Poll::Ready(Some(Err(anyhow!("voice stream was closed unexpectedly")))) } Poll::Ready(Some(Ok((None, _)))) => { // not enough data for the codec to create a new item } Poll::Ready(Some(Ok((Some(p), _)))) => { return Poll::Ready(Some(Ok(p))); } Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err.into()))), } match s.heartbeat.poll_unpin(cx) { Poll::Pending => {} Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err.into()))), Poll::Ready(Ok(_)) => { return Poll::Ready(Some(Err(anyhow!("TCP connection was closed unexpectedly")))); } } Poll::Pending } } impl Sink<Vec<u8>> for VoiceStream { type Error = mpsc::SendError; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { let s = self.get_mut(); Pin::new(&mut s.voice_sink).poll_ready(cx) } fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> { let mut sguid = [0; 22]; sguid.clone_from_slice(self.client.sguid().as_bytes()); let packet = VoicePacket { audio_part: item, frequencies: vec![Frequency { freq: self.client.freq() as f64, modulation: Modulation::AM, encryption: Encryption::None, }], unit_id: self.client.unit().map(|u| u.id).unwrap_or(0), packet_id: self.packet_id, sguid, }; let s = self.get_mut(); s.packet_id = s.packet_id.wrapping_add(1); Pin::new(&mut s.voice_sink).start_send(packet.into()) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { let s = self.get_mut(); Pin::new(&mut s.voice_sink).poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { let s = self.get_mut(); Pin::new(&mut s.voice_sink).poll_close(cx) } } async fn recv_updates( mut stream: SplitStream<Framed<TcpStream, MessagesCodec>>, ) -> Result<(), anyhow::Error> { while let Some(msg) = stream.next().await { // discard messages for now msg?; } Ok(()) } /// Sends updates about the client to the server. If `game_source` is set, /// the position and frequency from the latest received `GameMessage` is used. /// Otherwise, the parameters set in the `client` struct are used. async fn send_updates<G>( client: Client, mut sink: SplitSink<Framed<TcpStream, MessagesCodec>, Message>, game_source: Option<G>, ) -> Result<(), anyhow::Error> where G: Stream<Item = GameMessage> + Unpin, { // send initial SYNC message let sync_msg = create_sync_message(&client); sink.send(sync_msg).await?; if let Some(mut game_source) = game_source { let mut last_game_msg = None; loop { let delay = delay_for(Duration::from_secs(5)); match future::select(game_source.next(), delay).await { Either::Left((Some(msg), _)) => { last_game_msg = Some(msg); } Either::Left((None, _)) => { break; } Either::Right((_, _)) => { // debug!("Game message timeout") } } match &last_game_msg { Some(msg) => sink.send(radio_message_from_game(&client, msg)).await?, None => {} } } unreachable!("Game source disconnected"); } else { loop { delay_for(Duration::from_secs(5)).await; // Sending update message sink.send(create_update_message(&client)).await?; } } } async fn send_voice_pings( client: Client, mut tx: mpsc::Sender<Packet>, recv_voice: bool, ) -> Result<(), anyhow::Error> { // TODO: is there a future that never resolves let mut sguid = [0; 22]; sguid.clone_from_slice(client.sguid().as_bytes()); loop { if recv_voice { tx.send(Packet::Ping(sguid.clone())).await?; } delay_for(Duration::from_secs(5)).await; } } async fn forward_packets( mut rx: mpsc::Receiver<Packet>, mut sink: SplitSink<UdpFramed<VoiceCodec>, (Packet, SocketAddr)>, addr: SocketAddr, ) -> Result<(), anyhow::Error> { while let Some(p) = rx.next().await { sink.send((p, addr)).await?; } Ok(()) } fn create_sync_message(client: &Client) -> Message { let pos = client.position(); Message { client: Some(MsgClient { client_guid: client.sguid().to_string(), name: Some(client.name().to_string()), position: pos.clone(), coalition: Coalition::Blue, radio_info: Some(RadioInfo { name: "DATIS Radios".to_string(), pos: pos, ptt: false, radios: vec![Radio { enc: false, enc_key: 0, enc_mode: 0, // no encryption freq_max: 1.0, freq_min: 1.0, freq: client.freq() as f64, modulation: 0, name: "DATIS Radio".to_string(), sec_freq: 0.0, volume: 1.0, freq_mode: 0, // Cockpit vol_mode: 0, // Cockpit expansion: false, channel: -1, simul: false, }], control: 0, // HOTAS selected: 0, unit: client .unit() .map(|u| u.name.clone()) .unwrap_or_else(|| client.name().to_string()), unit_id: client.unit().as_ref().map(|u| u.id).unwrap_or(0), simultaneous_transmission: true, }), }), msg_type: MsgType::Sync, version: SRS_VERSION.to_string(), } } fn create_update_message(client: &Client) -> Message { Message { client: Some(MsgClient { client_guid: client.sguid().to_string(), name: Some(client.name().to_string()), position: client.position(), coalition: Coalition::Blue, radio_info: None, }), msg_type: MsgType::Update, version: SRS_VERSION.to_string(), } } fn radio_message_from_game(client: &Client, game_message: &GameMessage) -> Message { let pos = game_message.pos.clone(); Message { client: Some(MsgClient { client_guid: client.sguid().to_string(), name: Some(game_message.name.clone()), position: pos.clone(), coalition: Coalition::Blue, radio_info: Some(RadioInfo { name: game_message.name.clone(), pos: pos, ptt: game_message.ptt, radios: game_message .radios .iter() .map(|r| r.into()) .collect::<Vec<Radio>>(), control: 0, // HOTAS selected: game_message.selected, unit: game_message.unit.clone(), unit_id: game_message.unit_id, simultaneous_transmission: true, }), }), msg_type: MsgType::RadioUpdate, version: SRS_VERSION.to_string(), } }
VoiceStream
request.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { environment } from '../../../environments/environment'; import { AuthenticationService } from '../../service/auth/authentication.service'; import { LoadingService } from '../../service/loading/loading.service'; @Injectable() export class RequestInterceptor implements HttpInterceptor { constructor( private authenticationService: AuthenticationService, private loadingService: LoadingService ) { } intercept( request: HttpRequest<unknown>, next: HttpHandler ): Observable<HttpEvent<unknown>> { this.loadingService.setLoading( true ); request = this.authenticationService.addAuthorizationHeader( request ); if ( environment.identity !== 'production' ) { console.log( request.url ); } return next.handle( request ); } }
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs';
service.go
// Copyright © 2021 Attestant Limited. // 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 mock import ( "context" "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/attestantio/vouch/services/accountmanager" e2wtypes "github.com/wealdtech/go-eth2-wallet-types/v2" ) type validatingAccountsProvider struct{} // NewValidatingAccountsProvider is a mock. func NewValidatingAccountsProvider() accountmanager.ValidatingAccountsProvider { return &validatingAccountsProvider{} } // ValidatingAccountsForEpoch is a mock. func (v *validatingAccountsProvider) ValidatingAccountsForEpoch(ctx context.Context, epoch phase0.Epoch) (map[phase0.ValidatorIndex]e2wtypes.Account, error) { return make(map[phase0.ValidatorIndex]e2wtypes.Account), nil } // ValidatingAccountsForEpochByIndex obtains the specified validating accounts for a given epoch. func (v *validatingAccountsProvider) ValidatingAccountsForEpochByIndex(ctx context.Context, epoch phase0.Epoch, indices []phase0.ValidatorIndex, ) ( map[phase0.ValidatorIndex]e2wtypes.Account, error, ) { return make(map[phase0.ValidatorIndex]e2wtypes.Account), nil } type refresher struct{} // NewRefresher is a mock. func N
) accountmanager.Refresher { return &refresher{} } // Refresh is a mock. func (r *refresher) Refresh(ctx context.Context) {}
ewRefresher(
syncMsgs.ts
/**
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. */ import { Message } from './message'; export class SyncMsgs { lastUpdate?: Date; ownId: String; contactIds?: String[]; msgs?: Message[]; }
* Copyright 2018 Sven Loesekann Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
yaplox_callable.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, List # This is a hack to prevent circular imports; since Interpreter imports from this file, # we will only import it during the type_checking run from mypy if TYPE_CHECKING:
class YaploxCallable(ABC): @abstractmethod def call(self, interpreter: Interpreter, arguments: List[Any]): raise NotImplementedError @abstractmethod def arity(self) -> int: raise NotImplementedError
from yaplox.interpreter import Interpreter
QueryResourcePackageInstancesRequest.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkbssopenapi.endpoint import endpoint_data class QueryResourcePackageInstancesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'BssOpenApi', '2017-12-14', 'QueryResourcePackageInstances') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ExpiryTimeEnd(self): return self.get_query_params().get('ExpiryTimeEnd') def set_ExpiryTimeEnd(self,ExpiryTimeEnd): self.add_query_param('ExpiryTimeEnd',ExpiryTimeEnd) def get_ProductCode(self): return self.get_query_params().get('ProductCode') def set_ProductCode(self,ProductCode): self.add_query_param('ProductCode',ProductCode) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId) def get_ExpiryTimeStart(self): return self.get_query_params().get('ExpiryTimeStart') def set_ExpiryTimeStart(self,ExpiryTimeStart): self.add_query_param('ExpiryTimeStart',ExpiryTimeStart) def get_PageNum(self): return self.get_query_params().get('PageNum') def set_PageNum(self,PageNum): self.add_query_param('PageNum',PageNum) def get_PageSize(self):
def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize)
return self.get_query_params().get('PageSize')
main.go
func bitmask(digit uint) uint { return 1 << digit }
if num&bitmask(digit) != 0 { return true } else { return false } } func subsets(nums []int) [][]int { subsets := [][]int{} for i := uint(0); i < (1 << len(nums)); i++ { subset := []int{} for j := uint(0); j < uint(len(nums)); j++ { if checkbit(i, j) { subset = append(subset, nums[j]) } } subsets = append(subsets, subset) } return subsets }
func checkbit(num uint, digit uint) bool {
push_data_via_git.py
#!/usr/bin/env python3 # vim: set fileencoding=utf-8: # Standard library import json import logging import os # Third-party import git # First-party/Local import log GIT_USER_NAME = "CC creativecommons.github.io Bot" GIT_USER_EMAIL = "[email protected]" GITHUB_USERNAME = "cc-creativecommons-github-io-bot" GITHUB_ORGANIZATION = "creativecommons" GITHUB_REPO_NAME = "creativecommons.github.io-source" GITHUB_TOKEN = os.environ["ADMIN_GITHUB_TOKEN"] GITHUB_REPO_URL_WITH_CREDENTIALS = ( f"https://{GITHUB_USERNAME}:{GITHUB_TOKEN}" f"@github.com/{GITHUB_ORGANIZATION}/{GITHUB_REPO_NAME}.git" ) WORKING_DIRECTORY = "/tmp" GIT_WORKING_DIRECTORY = f"{WORKING_DIRECTORY}/{GITHUB_REPO_NAME}" JSON_FILE_DIRECTORY = f"{GIT_WORKING_DIRECTORY}/databags" log.set_up_logging() logger = logging.getLogger("push_data_to_ccos") log.reset_handler() def set_up_repo(): if not os.path.isdir(GIT_WORKING_DIRECTORY): logger.log(logging.INFO, "Cloning repo...") repo = git.Repo.clone_from( url=GITHUB_REPO_URL_WITH_CREDENTIALS, to_path=GIT_WORKING_DIRECTORY ) else: logger.log(logging.INFO, "Setting up repo...") repo = git.Repo(GIT_WORKING_DIRECTORY) origin = repo.remotes.origin logger.log(logging.INFO, "Pulling latest code...") origin.pull() return f"{WORKING_DIRECTORY}/{GITHUB_REPO_NAME}" def set_up_git_user(): logger.log(logging.INFO, "Setting up git user...") os.environ["GIT_AUTHOR_NAME"] = GIT_USER_NAME os.environ["GIT_AUTHOR_EMAIL"] = GIT_USER_EMAIL os.environ["GIT_COMMITTER_NAME"] = GIT_USER_NAME os.environ["GIT_COMMITTER_EMAIL"] = GIT_USER_EMAIL def generate_json_file(data, filename): logger.log(logging.INFO, "Generating JSON file...") json_filename = f"{JSON_FILE_DIRECTORY}/{filename}" with open(json_filename, "w") as json_file: json.dump(data, json_file, sort_keys=True, indent=4) return json_filename def commit_and_push_changes(json_filename): repo = git.Repo(GIT_WORKING_DIRECTORY) git_diff = repo.index.diff(None) if git_diff: repo.index.add(items=f"{json_filename}") repo.index.commit(message="Syncing new data changes.") origin = repo.remotes.origin logger.log(logging.INFO, "Pushing latest code...") origin.push() else: logger.log(logging.INFO, "No changes to push...") def push_data(data, filename):
set_up_repo() set_up_git_user() json_filename = generate_json_file(data, filename) commit_and_push_changes(json_filename)
export_mmap_test.go
// Copyright 2016 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. //go:build unix // Export guts for testing. package runtime var Mmap = mmap var Munmap = munmap const ENOMEM = _ENOMEM const MAP_ANON = _MAP_ANON const MAP_PRIVATE = _MAP_PRIVATE const MAP_FIXED = _MAP_FIXED func
() uintptr { return physPageSize }
GetPhysPageSize