How to use newBase method of td Package

Best Go-testdeep code snippet using td.newBase

fmi.go

Source:fmi.go Github

copy

Full Screen

1package fmi2import (3 "encoding/xml"4 "fmt"5 "io/ioutil"6 "math"7 "net/http"8 "net/url"9 "sort"10 "strings"11 "time"12)13type simpleFeatureCollection struct {14 Timestamp time.Time `xml:"timeStamp,attr"`15 Returned int `xml:"numberReturned,attr"`16 Matched int `xml:"numberMatched,attr"`17 Elements []observation `xml:"member>BsWfsElement"`18}19type observation struct {20 Location string `xml:"Location>Point>pos"`21 Time time.Time `xml:"Time"`22 Parameter string `xml:"ParameterName"`23 Value float64 `xml:"ParameterValue"`24}25func getFeature(query string, parameters url.Values) (*http.Response, error) {26 endpoint := url.URL{27 Scheme: "http",28 Host: "opendata.fmi.fi",29 Path: "/wfs",30 RawQuery: "service=WFS&version=2.0.0&request=getFeature",31 }32 q := endpoint.Query()33 q.Set("storedquery_id", query)34 for k, vs := range parameters {35 for _, v := range vs {36 q.Add(k, v)37 }38 }39 endpoint.RawQuery = q.Encode()40 return http.Get(endpoint.String())41}42func formatObservations(place string, observations map[string]float64) string {43 var output strings.Builder44 fmt.Fprintf(&output, "Viimeisimmät säähavainnot paikassa %s: ", strings.Title(strings.ToLower(place)))45 if !math.IsNaN(observations["t2m"]) {46 fmt.Fprintf(&output, "lämpötila %.1f°C", observations["t2m"])47 switch {48 case observations["t2m"] > 20 && !math.IsNaN(observations["td"]):49 h := humidex(observations["t2m"], observations["td"])50 if humidexScale(h) != "" {51 fmt.Fprintf(&output, " (%s, tuntuu kuin %.1f°C)", humidexScale(h), h)52 } else {53 fmt.Fprintf(&output, " (tuntuu kuin %.1f°C)", h)54 }55 case observations["t2m"] <= 10 && !math.IsNaN(observations["ws_10min"]):56 wc := windChillFmi(observations["t2m"], observations["ws_10min"])57 if windChillScale(wc) != "" {58 fmt.Fprintf(&output, " (%s, tuntuu kuin %.1f°C)", windChillScale(wc), wc)59 } else {60 fmt.Fprintf(&output, " (tuntuu kuin %.1f°C)", wc)61 }62 }63 } else {64 fmt.Fprint(&output, "lämpötilatiedot puuttuvat")65 }66 if !math.IsNaN(observations["n_man"]) {67 fmt.Fprintf(&output, ", %s", cloudCover(observations["n_man"]))68 }69 if !math.IsNaN(observations["ws_10min"]) {70 fmt.Fprintf(&output, ", %s %.f m/s (%.f m/s)", windSpeed(observations["ws_10min"], observations["wd_10min"]), observations["ws_10min"], observations["wg_10min"])71 }72 if !math.IsNaN(observations["rh"]) {73 fmt.Fprintf(&output, ", ilmankosteus %.f%%", observations["rh"])74 }75 if !math.IsNaN(observations["r_1h"]) && observations["r_1h"] >= 0 {76 fmt.Fprintf(&output, ", sateen määrä %.1f mm (%.1f mm/h)", observations["r_1h"], observations["ri_10min"])77 }78 if !math.IsNaN(observations["snow_aws"]) && observations["snow_aws"] >= 0 {79 fmt.Fprintf(&output, ", lumen syvyys %.f cm", observations["snow_aws"])80 }81 return output.String()82}83// Weather returns current weather for a place as a written description84func Weather(place string) string {85 if place == "" {86 return "Paikkaa ei syötetty"87 }88 return simpleObservations(place)89}90func appendIfMssing(slice []string, s string) []string {91 for _, el := range slice {92 if el == s {93 return slice94 }95 }96 return append(slice, s)97}98func simpleObservations(place string) string {99 q := url.Values{}100 q.Set("place", place)101 q.Set("maxlocations", "2")102 /* Parameters:103 name label measure104 t2m Air Temperature degC105 ws_10min Wind Speed m/s106 wg_10min Gust Speed m/s107 wd_10min Wind Direction degrees108 rh Relative humidity %109 td Dew-point temp. degC110 r_1h Precipitation amt mm111 ri_10min Precip. intensity mm/h112 snow_aws Snow depth cm113 -1 = no snow, 0 = snow in vicinity114 p_sea Pressure (msl) hPa115 vis Visibility m116 n_man Cloud cover 1/8117 wawa Present weather code (00-99)118 see: https://www.wmo.int/pages/prog/www/WMOCodes/WMO306_vI1/Publications/2017update/Sel9.pdf119 */120 measures := []string{"t2m", "ws_10min", "wg_10min", "wd_10min", "rh", "r_1h", "ri_10min", "snow_aws", "n_man", "td"}121 q.Set("parameters", strings.Join(measures, ","))122 // There should be data every 10 mins123 q.Set("timestep", "10")124 endTime := time.Now().UTC().Truncate(10 * time.Minute)125 startTime := endTime.Add(-10 * time.Minute)126 q.Set("starttime", startTime.Format(time.RFC3339))127 q.Set("endtime", endTime.Format(time.RFC3339))128 resp, err := getFeature("fmi::observations::weather::simple", q)129 if err != nil {130 // handle error131 return "Säähavaintoja ei saatu haettua"132 }133 defer resp.Body.Close()134 body, err := ioutil.ReadAll(resp.Body)135 if err != nil {136 // handle error?137 return "Virhe luettaessa havaintoja"138 }139 if resp.StatusCode != 200 {140 // If place parsing fails, returns 400 with OperationParsingFailed141 return "Säähavaintopaikkaa ei löytynyt"142 }143 var collection simpleFeatureCollection144 xml.Unmarshal(body, &collection)145 if collection.Matched == 0 || collection.Returned == 0 {146 return "Säähavaintoja ei löytynyt"147 }148 observations := make(map[time.Time]map[string]map[string]float64)149 times := make([]time.Time, 0)150 locations := make([]string, 0)151 for _, obs := range collection.Elements {152 if observations[obs.Time] == nil {153 times = append(times, obs.Time)154 observations[obs.Time] = make(map[string]map[string]float64)155 }156 if observations[obs.Time][obs.Location] == nil {157 locations = appendIfMssing(locations, obs.Location)158 observations[obs.Time][obs.Location] = make(map[string]float64)159 }160 observations[obs.Time][obs.Location][obs.Parameter] = obs.Value161 }162 sort.Slice(times, func(i, j int) bool {163 return times[i].After(times[j])164 })165 latestObs := make(map[string]float64)166 for _, timeIndex := range times {167 for _, locationIndex := range locations {168 if countNanMeasures(observations[timeIndex][locationIndex], measures) != len(measures) {169 latestObs = observations[timeIndex][locationIndex]170 }171 }172 }173 if len(latestObs) == 0 {174 return "Säähavaintoja ei löytynyt"175 }176 return formatObservations(place, latestObs)177}178func countNanMeasures(obs map[string]float64, measures []string) int {179 count := 0180 for _, measure := range measures {181 if math.IsNaN(obs[measure]) {182 count++183 }184 }185 return count186}187// windSpeed takes wind speed s (m/s) and direction d (angle) and188// returns a textual representation of them.189// For reference, see: https://ilmatieteenlaitos.fi/tuulet190func windSpeed(s float64, d float64) string {191 switch {192 case s < 0:193 return ""194 case s < 1:195 return "tyyntä"196 case s <= 4:197 return fmt.Sprintf("heikkoa %stuulta", windDirection(d))198 case s <= 8:199 return fmt.Sprintf("kohtalaista %stuulta", windDirection(d))200 case s <= 14:201 return fmt.Sprintf("navakkaa %stuulta", windDirection(d))202 case s <= 21:203 return fmt.Sprintf("kovaa %stuulta", windDirection(d))204 case s < 33:205 return "myrskyä"206 case s >= 33:207 return "hirmumyrskyä"208 }209 return ""210}211// windDirection takes a wind direction d in angles (0-360) and converts212// it to a string representation. For reference, see:213// https://ilmatieteenlaitos.fi/tuulet214func windDirection(d float64) string {215 switch {216 case d < 0:217 return ""218 case d >= 0 && d <= 22.5:219 return "pohjois"220 case d < 67.5:221 return "koillis"222 case d <= 112.5:223 return "itä"224 case d < 157.5:225 return "kaakkois"226 case d <= 202.5:227 return "etelä"228 case d < 247.5:229 return "lounais"230 case d <= 292.5:231 return "länsi"232 case d < 337.5:233 return "luoteis"234 case d >= 337.5 && d <= 360:235 return "pohjois"236 }237 return ""238}239// cloudCover converts the cloud cover measure (1/8) to textual format240// using definitions at https://ilmatieteenlaitos.fi/pilvisyys241func cloudCover(d float64) string {242 switch {243 case d < 0:244 return ""245 case d >= 0 && d <= 1:246 return "selkeää"247 case d <= 3:248 return "melko selkeää"249 case d <= 5:250 return "puolipilvistä"251 case d <= 7:252 return "melko pilvistä"253 case d <= 8:254 return "pilvistä"255 case d == 9:256 return "taivas ei näy"257 }258 return ""259}260// humidex calculates the humidity index given air temperature t (degC)261// and dew point (degC) td.262// For reference, see https://en.wikipedia.org/wiki/Humidex263func humidex(t float64, td float64) float64 {264 return t + 5.0/9.0*(6.11*math.Exp(5417.7530*(1/273.16-1/(273.15+td)))-10)265}266// humidexScale converts humidex index h to a textual classification using267// definitions from:268// https://web.archive.org/web/20150319113439/http://ilmatieteenlaitos.fi/tietoa-helteen-tukaluudesta269func humidexScale(h float64) string {270 switch {271 case h < 20:272 return ""273 case h <= 26:274 return "mukava"275 case h <= 30:276 return "lämmin"277 case h <= 34:278 return "kuuma"279 case h <= 40:280 return "tukala"281 case h > 40:282 return "erittäin tukala"283 }284 return ""285}286// windChill calculates the wind chill effect given air temperature t (degC)287// and wind speed v (m/s) using a Canadian formula.288// The calculation works for air temperatures at or below 10C and wind speeds above 0.4 m/s.289// For reference see,290// https://fi.m.wikipedia.org/wiki/Pakkasen_purevuus#Uusi_kaava291func windChill(t float64, v float64) float64 {292 return 13.12 + 0.6215*t - 13.956*math.Pow(v, 0.16) + 0.4867*t*math.Pow(v, 0.16)293}294// WindChillFmi calculates wind chill with FMI's formula295// For reference see,296// https://github.com/fmidev/smartmet-library-newbase/blob/0da9473163883089c35a4c7267ba4c8a8bb3e14f/newbase/NFmiMetMath.cpp#L380297// https://tietopyynto.fi/tietopyynto/ilmatieteen-laitoksen-kayttama-tuntuu-kuin-laskentakaava/298func windChillFmi(t float64, v float64) float64 {299 var kmh = v * 3.6300 if kmh < 5 {301 return t + (-1.59+0.1345*t)/5*kmh302 }303 return 13.12 + 0.6215*t - 11.37*math.Pow(v, 0.16) + 0.3965*t*math.Pow(v, 0.16)304}305// SummerSimmer calculates the Summer Simmer index306// For reference see,307// https://github.com/fmidev/smartmet-library-newbase/blob/0da9473163883089c35a4c7267ba4c8a8bb3e14f/newbase/NFmiMetMath.cpp#L335308// http://www.summersimmer.com/home.htm309func SummerSimmer(t float64, rh float64) float64 {310 const simmerLimit = 14.5311 const rhRef = 50.0 / 100.0312 if t <= simmerLimit {313 return t314 }315 var r = rh / 100.0316 return (1.8*t - 0.55*(1-r)*(1.8*t-26) - 0.55*(1-rhRef)*26) / (1.8 * (1 - 0.55*(1-rhRef)))317}318// FeelsLikeTemperature calculates FMI's "feel like" temperature319// For reference see,320// https://github.com/fmidev/smartmet-library-newbase/blob/0da9473163883089c35a4c7267ba4c8a8bb3e14f/newbase/NFmiMetMath.cpp#L418321// https://tietopyynto.fi/tietopyynto/ilmatieteen-laitoksen-kayttama-tuntuu-kuin-laskentakaava/322func FeelsLikeTemperature(t float64, v float64, rh float64, rad float64) float64 {323 const a = 15.0324 const t0 = 37.0325 var chill = a + (1-a/t0)*t + a/t0*math.Pow(v+1, 0.16)*(t-t0)326 var heat = SummerSimmer(t, rh)327 var feels = t + (chill - t) + (heat - t)328 if rad != -1 {329 const absorption = 0.07330 feels += 0.7*absorption*rad/(v+10) - 0.25331 }332 return feels333}334// windChillScale converts windChill index w to a textual representation using335// classifications from https://fi.wikipedia.org/wiki/Pakkasen_purevuus336func windChillScale(w float64) string {337 switch {338 case w > -25:339 return ""340 case w <= -60:341 return "suuri paleltumisvaara"342 case w <= -35:343 return "paleltumisvaara"344 case w <= -25:345 return "erittäin kylmä"346 }347 return ""348}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

