Best K6 code snippet using html.ParentElement
crud_list.go
Source:crud_list.go
1package controllers2import (3 "fmt"4 "regexp"5 "strings"6 "github.com/beego/beego/v2/core/logs"7 "github.com/pbillerot/beedule/dico"8 "github.com/pbillerot/beedule/models"9 beego "github.com/beego/beego/v2/adapter"10 "github.com/beego/beego/v2/client/orm"11)12// CrudListController as13type CrudListController struct {14 loggedRouter15}16// CrudList CrudListController17func (c *CrudListController) CrudList() {18 appid := c.Ctx.Input.Param(":app")19 tableid := c.Ctx.Input.Param(":table")20 viewid := c.Ctx.Input.Param(":view")21 // mémorisation de la recherche dans la vue22 var uiView UIView23 err = uiView.load(c.Controller, appid, tableid, viewid, dico.Element{})24 if err != nil {25 backward(c.Controller)26 return27 }28 if c.GetString("from-card-view") != "" {29 backward(c.Controller)30 return31 }32 // Remplissage du contexte pour le template33 setContext(c.Controller, appid, uiView.TableID)34 c.Data["AppId"] = uiView.AppID35 c.Data["Application"] = dico.Ctx.Applications[uiView.AppID]36 c.Data["UIView"] = &uiView37 // Positionnement du navigateur sur la page qui va s'ouvrir38 forward(c.Controller, fmt.Sprintf("/bee/list/%s/%s/%s", appid, tableid, viewid))39 if uiView.View.Type == "card" {40 c.TplName = "crud_list_card.html"41 } else if uiView.View.Type == "table" {42 c.TplName = "crud_list_table.html"43 } else if uiView.View.Type == "dashboard" {44 c.Ctx.Redirect(302, "/bee/dashboard/"+appid+"/"+tableid+"/"+viewid)45 // c.TplName = "crud_dashboard.html"46 } else {47 c.TplName = "crud_list_card.html"48 }49}50// UIView Vue51type UIView struct {52 Title string53 AppID string54 TableID string55 ViewID string56 Table dico.Table57 View dico.View58 Elements map[string]dico.Element59 Records []orm.Params60 Qrecords int61 Cols map[int]string62 SortID string63 SortDirection string64 Search string65 SearchStop string66}67func (ui *UIView) load(c beego.Controller, appid string, tableid string, viewid string, parentElement dico.Element) (err error) {68 ui.AppID = appid69 ui.TableID = tableid70 ui.ViewID = viewid71 flash := beego.ReadFromRequest(&c)72 // Ctrl appid tableid viewid formid73 if _, ok := dico.Ctx.Applications[appid]; !ok {74 err = fmt.Errorf("app not found %s", appid)75 logs.Error(err.Error())76 flash.Error(err.Error())77 flash.Store(&c)78 return79 }80 if val, ok := dico.Ctx.Applications[appid].Tables[tableid]; ok {81 if _, ok := val.Views[viewid]; ok {82 } else {83 err = fmt.Errorf("view not found %s", viewid)84 logs.Error(err.Error())85 flash.Error(err.Error())86 flash.Store(&c)87 return88 }89 } else {90 err = fmt.Errorf("table not found %s", tableid)91 logs.Error(err.Error())92 flash.Error(err.Error())93 flash.Store(&c)94 return95 }96 // Contrôle d'accès à la vue97 table := dico.Ctx.Applications[appid].Tables[tableid]98 view := dico.Ctx.Applications[appid].Tables[tableid].Views[viewid]99 ui.Table = *table100 ui.View = view101 ui.Title = view.Title102 if view.Group == "" {103 view.Group = dico.Ctx.Applications[appid].Group104 }105 if !IsInGroup(c, view.Group, appid, "") {106 err = fmt.Errorf("accès non autorisé de %s à %s", viewid, view.Group)107 logs.Error(err.Error())108 flash.Error(err.Error())109 flash.Store(&c)110 return111 }112 // Ctrl d'accès FormAdd FormView FormEdit113 if !IsInGroup(c, table.Forms[view.FormView].Group, appid, "") {114 view.FormView = ""115 }116 if !IsInGroup(c, table.Forms[view.FormAdd].Group, appid, "") {117 view.FormAdd = ""118 }119 if !IsInGroup(c, table.Forms[view.FormEdit].Group, appid, "") {120 view.FormEdit = ""121 }122 // Gestion du TRI enregistré dans la session et contexte123 sortID := ""124 sortDirection := ""125 ctxSortid := fmt.Sprintf("%s-%s-%s-sortid", appid, tableid, viewid)126 ctxSortdirection := fmt.Sprintf("%s-%s-%s-sortdirection", appid, tableid, viewid)127 if c.GetSession(ctxSortid) != nil {128 sortID = c.GetSession(ctxSortid).(string)129 }130 if c.GetSession(ctxSortdirection) != nil {131 sortDirection = c.GetSession(ctxSortdirection).(string)132 }133 // Data récupéré dans mergeElements et dans le template ensuite134 ui.SortID = sortID135 ui.SortDirection = sortDirection136 // Fusion des attributs des éléments de la table dans les éléments de la vue137 // en intégrant les éléments de tri fournis dans c.Data138 c.Data["SortID"] = sortID139 c.Data["SortDirection"] = sortDirection140 elements, cols := mergeElements(c, appid, tableid, dico.Ctx.Applications[appid].Tables[tableid].Views[viewid].Elements, "")141 ui.Cols = cols142 // Calcul des champs SQL de la vue143 if view.OrderBy != "" {144 view.OrderBy = macro(c, appid, view.OrderBy, orm.Params{})145 }146 if view.FooterSQL != "" {147 view.FooterSQL = requeteSQL(c, appid, view.FooterSQL, orm.Params{}, dico.Ctx.Applications[appid].Tables[tableid].Setting.AliasDB)148 }149 if len(view.PreUpdateSQL) > 0 {150 for _, presql := range view.PreUpdateSQL {151 // Remplissage d'un record avec les elements.SQLout152 record := orm.Params{}153 sql := macro(c, appid, presql, record)154 if sql != "" {155 err = models.CrudExec(sql, table.Setting.AliasDB)156 if err != nil {157 flash.Error(err.Error())158 flash.Store(&c)159 }160 }161 }162 }163 // CAS appel d'une vue dans le formulaire164 if parentElement.Params.View != "" {165 if parentElement.Params.Where != "" {166 view.Where = macro(c, appid, parentElement.Params.Where, parentElement.Record)167 } else {168 if view.Where != "" {169 view.Where = macro(c, appid, view.Where, orm.Params{})170 }171 }172 if parentElement.LabelLong != "" {173 view.Title = parentElement.LabelLong174 }175 if parentElement.IconName != "" {176 view.IconName = parentElement.IconName177 }178 }179 // RECHERCHE DANS LA VUE180 search := ""181 ctxSearch := fmt.Sprintf("%s-%s-%s-search", appid, tableid, viewid)182 if c.GetSession(ctxSearch) != nil {183 search = c.GetSession(ctxSearch).(string)184 }185 if search != "" {186 var colName string187 var val string188 var ope string189 re := regexp.MustCompile(`^(.*):(.*)`)190 match := re.FindStringSubmatch(search)191 if len(match) > 0 {192 colName = match[1]193 val = match[2]194 ope = "LIKE"195 }196 re = regexp.MustCompile(`^(.*)=(.*)`)197 match = re.FindStringSubmatch(search)198 if len(match) > 0 {199 colName = match[1]200 val = match[2]201 ope = "="202 }203 for key, element := range elements {204 if strings.HasPrefix(key, "_") {205 continue206 }207 if ope != "" && key == colName {208 // recherche sur une seule colonne209 switch element.Type {210 case "checkbox":211 if strings.Contains(strings.ToLower(element.LabelShort), search) {212 if view.Search != "" {213 view.Search += " OR "214 }215 if element.Jointure.Column != "" {216 view.Search += element.Jointure.Column + " = '1'"217 } else {218 view.Search += tableid + "." + key + " = '1'"219 }220 }221 case "list":222 // TODO recherche dans le label du list223 default:224 if view.Search != "" {225 view.Search += " OR "226 }227 if element.Jointure.Column != "" {228 if ope == "=" {229 view.Search += "cast(" + element.Jointure.Column + " as TEXT) = '" + val + "'"230 } else {231 view.Search += "cast(" + element.Jointure.Column + " as TEXT) = '" + val + "'"232 }233 } else {234 if ope == "=" {235 view.Search += "cast(" + tableid + "." + key + " as TEXT) = '" + val + "'"236 } else {237 view.Search += "cast(" + tableid + "." + key + " as TEXT) LIKE '%" + val + "%'"238 }239 }240 }241 break242 }243 switch element.Type {244 case "checkbox":245 if strings.Contains(strings.ToLower(element.LabelShort), search) {246 if view.Search != "" {247 view.Search += " OR "248 }249 if element.Jointure.Column != "" {250 view.Search += element.Jointure.Column + " = '1'"251 } else {252 view.Search += tableid + "." + key + " = '1'"253 }254 }255 case "list":256 // TODO recherche dans le label du list257 default:258 if view.Search != "" {259 view.Search += " OR "260 }261 if element.Jointure.Column != "" {262 view.Search += "cast(" + element.Jointure.Column + " as TEXT) LIKE '%" + search + "%'"263 } else {264 view.Search += "cast(" + tableid + "." + key + " as TEXT) LIKE '%" + search + "%'"265 }266 }267 }268 }269 // Filtrage si élément owner270 for key, element := range elements {271 // Un seule élément owner par enregistrement272 if element.Group == "owner" && !IsAdmin(c) {273 if view.Search != "" {274 view.Search = "(" + view.Search + ") AND "275 }276 view.Search += tableid + "." + key + " = '" + c.GetSession("Username").(string) + "'"277 break278 }279 }280 ui.Search = search281 // lecture des records282 records, err := models.CrudList(appid, tableid, viewid, &view, elements)283 ui.Records = records284 if err != nil {285 flash.Error(err.Error())286 flash.Store(&c)287 }288 if len(records) > 0 {289 // Calcul des éléments hors values290 elements = computeElements(c, false, elements, records[0])291 ui.Qrecords = len(records)292 }293 ui.Elements = elements294 return nil295}...
rice-box.go
Source:rice-box.go
1package main2import (3 "github.com/GeertJohan/go.rice/embedded"4 "time"5)6func init() {7 // define files8 file2 := &embedded.EmbeddedFile{9 Filename: `index.html`,10 FileModTime: time.Unix(1477658429, 0),11 Content: string("<!doctype html>\n<!--\nCopyright 2016 Google Inc. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n-->\n<head>\n <style>\n :root {\n font-family: monospace;\n font-size: 20px;\n }\n .template {\n display: none;\n }\n input, select, option {\n font-family: monospace;\n font-size: 1rem;\n }\n input {\n border: 0;\n border-bottom: 1px solid black;\n }\n </style>\n</head>\n<body>\n <select id=\"method\">\n <option selected>GET</option>\n <option>POST</option>\n <option>PUT</option>\n <option>DELETE</option>\n <option>HEAD</option>\n <option>OPTIONS</option>\n </select> <input type=\"text\" id=\"url\" placeholder=\"/kitty.jpg\"> HTTP/1.1<br>\n <div>\n Host: <input type=\"text\" placeholder=\"www.google.com\">\n </div>\n <div class=\"template header\">\n <input type=\"text\" placeholder=\"X-Forwarded-for\">: <input type=\"text\" placeholder=\"Value\">\n <button>-</button><br>\n </div>\n <div>\n <button id=\"addheader\">+</button>\n </div>\n <br>\n <script>\n (function() {\n var $ = document.querySelector.bind(document);\n var output = $('pre');\n var deleteHeaderFunc = function(ev) {\n ev.target.parentElement.parentElement.removeChild(ev.target.parentElement);\n };\n $('#addheader').addEventListener('click', function(ev) {\n var n = $('.header.template').cloneNode(true);\n n.classList.remove('template');\n n.querySelector('button').addEventListener('click', deleteHeaderFunc);\n ev.target.parentElement.parentElement.insertBefore(n, ev.target.parentElement);\n });\n $('#send').addEventListener('click', function() {\n var headers = {};\n Array.prototype.forEach.call(document.querySelectorAll('.header:not(.template)'), function(fields) {\n var header = fields.querySelector('input:nth-of-type(1)').value;\n var value = fields.querySelector('input:nth-of-type(2)').value;\n headers[header] = value;\n });\n });\n })();\n </script>\n</body>\n"),12 }13 // define dirs14 dir1 := &embedded.EmbeddedDir{15 Filename: ``,16 DirModTime: time.Unix(1477658429, 0),17 ChildFiles: []*embedded.EmbeddedFile{18 file2, // index.html19 },20 }21 // link ChildDirs22 dir1.ChildDirs = []*embedded.EmbeddedDir{}23 // register embeddedBox24 embedded.RegisterEmbeddedBox(`assets`, &embedded.EmbeddedBox{25 Name: `assets`,26 Time: time.Unix(1477658429, 0),27 Dirs: map[string]*embedded.EmbeddedDir{28 "": dir1,29 },30 Files: map[string]*embedded.EmbeddedFile{31 "index.html": file2,32 },33 })34}...
parser.go
Source:parser.go
1package gen2import (3 "fmt"4 "io"5 "strconv"6 "golang.org/x/net/html"7)8func parseNode(node *html.Node) *ElementNode {9 res := &ElementNode{}10 res.Children = make([]*ElementNode, 0)11 res.Type = node.Data12 for _, attr := range node.Attr {13 switch attr.Key {14 case "colspan":15 res.Colspan, _ = strconv.Atoi(attr.Val)16 case "namespace":17 res.Namespace = attr.Val18 case "background-color":19 if res.Background == nil {20 res.Background = &Background{}21 }22 res.Background.Color = attr.Val23 case "text-align":24 if res.Text == nil {25 res.Text = &Text{}26 }27 res.Text.Align = attr.Val28 case "font-size":29 if res.Font == nil {30 res.Font = &Font{}31 }32 res.Font.Size, _ = strconv.Atoi(attr.Val)33 case "font-color":34 if res.Font == nil {35 res.Font = &Font{}36 }37 res.Font.Color = attr.Val38 }39 }40 return res41}42func parse(template io.Reader) *ElementNode {43 raw, _ := html.Parse(template)44 var process func(*html.Node, *ElementNode)45 var doc *ElementNode46 process = func(node *html.Node, parentElement *ElementNode) {47 if node.Type == html.TextNode {48 if node.Data != "" && parentElement != nil {49 parentElement.Data = node.Data50 }51 } else {52 var ele *ElementNode53 if node.Type == html.ElementNode {54 ele = parseNode(node)55 fmt.Printf("Parse node %s\n", ele.Type)56 if ele.Type == "document" {57 doc = ele58 } else if parentElement != nil {59 parentElement.Children = append(parentElement.Children, ele)60 }61 }62 for child := node.FirstChild; child != nil; child = child.NextSibling {63 process(child, ele)64 }65 }66 }67 process(raw, nil)68 return doc69}...
ParentElement
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v6 os.Exit(1)7 }8 for _, link := range visit(nil, doc) {9 fmt.Println(link)10 }11}12func visit(links []string, n *html.Node) []string {13 if n.Type == html.ElementNode && n.Data == "a" {14 for _, a := range n.Attr {15 if a.Key == "href" {16 links = append(links, a.Val)17 }18 }19 }20 for c := n.FirstChild; c != nil; c = c.NextSibling {21 links = visit(links, c)22 }23}24import (25func main() {26 doc, err := html.Parse(os.Stdin)27 if err != nil {28 fmt.Fprintf(os.Stderr, "findlinks1: %v29 os.Exit(1)30 }31 for _, link := range visit(nil, doc) {32 fmt.Println(link)33 }34}35func visit(links []string, n *html.Node) []string {36 if n.Type == html.ElementNode && n.Data == "a" {37 for _, a := range n.Attr {38 if a.Key == "href" {39 links = append(links, a.Val)40 }41 }42 }43 for c := n.FirstChild; c != nil; c = c.NextSibling {44 links = visit(links, c)45 }46}47import (48func main() {49 doc, err := html.Parse(os.Stdin)50 if err != nil {51 fmt.Fprintf(os.Stderr, "findlinks1: %v52 os.Exit(1)53 }54 for _, link := range visit(nil, doc) {55 fmt.Println(link)56 }57}58func visit(links []string, n *html.Node) []string {
ParentElement
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatalln(err)5 }6 defer resp.Body.Close()7 doc, err := goquery.NewDocumentFromReader(resp.Body)8 if err != nil {9 log.Fatalln(err)10 }11 doc.Find("a").Each(func(i int, s *goquery.Selection) {12 linkTag := s.Parent()13 fmt.Println(linkTag.Text())14 })15}16import (17func main() {18 if err != nil {19 log.Fatalln(err)20 }21 defer resp.Body.Close()22 doc, err := goquery.NewDocumentFromReader(resp.Body)23 if err != nil {24 log.Fatalln(err)25 }26 doc.Find("a").Each(func(i int, s *goquery.Selection) {27 if s.HasClass("gb_P") {28 fmt.Println(s.Text())29 }30 })31}
ParentElement
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Print("Document not found")5 }6 doc.Find(".gb_P").Each(func(i int, s *goquery.Selection) {7 band := s.Find("a").Text()8 fmt.Printf("Review %d: %s - ", i, band)9 title := s.Find("span").Text()10 fmt.Printf(" %s\n", title)11 })12}
ParentElement
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 doc.Find(".w3-bar-item").Each(func(i int, s *goquery.Selection) {7 band := s.Find("a").Text()8 title := s.Find("a").Parent().Text()9 fmt.Printf("Review %d: %s - %s\n", i, band, title)10 })11}
ParentElement
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer res.Body.Close()7 if res.StatusCode != 200 {8 log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)9 }10 doc, err := goquery.NewDocumentFromReader(res.Body)11 if err != nil {12 log.Fatal(err)13 }14 doc.Find(".review").Each(func(i int, s *goquery.Selection) {15 band := s.Find("h2").Text()16 title := s.Find("h3").Text()17 fmt.Printf("Review %d: %s - %s18 })19}
ParentElement
Using AI Code Generation
1import (2func main() {3 doc, _ := goquery.NewDocument(url)4 doc.Find("a").Each(func(index int, item *goquery.Selection) {5 fmt.Println("Link: ", item.Text(), " -> ", item.AttrOr("href", "NA"))6 fmt.Println("Parent: ", item.Parent().Text())7 })8}
ParentElement
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 doc.Find(".navbar-nav").Each(func(i int, s *goquery.Selection) {7 band := s.Find("a").Text()8 title := s.Find("a").Attr("href")9 fmt.Printf("Review %d: %s - %s10 })11}
ParentElement
Using AI Code Generation
1import (2func main() {3 resp, err := http.Get(url)4 if err != nil {5 log.Fatal(err)6 }7 defer resp.Body.Close()8 body, err := ioutil.ReadAll(resp.Body)9 if err != nil {10 log.Fatal(err)11 }12 doc, err := html.Parse(strings.NewReader(string(body)))13 if err != nil {14 log.Fatal(err)15 }16 visit(doc, &links)17 for _, link := range links {18 fmt.Println(link)19 }20}21func visit(n *html.Node, links *[]string) {22 if n.Type == html.ElementNode && n.Data == "a" {23 for _, a := range n.Attr {24 if a.Key == "href" {25 *links = append(*links, a.Val)26 }27 }28 }29 for c := n.FirstChild; c != nil; c = c.NextSibling {30 visit(c, links)31 }32}33import (34func main() {35 resp, err := http.Get(url)36 if err != nil {37 log.Fatal(err)38 }39 defer resp.Body.Close()40 body, err := ioutil.ReadAll(resp.Body)
ParentElement
Using AI Code Generation
1import (2func main() {3 f, err := os.Open("test.html")4 if err != nil {5 fmt.Println(err)6 }7 z := html.NewTokenizer(f)8 for {9 tt := z.Next()10 switch {11 t := z.Token()12 if t.Data == "div" {13 for _, a := range t.Attr {14 if a.Key == "id" && a.Val == "main" {15 fmt.Println(p.Data)16 }17 }18 }19 }20 }21}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!