...18type OffsetTime struct {19 offset time.Duration20 base simTime21}22func (t *OffsetTime) normalizeTo(newBase simTime) {23 oldBase := t.base24 difference := oldBase.Sub(newBase.Time)25 t.base = newBase26 t.offset = t.offset + difference27}28func (t *OffsetTime) replaceBaseWithoutNormalizing(newBase simTime) {29 t.base = newBase30}31func (t *simTime) UnmarshalJSON(buf []byte) error {32 tt, err := time.Parse(time.StampMicro, strings.Trim(string(buf), `"`))33 if err != nil {34 return err35 }36 t.Time = tt37 return nil38}39type ThroughputData struct {40 time OffsetTime41 count int42}43func (td ThroughputData) toStringList() []string {44 time := fmt.Sprintf("%d", td.time.offset.Milliseconds())45 throughput := fmt.Sprintf("%d", td.count)46 return []string{time, throughput}47}48type ThroughputDataset struct {49 data []ThroughputData50}51func (td *ThroughputDataset) getColumnNames() []string {52 return []string{"time", "count"}53}54func (td *ThroughputDataset) toCsv(filename string) {55 file, err := os.Create(filename)56 if err != nil {57 panic(err)58 }59 defer file.Close()60 w := csv.NewWriter(file)61 defer w.Flush()62 columns := td.getColumnNames()63 w.Write(columns)64 for _, throughputData := range td.data {65 w.Write(throughputData.toStringList())66 }67}68type LatencyData struct {69 time OffsetTime70 latency time.Duration71 dropped bool72}73type Dataset interface {74 getColumnNames() []string75}76type LatencyDataset struct {77 data []LatencyData78}79func (ld *LatencyDataset) getColumnNames() []string {80 return []string{"time", "latency"}81}82func (ld *LatencyDataset) replaceBaseTimes(newBase simTime) {83 for _, data := range ld.data {84 data.time.replaceBaseWithoutNormalizing(newBase)85 }86}87func (ld *LatencyDataset) normalizeTimesTo(newBase simTime) {88 for _, data := range ld.data {89 data.time.normalizeTo(newBase)90 }91}92func (ld LatencyData) toStringList() []string {93 time := fmt.Sprintf("%d", ld.time.offset.Milliseconds())94 latency := fmt.Sprintf("%d", ld.latency.Milliseconds())95 dropped := fmt.Sprintf("%v", ld.dropped)96 return []string{time, latency, dropped}97}98func experimentType(filename string) string {99 parts := strings.Split(filename, "/")100 name := strings.Split(parts[len(parts)-1], ".csv")[0]101 return name102}103func (lg *LatencyDataset) toCsv(filename string) {...

Full Screen

Full Screen

error.go

Source:error.go Github

copy

Full Screen

1// Package errors provides error and error wrapping facilities that allow2// for the easy reporting of call stacks and structured error annotations.3package errors4import (5 "bytes"6 "encoding/json"7 "fmt"8)9// New returns a base error that captures the call stack.10func New(text string) error {11 return NewBase(1, text)12}13// Base is an error type that supports capturing the call stack at creation14// time, and storing separate text & data to allow structured logging.15// While it could be used directly, it may make more sense as an16// anonymous inside a package/application specific error struct.17type Base struct {18 Text string19 Fields Fields20 CallStack CallStack21}22// Fields holds the annotations for an error.23type Fields map[string]interface{}24// NewBase creates a new Base, capturing a call trace starting25// at "skip" calls above.26func NewBase(skip int, text string) *Base {27 return &Base{28 Text: text,29 CallStack: CurrentCallStack(skip + 1),30 }31}32func (e *Base) Error() string {33 return textAndFields(e.Text, e.Fields)34}35// AddFields allows a Error message to be further annotated with36// a set of key,values, to add more context when inspecting37// Error messages.38func (e *Base) AddFields(fields Fields) {39 e.Fields = combineFields(e.Fields, fields)40}41// Location returns the location info (file, line, ...) for the place42// where this Error error was created.43func (e *Base) Location() *Location {44 return e.CallStack[0].Location()45}46func (e *Base) String() string {47 var td string48 loc := e.Location()49 if e.Text != "" || len(e.Fields) > 0 {50 td = fmt.Sprintf(": %s", textAndFields(e.Text, e.Fields))51 }52 return fmt.Sprintf("%s:%d%s", loc.File, loc.Line, td)53}54// MarshalJSON creates a JSON representation of a Error.55func (e *Base) MarshalJSON() ([]byte, error) {56 m := make(Fields)57 loc := e.Location()58 m["file"] = loc.File59 m["line"] = loc.Line60 m["func"] = loc.Func61 if e.Text != "" {62 m["text"] = e.Text63 }64 if len(e.Fields) > 0 {65 m["fields"] = e.Fields66 }67 return json.Marshal(m)68}69// Stack returns the call stack from where this Error was created.70func (e *Base) Stack() CallStack {71 return e.CallStack72}73func combineFields(f1 Fields, f2 Fields) Fields {74 data := make(Fields, len(f1)+len(f2))75 for k, v := range f1 {76 data[k] = v77 }78 for k, v := range f2 {79 data[k] = v80 }81 return data82}83func textAndFields(text string, fields Fields) string {84 buf := &bytes.Buffer{}85 if text != "" {86 buf.WriteString(text)87 }88 for k, v := range fields {89 buf.WriteByte(' ')90 buf.WriteString(k)91 buf.WriteByte('=')92 fmt.Fprintf(buf, "%+v", v)93 }94 return string(buf.Bytes())95}...

Full Screen

Full Screen

newBase

Using AI Code Generation

copy

Full Screen

1import "fmt"2type td struct {3}4func main() {5 a = newBase(3, 4)6 fmt.Println(a.x, a.y)7}8func newBase(x, y int) td {9 return td{x, y}10}11type td struct {12}13type td struct {14}15type td struct {16}17type td struct {18}19type td struct {20}21type td struct {22}23type td struct {24}25type td struct {26}27type td struct {28}29type td struct {30}

Full Screen

Full Screen

newBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 td := newBase()4 fmt.Println(td.a, td.b)5}6import (7func main() {8 td := newBase()9 fmt.Println(td.a, td.b)10}11import (12func main() {13 td := newBase()14 fmt.Println(td.a, td.b)15}16import (17func main() {18 td := newBase()19 fmt.Println(td.a, td.b)20}21import (22func main() {23 td := newBase()24 fmt.Println(td.a, td.b)25}26import (27func main() {28 td := newBase()29 fmt.Println(td.a, td.b)30}31import (32func main() {33 td := newBase()34 fmt.Println(td.a, td.b)35}36import (37func main() {38 td := newBase()39 fmt.Println(td.a, td.b)40}41import (42func main() {43 td := newBase()44 fmt.Println(td.a, td.b)45}46import (

Full Screen

Full Screen

newBase

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 b := td.NewBase(2, 3)4 fmt.Println(b)5}6import (7func main() {8 b := td.NewBase(2, 3)9 fmt.Println(b)10}11import (12func main() {13 b := td.NewBase(2, 3)14 fmt.Println(b)15}16import (17func main() {18 b := td.NewBase(2, 3)19 fmt.Println(b)20}21import (22func main() {23 b := td.NewBase(2, 3)24 fmt.Println(b)25}26import (27func main() {28 b := td.NewBase(2, 3)29 fmt.Println(b)30}31import (32func main() {33 b := td.NewBase(2, 3)34 fmt.Println(b)35}36import (37func main() {38 b := td.NewBase(2, 3)39 fmt.Println(b)40}41import (42func main() {43 b := td.NewBase(2, 3)44 fmt.Println(b)45}46import (47func main() {48 b := td.NewBase(2, 3)49 fmt.Println(b)50}

Full Screen

Full Screen

newBase

Using AI Code Generation

copy

Full Screen

1import (2type td struct {3}4func main() {5 fmt.Println("hello world")6 t := td{name: "hello"}7 t.newBase()8}9import (10type td struct {11}12func (t td) newBase() {13 fmt.Println("hello world")14}15func main() {16 fmt.Println("hello world")17 t := td{name: "hello"}18 t.newBase()19}20import (21type td struct {22}23func (t td) newBase() {24 fmt.Println("hello world")25}26func main() {27 fmt.Println("hello world")28 t := td{name: "hello"}29 t.newBase()30}31import (32type td struct {33}34func (t td) newBase() {35 fmt.Println("hello world")36}37func main() {38 fmt.Println("hello world")39 t := td{name: "hello"}40 t.newBase()41}42import (43type td struct {44}45func (t td) newBase() {46 fmt.Println("hello world")47}48func main() {49 fmt.Println("hello world")50 t := td{name: "hello"}51 t.newBase()52}53import (54type td struct {55}56func (t td) newBase() {57 fmt.Println("hello world")58}59func main() {60 fmt.Println("hello world")61 t := td{name: "hello"}62 t.newBase()63}64import (65type td struct {66}67func (t td) newBase() {68 fmt.Println("hello world")69}70func main() {71 fmt.Println("hello world")72 t := td{name: "hello"}73 t.newBase()74}

Full Screen

Full Screen

newBase

Using AI Code Generation

copy

Full Screen

1td1 := new(td)2td1.newBase()3println(td1.base)4println(td1.name)5println(td1.age)6println(td1.newBase())7td1 := new(td)8td1.newBase()9println(td1.base)10println(td1.name)11println(td1.age)12println(td1.newBase())13td1 := new(td)14td1.newBase()15println(td1.base)16println(td1.name)17println(td1.age)18println(td1.newBase())19td1 := new(td)20td1.newBase()21println(td1.base)22println(td1.name)23println(td1.age)24println(td1.newBase())25td1 := new(td)26td1.newBase()27println(td1.base)28println(td1.name)29println(td1.age)30println(td1.newBase())31td1 := new(td)32td1.newBase()33println(td1.base)34println(td1.name)35println(td1.age)36println(td1.newBase())

Full Screen

Full Screen

newBase

Using AI Code Generation

copy

Full Screen

1func main(){2 td.newBase(2, 3)3 fmt.Println(td.x)4}5type td struct {6}7func (td *td) newBase(a, b int) {8}9type td struct {10}11func (td *td) newBase(a, b int) {12}13import (14func main(){15 td.newBase(2, 3)16 fmt.Println(td.x)17}18type td struct {19}20func (td *td) newBase(a, b int) {21}22import (23func main(){24 td.newBase(2, 3)25 fmt.Println(td.x)26}27type td struct {28}29func (td *td) newBase(a, b int) {30}31import (32func main(){33 td.newBase(2, 3)34 fmt.Println(td.x)35}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Go-testdeep automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful