{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== '免费Z-image图片生成' && linkText !== '免费Z-image图片生成' ) { link.textContent = '免费Z-image图片生成'; link.href = 'https://zimage.run'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Vibevoice' ) { link.textContent = 'Vibevoice'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 替换Pricing链接 - 仅替换一次 else if ( (linkHref.includes('/pricing') || linkHref === '/pricing' || linkText === 'Pricing' || linkText.match(/^s*Pricings*$/i)) && linkText !== '免费去水印' ) { link.textContent = '免费去水印'; link.href = 'https://sora2watermarkremover.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'GitHub加速' ) { link.textContent = 'GitHub加速'; link.href = 'https://githubproxy.cc'; replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, '免费Z-image图片生成'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \"\n\tresultPage = `` + bootstrap + `\n\t\t\t{{.ErrorMessage}}

{{if .Artist}}{{.Artist}} - {{.TrackName}}{{end}}

\n\t\t \n\t\t\t`\n\n\thourRegex = regexp.MustCompile(\"([0-9]+)h\")\n\tminuteRegex = regexp.MustCompile(\"([0-9]+)m\")\n\tsecondRegex = regexp.MustCompile(\"([0-9]+)s\")\n\tcleanUrlRegex = regexp.MustCompile(\"(.*)\\\\?\")\n\tnotRecognisedMessage = \"Track could not be recognised.\"\n)\n\nfunc main() {\n\tloadCacheFromDisc()\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(20 * time.Second)\n\t\t\tsaveCacheToDisc()\n\t\t}\n\t}()\n\tServe()\n}\n\ntype Result struct {\n\tErrorMessage string `json:\"error,omitempty\"`\n\tArtist string `json:\"artist,omitempty\"`\n\tTrackName string `json:\"trackName,omitempty\"`\n\tRawBody string `json:\"rawBody,omitempty\"`\n}\n\nfunc Serve() {\n\tfs := http.FileServer(http.Dir(\"frontend\"))\n\thttp.Handle(\"/\", fs)\n\thttp.HandleFunc(\"/stats\", func(rw http.ResponseWriter, req *http.Request) {\n\t\tdump, err := dumpCache()\n\t\tif err != nil {\n\t\t\trw.Write([]byte(err.Error()))\n\t\t}\n\t\trw.Write(dump)\n\t})\n\tthrottledRecogniser := newThrottledRecogniser()\n\n\thttp.HandleFunc(\"/api/recognise\", func(rw http.ResponseWriter, req *http.Request) {\n\t\tq := req.URL.Query()\n\t\tsongUrl := q[\"url\"][0]\n\t\tsongUrl = cleanUrl(songUrl)\n\t\tts := q[\"t\"][0]\n\t\tresult := throttledRecogniser(songUrl, ts)\n\n\t\tif result.RawBody != \"\" {\n\t\t\trw.Write([]byte(result.RawBody))\n\t\t\treturn\n\t\t}\n\n\t\tt := template.New(\"some template\") // Create a template.\n\t\t//t2, err := t.ParseFiles(\"./frontend/result_page.html\") // Parse template file.\n\t\tt2, err := t.Parse(resultPage) // Parse template file.\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tt2.Execute(rw, *result)\n\t})\n\tlog.Fatal(http.ListenAndServe(\":3000\", nil))\n}\n\nfunc newThrottledRecogniser() func(songUrl string, ts string) *Result {\n\trecognitionSP := slotprovider.New(5)\n\treturn func(songUrl, ts string) *Result {\n\t\ttimeInSeconds, err := extractTimeInSeconds(ts)\n\t\tif err != nil {\n\t\t\treturn &Result{ErrorMessage:err.Error()}\n\t\t}\n\t\ttimeInSeconds = floorToInterval(timeInSeconds, 30)\n\t\tfullUrl := songUrl + \"#t=\" + strconv.Itoa(timeInSeconds) + \"s\"\n\t\tinitialized, res := getFromCache(fullUrl)\n\t\tif res != nil {\n\t\t\tlog.Printf(\"Responding to %v with cached result\", fullUrl)\n\t\t\treturn res\n\t\t} else if initialized {\n\t\t\t// this item is processing currently\n\t\t\tlog.Printf(\"Responding to %v with 'in progress'\", fullUrl)\n\t\t\treturn &Result{RawBody:inProgressMessage}\n\t\t}\n\t\t//else start recognition\n\n\t\tisSlotAcquired, releaseSlot := recognitionSP.AcquireSlot()\n\t\tif !isSlotAcquired {\n\t\t\tlog.Printf(\"Responding to %v with 'no free slots'\", fullUrl)\n\t\t\treturn &Result{ErrorMessage:\"Request limit reached. We are not able to recognize more songs at the moment. Please try later.\"}\n\t\t}\n\t\treserveCache(fullUrl)\n\n\t\tgo func() {\n\t\t\tdefer releaseSlot()\n\t\t\tlog.Printf(\"Start recognition of %v\", fullUrl)\n\t\t\tresult := RecogniseSong(songUrl, timeInSeconds)\n\t\t\tres := parseResult(result)\n\t\t\tputResultToCache(fullUrl, res)\n\t\t}()\n\t\tlog.Printf(\"Responding to %v with 'in progress' and start recognition\", fullUrl)\n\t\treturn &Result{RawBody:inProgressMessage}\n\t}\n\n}\n\nfunc floorToInterval(time int, intervall int) int {\n\tfx := float32(time) / float32(intervall)\n\tf := time / intervall\n\tif fx - float32(f) < 0.5 {\n\t\treturn f * intervall\n\t} else {\n\t\treturn (f + 1) * intervall\n\t}\n}\n\nfunc parseResult(result string) *Result {\n\tsj, err := simplejson.NewJson([]byte(result))\n\tif err != nil {\n\t\treturn &Result{ErrorMessage:\"Error occurred\"}\n\t}\n\n\tnoResult, err := (*sj).GetPath(\"status\", \"msg\").String()\n\tif noResult == \"No result\" {\n\t\treturn &Result{ErrorMessage:notRecognisedMessage}\n\t}\n\n\tartist, err := (*sj).GetPath(\"metadata\", \"music\").GetIndex(0).Get(\"artists\").GetIndex(0).Get(\"name\").String()\n\tif err != nil {\n\t\treturn &Result{ErrorMessage:\"Error occurred\"}\n\t}\n\n\ttrackName, err := (*sj).GetPath(\"metadata\", \"music\").GetIndex(0).Get(\"title\").String()\n\tif err != nil {\n\t\treturn &Result{ErrorMessage:\"Error occurred\"}\n\t} else {\n\n\t\treturn &Result{Artist:artist, TrackName:trackName}\n\t}\n}\n\nfunc RecogniseSong(songUrl string, timeInSeconds int) (string) {\n\tfilePath, err := downloadSong(songUrl)\n\tif err != nil {\n\t\treturn \"Error while downloading: \" + err.Error()\n\t}\n\tresult, err := sendSongToACR(filePath, timeInSeconds)\n\tif err != nil {\n\t\treturn \"Error while recognizing: \" + err.Error()\n\t}\n\treturn result\n}\n\nfunc downloadSong(songUrl string) (string, error) {\n\tvar fileName string\n\tvar err error\n\tif strings.Contains(songUrl, \"youtube\") {\n\t\tfileName, err = executeAndGetLastLine(\"./download_youtube.sh\", songUrl)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else if strings.Contains(songUrl, \"soundcloud\") {\n\t\tfileName, err = executeAndGetLastLine(\"./download_soundcloud.sh\", songUrl)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tlog.Println(\"Downloaded song to file: \", fileName, songUrl)\n\treturn fileName, nil\n}\n\nfunc sendSongToACR(filePath string, timeInSeconds int) (string, error) {\n\treturn executeAndGetLastLine(\"./recognise.sh\", filePath, strconv.Itoa(timeInSeconds))\n}\n\nfunc executeAndGetLastLine(script string, opts... string) (string, error) {\n\tout, err := exec.Command(script, opts...).Output()\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Script %v failed with %v\\n\", script, err)\n\t\treturn \"\", err\n\t}\n\tlog.Printf(\"[SUCCESS] Script %v finished\\n\", script)\n\treturn getLastLine(string(out)), nil\n}\n\n// ### HELPER ####\nfunc getLastLine(input string) string {\n\tlines := strings.Split(string(input), \"\\n\")\n\tres := \"unknown error occurred\"\n\tfor i := len(lines) - 1; i >= 0; i-- {\n\t\tif lines[i] != \"\" {\n\t\t\tres = lines[i]\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn res\n}\n\nfunc extractTimeInSeconds(timestamp string) (int, error) {\n\tif timestamp == \"\" {\n\t\treturn 0, nil\n\t} else if strings.Contains(timestamp, \"s\") || strings.Contains(timestamp, \"h\") || strings.Contains(timestamp, \"m\") {\n\t\treturn extractFromHMSFormat(timestamp)\n\t} else {\n\t\treturn extractFromCOLONFormat(timestamp)\n\t}\n}\n\nfunc extractFromCOLONFormat(timestamp string) (int, error) {\n\tp := strings.Split(timestamp, \":\")\n\tfactor := int(math.Pow(float64(60), float64(len(p) - 1)))\n\ttotal := 0\n\tfor i := 0; i < len(p); i++ {\n\t\tc, err := strconv.Atoi(p[i])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttotal += c * factor\n\t\tfactor = factor / 60\n\t}\n\treturn total, nil\n}\n\nfunc extractFromHMSFormat(timestamp string) (int, error) {\n\tt := 0\n\tmatch := hourRegex.FindStringSubmatch(timestamp)\n\tif len(match) > 0 {\n\t\thrs, err := strconv.Atoi(match[1])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tt += hrs * 1200\n\t}\n\tmatch = minuteRegex.FindStringSubmatch(timestamp)\n\tif len(match) > 0 {\n\t\tmin, err := strconv.Atoi(match[1])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tt += min * 60\n\t}\n\tmatch = secondRegex.FindStringSubmatch(timestamp)\n\tif len(match) > 0 {\n\t\tsec, err := strconv.Atoi(match[1])\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tt += sec\n\t}\n\treturn t, nil\n}\n\nfunc cleanUrl(url string) string {\n\tif strings.Contains(url, \"soundcloud\") && strings.Contains(url, \"?\") {\n\t\turl = cleanUrlRegex.FindStringSubmatch(url)[0]\n\t\turl = url[:len(url) - 1]\n\t}\n\treturn url\n}\n\n\n\n// ############ Cache ############\nvar (\n\tcache = make(map[string]*Result)\n\tcacheMux = sync.Mutex{}\n\tInitialResult = &Result{ErrorMessage:\"Processing\"}\n)\n\nfunc reserveCache(id string) {\n\tcacheMux.Lock()\n\tdefer cacheMux.Unlock()\n\tcache[id] = InitialResult\n}\n\nfunc putResultToCache(id string, result *Result) {\n\tcacheMux.Lock()\n\tdefer cacheMux.Unlock()\n\tif cache[id] == nil {\n\t\tlog.Printf(\"Warning: Result for %v has been stored in cache without prior reservation\\n\", id)\n\t}\n\tcache[id] = result\n}\n\nfunc dumpCache() ([]byte, error) {\n\tcacheMux.Lock()\n\tdefer cacheMux.Unlock()\n\treturn json.Marshal(cache)\n}\n\nconst cacheDumpFilePath = \"cachedump.json\"\n\nfunc loadCacheFromDisc() {\n\tif content, err := ioutil.ReadFile(cacheDumpFilePath); err == nil {\n\t\tvar savedCache map[string]*Result\n\t\terr := json.Unmarshal(content, &savedCache)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tkeysToDelete := make([]string, 0)\n\t\tfor k, v := range savedCache {\n\t\t\tif v.ErrorMessage != \"\" && v.ErrorMessage != notRecognisedMessage {\n\t\t\t\tkeysToDelete = append(keysToDelete, k)\n\t\t\t}\n\t\t}\n\t\tfor _, k := range keysToDelete {\n\t\t\tdelete(savedCache, k)\n\t\t}\n\t\tcacheMux.Lock()\n\t\tdefer cacheMux.Unlock()\n\t\tcache = savedCache\n\t} else if !os.IsNotExist(err) {\n\t\tlog.Println(\"Could not load dump\", err)\n\t}\n}\n\nfunc saveCacheToDisc() {\n\tlog.Println(\"Saving result dump to disk\")\n\tvar f *os.File\n\tvar err error\n\n\tf, err = os.OpenFile(cacheDumpFilePath, os.O_CREATE | os.O_RDWR | os.O_TRUNC, 0666)\n\tdefer f.Close()\n\n\tbytes, err := dumpCache()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tf.Write(bytes)\n}\nfunc getFromCache(id string) (initialized bool, result *Result) {\n\tcacheMux.Lock()\n\tdefer cacheMux.Unlock()\n\texisting := cache[id]\n\tif existing == nil {\n\t\treturn false, nil\n\t}\n\tif existing == InitialResult {\n\t\treturn true, nil\n\t}\n\treturn true, existing\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":945,"cells":{"blob_id":{"kind":"string","value":"a34a69f3f28181f15382e8778e45df94172a0a20"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"TheFlies/ofriends"},"path":{"kind":"string","value":"/internal/app/visit/visit.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3320,"string":"3,320"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package visit\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/TheFlies/ofriends/internal/app/types\"\n\t\"github.com/TheFlies/ofriends/internal/pkg/glog\"\n\tvalidation \"github.com/go-ozzo/ozzo-validation\"\n)\n\n// Repository is an interface of a visit repository\ntype Repository interface {\n\tFindByID(ctx context.Context, id string) (*types.Visit, error)\n\tFindAll(ctx context.Context) ([]types.Visit, error)\n\tFindByCustomerID(ctx context.Context, customerId string) ([]types.Visit, error)\n\tCreate(ctx context.Context, visit types.Visit) (string, error)\n\tUpdate(ctx context.Context, visit types.Visit) error\n\tDelete(ctx context.Context, id string) error\n\tFindInCommingVisit(ctx context.Context, dayTime int64) ([]types.Visit, error)\n\tFindVisitsByDay(ctx context.Context, startTime, endTime int64) ([]types.Visit, error)\n}\n\ntype ActVisitAssocService interface {\n\tDeleteByVisitID(ctx context.Context, visitID string) error\n}\n\ntype CusVisitAssocService interface {\n\tDeleteByVisitID(ctx context.Context, visitID string) error\n}\n\n// Service is an visit service\ntype Service struct {\n\trepo Repository\n\tassocCusService CusVisitAssocService\n\tassocActService ActVisitAssocService\n\tlogger glog.Logger\n}\n\n// NewService return a new visit service\nfunc NewService(r Repository, assocCusService CusVisitAssocService, assocActService ActVisitAssocService, l glog.Logger) *Service {\n\treturn &Service{\n\t\trepo: r,\n\t\tassocCusService: assocCusService,\n\t\tassocActService: assocActService,\n\t\tlogger: l,\n\t}\n}\n\n// Get return given visit by his/her id\nfunc (s *Service) Get(ctx context.Context, id string) (*types.Visit, error) {\n\treturn s.repo.FindByID(ctx, id)\n}\n\n// Get all visits from database by customer ID\nfunc (s *Service) GetByCustomerID(ctx context.Context, customerId string) ([]types.Visit, error) {\n\treturn s.repo.FindByCustomerID(ctx, customerId)\n}\n\n// Get All return all visits from database\nfunc (s *Service) GetAll(ctx context.Context) ([]types.Visit, error) {\n\treturn s.repo.FindAll(ctx)\n}\n\n// Create a visit\nfunc (s *Service) Create(ctx context.Context, visit types.Visit) (string, error) {\n\tif err := validation.ValidateStruct(&visit,\n\t\tvalidation.Field(&visit.Lab, validation.Required),\n\t\tvalidation.Field(&visit.ArrivedTime, validation.Required),\n\t\tvalidation.Field(&visit.DepartureTime, validation.Required),\n\t); err != nil {\n\t\treturn \"\", err\n\t} // not empty\n\treturn s.repo.Create(ctx, visit)\n}\n\n// Update a visit\nfunc (s *Service) Update(ctx context.Context, visit types.Visit) error {\n\tif err := validation.ValidateStruct(&visit,\n\t\tvalidation.Field(&visit.ID, validation.Required),\n\t\tvalidation.Field(&visit.Lab, validation.Required),\n\t\tvalidation.Field(&visit.ArrivedTime, validation.Required),\n\t\tvalidation.Field(&visit.DepartureTime, validation.Required),\n\t); err != nil {\n\t\treturn err\n\t} // not empty\n\treturn s.repo.Update(ctx, visit)\n}\n\n// Delete a visit\nfunc (s *Service) Delete(ctx context.Context, id string) error {\n\tif err := s.assocActService.DeleteByVisitID(ctx, id); err != nil && err.Error() != \"not found\" {\n\t\tfmt.Println(err)\n\t\tfmt.Println(err.Error())\n\t\treturn err\n\t}\n\tif err := s.assocCusService.DeleteByVisitID(ctx, id); err != nil && err.Error() != \"not found\" {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tif err := s.repo.Delete(ctx, id); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":946,"cells":{"blob_id":{"kind":"string","value":"d5022b7e715e562c5efe6a338a8183f32f8ccd51"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"Tsuyoshi-Iwanaga/learning_go"},"path":{"kind":"string","value":"/003/06_struct.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":382,"string":"382"},"score":{"kind":"number","value":3.75,"string":"3.75"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport \"fmt\"\n\n// var mydata struct {\n// \tName string\n// \tData []int\n// }\n\ntype Mydata struct {\n\tName string\n\tData []int\n}\n\nfunc main() {\n\t// mydata.Name = \"Taro\"\n\t// mydata.Data = []int{10, 20, 30}\n\t// fmt.Println(mydata)\n\n\ttaro := Mydata{\"Taro\", []int{10, 20, 30}}\n\thanako := Mydata{Name: \"Hanako\", Data: []int{90, 80, 70}}\n\n\tfmt.Println(taro)\n\tfmt.Println(hanako)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":947,"cells":{"blob_id":{"kind":"string","value":"629eb5b6f97fe410473ce41355a81e851287a9d4"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"komkom/jsonc"},"path":{"kind":"string","value":"/jsonc/filter.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":15166,"string":"15,166"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package jsonc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"unicode\"\n\t\"unicode/utf8\"\n)\n\ntype TokenType int\n\ntype State interface {\n\tType() TokenType\n\tNext(r rune, f *Filter) error\n}\n\nvar ErrDontAdvance = fmt.Errorf(`do-not-advance`)\n\nconst (\n\tRoot TokenType = iota // 0\n\tObject // 1\n\tKey // 2\n\tKeyNoQuote // 3\n\tValue // 4\n\tValueNoQuote // 5\n\tValueMultiline // 6\n\tArray // 7\n\tComment // 8\n\tCommentMultiLine // 9\n)\n\ntype Filter struct {\n\tring *Ring\n\toutMinSize int\n\tstack []State\n\trootState *RootState\n\tdone bool\n\terr error\n\tformat bool\n\tnewlineCount int\n\tspace string\n\n\toutbuf []byte\n\tlastOut rune\n}\n\nfunc NewFilter(ring *Ring, outMinSize int, format bool, space string) *Filter {\n\treturn &Filter{\n\t\tring: ring,\n\t\toutMinSize: outMinSize,\n\t\trootState: &RootState{},\n\t\tformat: format,\n\t\tspace: space,\n\t\tlastOut: utf8.RuneError,\n\t}\n}\n\nfunc (f *Filter) Clear() {\n\tf.rootState.init = false\n\tf.outbuf = nil\n\tf.stack = nil\n\tf.done = false\n\tf.err = nil\n\tf.lastOut = utf8.RuneError\n}\n\nfunc (f *Filter) Done() bool {\n\treturn f.done\n}\n\nfunc (f *Filter) Err() error {\n\treturn f.err\n}\n\ntype RootState struct {\n\tinit bool\n}\n\nfunc (r *RootState) Type() TokenType {\n\treturn Root\n}\n\nfunc (r *RootState) Next(ru rune, f *Filter) error {\n\n\tif f.format {\n\t\tif ru == '\\n' {\n\t\t\tf.pushOut(ru)\n\t\t}\n\t}\n\n\t// check if comments need to be dispatched\n\tdispatch, err := dispatchComment(f, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dispatch {\n\t\treturn ErrDontAdvance\n\t}\n\n\tif !r.init {\n\t\tswitch ru {\n\t\tcase '{':\n\t\t\tr.init = true\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ObjectState{})\n\t\t\treturn nil\n\n\t\tcase '[':\n\t\t\tr.init = true\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ArrayState{})\n\t\t\treturn nil\n\n\t\tcase '\"':\n\t\t\tr.init = true\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ValueState{})\n\t\t\treturn nil\n\n\t\tcase '`':\n\t\t\tr.init = true\n\t\t\tif f.format {\n\t\t\t\tf.pushOut(ru)\n\t\t\t} else {\n\t\t\t\tf.pushOut('\"')\n\t\t\t}\n\t\t\tf.pushState(&ValueMultilineState{})\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif !unicode.IsSpace(ru) {\n\t\treturn Errorf(\"invalid first character: %v\", -1, string(ru))\n\t}\n\treturn nil\n}\n\ntype KeyState struct {\n\tescaped bool\n}\n\nfunc (o *KeyState) Type() TokenType {\n\treturn Key\n}\n\nfunc (k *KeyState) Next(ru rune, f *Filter) error {\n\n\tif !k.escaped && ru == '\"' {\n\n\t\tf.pushOut(ru)\n\t\tf.popState()\n\t\treturn nil\n\t}\n\n\tk.escaped = false\n\tif ru == '\\\\' {\n\t\tk.escaped = true\n\t}\n\n\tf.pushOut(ru)\n\treturn nil\n}\n\ntype ValueState struct {\n\tescaped bool\n}\n\nfunc (v *ValueState) Type() TokenType {\n\treturn Value\n}\n\nfunc (v *ValueState) Next(ru rune, f *Filter) error {\n\n\tif !v.escaped && ru == '\\n' {\n\t\treturn fmt.Errorf(`line break in string value`)\n\t}\n\n\tif !v.escaped && ru == '\"' {\n\t\tf.pushOut(ru)\n\t\tf.popState()\n\t\treturn nil\n\t}\n\n\tv.escaped = false\n\tif ru == '\\\\' {\n\t\tv.escaped = true\n\t}\n\n\tf.pushOut(ru)\n\treturn nil\n}\n\ntype KeyNoQuoteState struct {\n\tnotFirst bool\n}\n\nfunc (o *KeyNoQuoteState) Type() TokenType {\n\treturn KeyNoQuote\n}\n\nfunc (k *KeyNoQuoteState) Next(ru rune, f *Filter) error {\n\n\tif !k.notFirst {\n\t\tif !unicode.IsLetter(ru) && !unicode.IsDigit(ru) {\n\t\t\treturn Errorf(\"invalid key\", f.ring.Position())\n\t\t}\n\t}\n\n\tif !f.format {\n\t\tif !k.notFirst {\n\t\t\tf.pushOut('\"')\n\t\t}\n\t}\n\tk.notFirst = true\n\n\tif ru == ':' || ru == '/' || unicode.IsSpace(ru) {\n\n\t\tif !f.format {\n\t\t\tf.pushOut('\"')\n\t\t}\n\t\tf.popState()\n\t\treturn ErrDontAdvance\n\t}\n\n\tif !unicode.IsLetter(ru) && !unicode.IsDigit(ru) {\n\t\treturn Errorf(\"invalid key\", f.ring.Position())\n\t}\n\n\tf.pushOut(ru)\n\treturn nil\n}\n\ntype ValueNoQuoteState struct {\n\tcval []rune\n}\n\nfunc (o *ValueNoQuoteState) Type() TokenType {\n\treturn ValueNoQuote\n}\n\nfunc (v *ValueNoQuoteState) Next(ru rune, f *Filter) error {\n\n\trenderValue := func() error {\n\n\t\tf.popState()\n\t\tif len(v.cval) == 0 {\n\t\t\treturn Errorf(\"empty no quote state\", f.ring.Position())\n\t\t}\n\n\t\t// check if quotes are not needed\n\t\ts := string(v.cval)\n\t\tif IsNumber(s) ||\n\t\t\ts == `true` ||\n\t\t\ts == `false` ||\n\t\t\ts == `null` {\n\n\t\t\tf.pushRunes(v.cval)\n\t\t\treturn ErrDontAdvance\n\t\t}\n\n\t\tif !unicode.IsLetter(([]rune(s))[0]) {\n\t\t\treturn Errorf(\"invalid identifier\", f.ring.Position())\n\t\t}\n\n\t\tif f.format {\n\t\t\tf.pushRunes(v.cval)\n\t\t\treturn ErrDontAdvance\n\t\t}\n\n\t\t// quote the value\n\t\tf.pushOut('\"')\n\t\tf.pushRunes(v.cval)\n\t\tf.pushOut('\"')\n\n\t\treturn ErrDontAdvance\n\t}\n\n\tif unicode.IsSpace(ru) || ru == ',' || ru == '}' || ru == ']' || ru == '/' {\n\t\treturn renderValue()\n\t}\n\n\tif !unicode.IsLetter(ru) && !unicode.IsDigit(ru) && ru != '.' && ru != '+' {\n\t\treturn Errorf(\"invalid identifier\", f.ring.Position())\n\t}\n\n\tif ru == '\\\\' {\n\t\treturn Errorf(\"invalid identifier\", f.ring.Position())\n\t}\n\n\tv.cval = append(v.cval, ru)\n\treturn nil\n}\n\nvar (\n\tmultilineEscapes = []struct {\n\t\tcode rune\n\t\treplace rune\n\t}{\n\t\t{code: '\"', replace: '\"'},\n\t\t{code: '\\n', replace: 'n'},\n\t}\n)\n\nfunc needsReplacement(r rune) (replace rune, ok bool) {\n\n\tfor _, o := range multilineEscapes {\n\t\tif o.code == r {\n\t\t\treturn o.replace, true\n\t\t}\n\t}\n\treturn replace, false\n}\n\ntype ValueMultilineState struct{}\n\nfunc (v *ValueMultilineState) Type() TokenType {\n\treturn Value\n}\n\nfunc (v *ValueMultilineState) Next(ru rune, f *Filter) error {\n\n\tif f.format {\n\n\t\tif ru == '`' {\n\t\t\tf.pushOut(ru)\n\t\t\tf.popState()\n\t\t\treturn nil\n\t\t}\n\n\t\tif ru == '\\\\' {\n\t\t\treturn fmt.Errorf(\"character \\\\ found in multiline string\")\n\n\t\t}\n\n\t\tf.pushOut(ru)\n\t\treturn nil\n\t}\n\n\tif ru == '`' {\n\t\tf.pushOut('\"')\n\t\tf.popState()\n\t\treturn nil\n\t}\n\n\tif ru == '\\\\' {\n\t\treturn fmt.Errorf(\"character \\\\ found in multiline string\")\n\t}\n\n\tif rep, ok := needsReplacement(ru); ok {\n\t\tf.pushOut('\\\\')\n\t\tf.pushOut(rep)\n\t\treturn nil\n\t}\n\n\tif unicode.IsSpace(ru) {\n\t\tf.pushOut(' ')\n\t\treturn nil\n\t}\n\n\tf.pushOut(ru)\n\treturn nil\n}\n\ntype ObjInternalState = int\n\nconst (\n\tObjIntNextAfterComma ObjInternalState = iota\n\tObjIntNext\n\tObjInternalKey\n\tObjInternalDelimiter\n\tObjInternalValue\n)\n\ntype ObjectState struct {\n\tinternalState ObjInternalState\n\tlineBreaks int\n\tfromComment bool\n}\n\nfunc (o *ObjectState) Type() TokenType {\n\treturn Object\n}\n\nfunc (o *ObjectState) pop(f *Filter) error {\n\n\tif f.format {\n\t\tf.pushOutMult(o.lineBreaks, 2, '\\n')\n\t\tif o.lineBreaks > 0 {\n\t\t\tf.pushSpaces(f.indent() - 1)\n\t\t}\n\t\to.lineBreaks = 0\n\t}\n\tf.pushOut('}')\n\tf.popState()\n\treturn nil\n}\n\nfunc (o *ObjectState) Next(ru rune, f *Filter) error {\n\n\tif ru == '\\n' {\n\t\to.lineBreaks++\n\t\treturn nil\n\t}\n\n\tif unicode.IsSpace(ru) {\n\t\treturn nil\n\t}\n\n\t// check if comments need to be dispatched\n\tdispatch, err := dispatchComment(f, func() error {\n\n\t\tif f.format {\n\t\t\to.fromComment = true\n\t\t\tf.pushOutMult(o.lineBreaks, 2, '\\n')\n\t\t\tif o.lineBreaks > 0 {\n\t\t\t\tf.lastOut = utf8.RuneError\n\t\t\t}\n\t\t\to.lineBreaks = 0\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dispatch {\n\t\treturn ErrDontAdvance\n\t}\n\n\tswitch o.internalState {\n\tcase ObjIntNext:\n\n\t\tif ru == '}' {\n\t\t\treturn o.pop(f)\n\t\t}\n\n\t\tif !f.format {\n\t\t\tf.pushOut(',')\n\t\t}\n\t\to.internalState = ObjIntNextAfterComma\n\t\treturn ErrDontAdvance\n\n\tcase ObjIntNextAfterComma:\n\n\t\tif ru == '}' {\n\t\t\treturn o.pop(f)\n\t\t}\n\n\t\tif f.format {\n\t\t\tf.pushOutMult(o.lineBreaks, 2, '\\n')\n\n\t\t\tif o.lineBreaks > 0 || o.fromComment {\n\t\t\t\tf.pushSpaces(f.indent())\n\t\t\t\to.fromComment = false\n\t\t\t}\n\t\t\to.lineBreaks = 0\n\t\t}\n\n\t\to.internalState = ObjInternalKey\n\t\tif ru == '\"' {\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&KeyState{})\n\t\t\treturn nil\n\t\t}\n\n\t\tf.pushState(&KeyNoQuoteState{})\n\t\treturn ErrDontAdvance\n\n\tcase ObjInternalKey:\n\n\t\tif ru == ':' {\n\t\t\tf.pushOut(ru)\n\t\t\tif f.format {\n\t\t\t\tf.pushOut(' ')\n\t\t\t}\n\t\t\to.internalState = ObjInternalDelimiter\n\t\t\treturn nil\n\t\t}\n\n\t\treturn Errorf(\"error parsing object rune: %v\", f.ring.Position(), string(ru))\n\n\tcase ObjInternalDelimiter:\n\n\t\to.internalState = ObjInternalValue\n\t\tswitch ru {\n\t\tcase '[':\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ArrayState{})\n\t\t\treturn nil\n\n\t\tcase '{':\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ObjectState{})\n\t\t\treturn nil\n\n\t\tcase '\"':\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ValueState{})\n\t\t\treturn nil\n\n\t\tcase '`':\n\t\t\tif f.format {\n\t\t\t\tf.pushOut(ru)\n\t\t\t} else {\n\t\t\t\tf.pushOut('\"')\n\t\t\t}\n\t\t\tf.pushState(&ValueMultilineState{})\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tf.pushState(&ValueNoQuoteState{})\n\t\t\treturn ErrDontAdvance\n\t\t}\n\n\tcase ObjInternalValue:\n\n\t\tif ru == '}' {\n\t\t\treturn o.pop(f)\n\t\t}\n\n\t\tif ru == ',' {\n\n\t\t\tif f.format {\n\t\t\t\tf.pushOut(',')\n\t\t\t}\n\t\t\to.internalState = ObjIntNext\n\t\t\treturn nil\n\t\t}\n\n\t\tif f.format {\n\t\t\tif o.lineBreaks == 0 && !o.fromComment {\n\t\t\t\tf.pushOut(' ')\n\t\t\t}\n\t\t\to.internalState = ObjIntNextAfterComma\n\t\t} else {\n\t\t\to.internalState = ObjIntNext\n\t\t}\n\t\treturn ErrDontAdvance\n\tdefault:\n\t\treturn Errorf(\"invalid internal object state: %v\", f.ring.Position(), string(ru))\n\t}\n}\n\ntype ArrayInternalState = int\n\nconst (\n\tArrayIntStart ObjInternalState = iota\n\tArrayIntValue\n\tArrayIntAfterValue\n)\n\ntype ArrayState struct {\n\tinit bool\n\tinternalState ArrayInternalState\n\tlineBreaks int\n\tspaceOrControls int\n\tfromComment bool\n}\n\nfunc (ArrayState) Type() TokenType {\n\treturn Array\n}\n\nfunc (a *ArrayState) Next(ru rune, f *Filter) error {\n\n\tif ru == '\\n' {\n\t\ta.lineBreaks++\n\t}\n\n\tif unicode.IsSpace(ru) {\n\t\ta.spaceOrControls++\n\t\treturn nil\n\t}\n\n\t// check if comments need to be dispatched\n\tdispatch, err := dispatchComment(f, func() error {\n\n\t\tif f.format {\n\t\t\tf.pushOutMult(a.lineBreaks, 2, '\\n')\n\t\t\tif a.lineBreaks > 0 {\n\t\t\t\tf.lastOut = utf8.RuneError\n\t\t\t}\n\t\t\ta.fromComment = true\n\t\t\ta.lineBreaks = 0\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dispatch {\n\t\treturn ErrDontAdvance\n\t}\n\n\tswitch a.internalState {\n\tcase ArrayIntAfterValue:\n\n\t\tspaceOrControls := a.spaceOrControls\n\t\ta.spaceOrControls = 0\n\n\t\tswitch ru {\n\t\tcase ']':\n\t\t\ta.internalState = ArrayIntValue\n\t\t\treturn ErrDontAdvance\n\t\tcase ',':\n\t\t\ta.internalState = ArrayIntValue\n\t\t\tif f.format {\n\t\t\t\tf.pushOut(',')\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif spaceOrControls > 0 {\n\t\t\tif f.format && (a.lineBreaks == 0 && !a.fromComment) {\n\t\t\t\tf.pushOut(' ')\n\t\t\t}\n\t\t\ta.internalState = ArrayIntValue\n\t\t\treturn ErrDontAdvance\n\t\t}\n\n\t\treturn Errorf(\"invalid character after value\", f.ring.Position())\n\n\tcase ArrayIntStart, ArrayIntValue:\n\n\t\tif ru == ']' {\n\t\t\tif f.format {\n\t\t\t\tf.pushOutMult(a.lineBreaks, 2, '\\n')\n\t\t\t\tif a.lineBreaks > 0 || a.fromComment {\n\t\t\t\t\ta.fromComment = false\n\t\t\t\t\tf.pushSpaces(f.indent() - 1)\n\t\t\t\t}\n\t\t\t\ta.lineBreaks = 0\n\t\t\t}\n\t\t\tf.popState()\n\t\t\tf.pushOut(ru)\n\t\t\treturn nil\n\t\t}\n\n\t\tif a.internalState != ArrayIntStart && !f.format {\n\t\t\tf.pushOut(',')\n\t\t}\n\n\t\tif f.format {\n\t\t\tf.pushOutMult(a.lineBreaks, 2, '\\n')\n\t\t\tif a.lineBreaks > 0 || a.fromComment {\n\t\t\t\ta.fromComment = false\n\t\t\t\tf.pushSpaces(f.indent())\n\t\t\t}\n\t\t\ta.lineBreaks = 0\n\t\t}\n\n\t\ta.internalState = ArrayIntAfterValue\n\t\tswitch ru {\n\t\tcase '[':\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ArrayState{})\n\t\t\treturn nil\n\n\t\tcase '{':\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ObjectState{})\n\t\t\treturn nil\n\n\t\tcase '\"':\n\t\t\tf.pushOut(ru)\n\t\t\tf.pushState(&ValueState{})\n\t\t\treturn nil\n\n\t\tcase '`':\n\t\t\tif f.format {\n\t\t\t\tf.pushOut(ru)\n\t\t\t} else {\n\t\t\t\tf.pushOut('\"')\n\t\t\t}\n\t\t\tf.pushState(&ValueMultilineState{})\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tf.pushState(&ValueNoQuoteState{})\n\t\t\treturn ErrDontAdvance\n\t\t}\n\tdefault:\n\t\treturn Errorf(\"invalid internal array state: %v\", f.ring.Position(), string(ru))\n\t}\n}\n\nfunc dispatchComment(f *Filter, postHook func() error) (shouldDispatch bool, err error) {\n\n\tru := f.ring.Peek()\n\n\tif ru == '/' {\n\t\terr = f.ring.Advance()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tru = f.ring.Peek()\n\t\tif ru == '/' {\n\n\t\t\tif postHook != nil {\n\t\t\t\terr = postHook()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tshouldDispatch = true\n\t\t\terr = f.ring.Advance()\n\t\t\tif f.format {\n\t\t\t\tf.pushSpace()\n\t\t\t\tf.pushRunes([]rune(\"//\"))\n\t\t\t}\n\t\t\tf.pushState(&CommentState{})\n\t\t\treturn\n\t\t}\n\n\t\tif ru == '*' {\n\t\t\tif postHook != nil {\n\t\t\t\tpostHook()\n\t\t\t}\n\n\t\t\tshouldDispatch = true\n\t\t\tif f.format {\n\t\t\t\tf.pushSpace()\n\t\t\t\tf.pushRunes([]rune(\"/*\"))\n\t\t\t}\n\t\t\terr = f.ring.Advance()\n\t\t\tf.pushState(&CommentMultiLineState{})\n\t\t\treturn\n\t\t}\n\t\terr = f.ring.Pop()\n\n\t\treturn\n\t}\n\n\treturn\n}\n\ntype CommentState struct{}\n\nfunc (c *CommentState) Type() TokenType {\n\treturn Comment\n}\n\nfunc (*CommentState) Next(ru rune, f *Filter) error {\n\n\tif ru == '\\n' {\n\t\tf.popState()\n\t\tif f.format {\n\t\t\tf.pushOut('\\n')\n\t\t}\n\t\treturn nil\n\t}\n\n\tif f.format {\n\t\tf.pushOut(ru)\n\t}\n\n\terr := f.ring.Advance()\n\tif err != nil {\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tf.popState()\n\t\t}\n\t\treturn err\n\t}\n\treturn ErrDontAdvance\n}\n\ntype CommentMultiLineState struct {\n\tescaped bool\n}\n\nfunc (c *CommentMultiLineState) Type() TokenType {\n\treturn CommentMultiLine\n}\n\nfunc (c *CommentMultiLineState) Next(ru rune, f *Filter) error {\n\n\tif !c.escaped && ru == '*' {\n\n\t\terr := f.ring.Advance()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tru = f.ring.Peek()\n\t\tif ru == '/' {\n\n\t\t\tif f.format {\n\t\t\t\tf.pushOut('*')\n\t\t\t\tf.pushOut('/')\n\t\t\t}\n\n\t\t\tf.popState()\n\t\t\treturn nil\n\t\t}\n\n\t\tf.ring.Pop()\n\t}\n\n\tc.escaped = false\n\tif ru == '\\\\' {\n\t\tc.escaped = true\n\t}\n\n\tif f.format {\n\t\tf.pushOut(ru)\n\t}\n\n\treturn nil\n}\n\nfunc (f *Filter) Read(p []byte) (n int, err error) {\n\n\tif f.err != nil {\n\t\treturn 0, f.err\n\t}\n\n\tn = f.outMinSize\n\tif n > len(p) {\n\t\tn = len(p)\n\t}\n\n\tfor n > len(f.outbuf) {\n\n\t\terr = f.fill()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tf.err = err\n\n\tif len(f.outbuf) < n {\n\t\tn = len(f.outbuf)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = f.outbuf[i]\n\t}\n\n\tf.outbuf = f.outbuf[n:]\n\n\tif errors.Is(err, io.EOF) && f.peekState().Type() == Root {\n\t\tf.done = true\n\t}\n\n\treturn n, err\n}\n\nfunc (f *Filter) fill() error {\n\n\tstate := f.peekState()\n\tfor f.outMinSize > len(f.outbuf) {\n\n\t\tru := f.ring.Peek()\n\n\t\tif ru != '\\n' {\n\t\t\t// let only '\\n' new line pass from the set of control characters\n\t\t\tif unicode.IsControl(ru) {\n\t\t\t\terr := f.ring.Advance()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// transform all spaces to single spaces\n\t\t\tif unicode.IsSpace(ru) {\n\t\t\t\tru = ' '\n\t\t\t}\n\t\t}\n\n\t\terr := state.Next(ru, f)\n\t\tif err != nil && !errors.Is(err, ErrDontAdvance) {\n\t\t\treturn err\n\t\t}\n\n\t\tif !errors.Is(err, ErrDontAdvance) {\n\t\t\terr = f.ring.Advance()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tstate = f.peekState()\n\t}\n\n\treturn nil\n}\n\nfunc (f *Filter) peekState() State {\n\tif len(f.stack) > 0 {\n\t\treturn f.stack[len(f.stack)-1]\n\t}\n\treturn f.rootState\n}\n\nfunc (f *Filter) pushState(s State) {\n\tf.stack = append(f.stack, s)\n}\n\nfunc (f *Filter) popState() {\n\tif len(f.stack) == 0 {\n\t\treturn\n\t}\n\tf.stack = f.stack[:len(f.stack)-1]\n}\n\nfunc (f *Filter) indent() int {\n\n\tvar indent int\n\tfor _, s := range f.stack {\n\t\tif s.Type() == Object || s.Type() == Array {\n\t\t\tindent++\n\t\t}\n\t}\n\treturn indent\n}\n\nfunc (f *Filter) pushSpace() {\n\tif f.lastOut != ' ' && f.lastOut != utf8.RuneError {\n\t\tf.pushOut(' ')\n\t}\n}\n\nfunc (f *Filter) pushSpaces(c int) {\n\tfor i := 0; i < c; i++ {\n\t\tf.pushOut(' ')\n\t}\n}\n\nfunc (f *Filter) pushOut(r rune) {\n\tf.lastOut = r\n\tf.outbuf = append(f.outbuf, byte(r))\n}\n\nfunc (f *Filter) pushRunes(runes []rune) {\n\tif len(runes) > 0 {\n\t\tf.lastOut = runes[len(runes)-1]\n\t}\n\tf.outbuf = append(f.outbuf, []byte(string(runes))...)\n}\n\nfunc (f *Filter) pushOutMult(t int, max int, r rune) {\n\n\tif t > max {\n\t\tt = max\n\t}\n\n\tfor i := 0; i < t; i++ {\n\t\tf.lastOut = r\n\t\tf.pushOut(r)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":948,"cells":{"blob_id":{"kind":"string","value":"d2771d9cadd85362c0f419f7abeaa9fa51e8d477"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"kapustkin/envdir"},"path":{"kind":"string","value":"/internal/commands_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1174,"string":"1,174"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetEnviroment1(t *testing.T) {\n\tres, err := getEnviroment(\"../test/1\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, res, []string{\"A_ENV=123\", \"B_VAR=another_val\"})\n}\n\nfunc TestGetEnviroment2(t *testing.T) {\n\tres, err := getEnviroment(\"../test/2\")\n\tassert.NotNil(t, err)\n\tassert.Equal(t, res, []string{})\n}\n\nfunc TestGetEnvParametr1(t *testing.T) {\n\tres, err := getEnvParametr(\"../test/1/A_ENV.txt\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, res, \"A_ENV=123\")\n}\n\nfunc TestGetEnvParametr2(t *testing.T) {\n\tres, err := getEnvParametr(\"../test/1/NO_EXIST.txt\")\n\tassert.NotNil(t, err)\n\tassert.Equal(t, res, \"\")\n}\n\nfunc TestFileNameWithoutExtension(t *testing.T) {\n\tres := fileNameWithoutExtension(\"../test/1/A_ENV.txt\")\n\tassert.Equal(t, res, \"A_ENV\")\n}\n\nfunc TestGetInputValues1(t *testing.T) {\n\tenv, path, err := getInputValues([]string{\"1233\", \"321\"})\n\tassert.Equal(t, env, \"1233\")\n\tassert.Equal(t, path, \"321\")\n\tassert.Nil(t, err)\n}\n\nfunc TestGetInputValues2(t *testing.T) {\n\tenv, path, err := getInputValues([]string{})\n\tassert.Equal(t, env, \"\")\n\tassert.Equal(t, path, \"\")\n\tassert.NotNil(t, err)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":949,"cells":{"blob_id":{"kind":"string","value":"60ecc914bdcbd94584f7f95d1eda95c1b8515d33"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"icemanblues/advent-of-code"},"path":{"kind":"string","value":"/2018/day08/day08.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1705,"string":"1,705"},"score":{"kind":"number","value":3.546875,"string":"3.546875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc readInput(filename string) []string {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Printf(\"something bad with file: %v\\n\", err)\n\t\treturn nil\n\t}\n\tdefer file.Close()\n\n\tvar lines []string\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\treturn lines\n}\n\nfunc main() {\n\tfmt.Println(\"Day 08: Memory Maneuver\")\n\n\t// part1()\n\tpart2()\n}\n\ntype Node struct {\n\tnumChild int\n\tnumMetaData int\n\tmetadata []int\n\tchildren []*Node\n}\n\nfunc part1() {\n\tfmt.Println(\"Part 1\")\n\n\tline := readInput(\"input08.txt\")[0]\n\ttokens := strings.Split(line, \" \")\n\t_, _, sum := buildNode(tokens, 0)\n\tfmt.Println(sum)\n\n}\n\nfunc buildNode(l []string, i int) (*Node, int, int) {\n\tsum := 0\n\n\tnumChild, _ := strconv.Atoi(l[i])\n\tnumMetaData, _ := strconv.Atoi(l[i+1])\n\tn := &Node{numChild, numMetaData, nil, nil}\n\n\tk := i + 2\n\tfor kid := 0; kid < numChild; kid++ {\n\t\tchild, j, jmd := buildNode(l, k)\n\t\tn.children = append(n.children, child)\n\t\tk = j\n\t\tsum += jmd\n\t}\n\n\tfor m := 0; m < numMetaData; m++ {\n\t\tmd, _ := strconv.Atoi(l[k])\n\t\tsum += md\n\t\tn.metadata = append(n.metadata, md)\n\t\tk++\n\t}\n\n\t// fmt.Println(n)\n\treturn n, k, sum\n}\n\nfunc part2() {\n\tfmt.Println(\"Part 2\")\n\n\tline := readInput(\"input08.txt\")[0]\n\ttokens := strings.Split(line, \" \")\n\troot, _, _ := buildNode(tokens, 0)\n\tfmt.Println(value(*root))\n}\n\nfunc value(n Node) int {\n\tif n.numChild == 0 {\n\t\tsum := 0\n\t\tfor _, md := range n.metadata {\n\t\t\tsum += md\n\t\t}\n\t\treturn sum\n\t}\n\n\tv := 0\n\tfor _, md := range n.metadata {\n\t\tif md == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif md >= len(n.children)+1 {\n\t\t\tcontinue\n\t\t}\n\t\tv += value(*n.children[md-1])\n\t}\n\treturn v\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":950,"cells":{"blob_id":{"kind":"string","value":"8ca67c54a13c1bd99d914ee9de02a2b9c090f794"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"john6938/tenseIdentifierGo"},"path":{"kind":"string","value":"/learningData.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":18303,"string":"18,303"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\n// Learning data\n// TODO: Implement loading from csv files\nvar (\n\tEXAMPLES_ARRAY = map[string]int{\n\t\t\"He goes to school every morning.\": TENSE_PRESENT_SIMPLE,\n\t\t\"She understands English.\": TENSE_PRESENT_SIMPLE,\n\t\t\"It mixes the sand and the water.\": TENSE_PRESENT_SIMPLE,\n\t\t\"He tries very hard.\": TENSE_PRESENT_SIMPLE,\n\t\t\"She enjoys playing the piano.\": TENSE_PRESENT_SIMPLE,\n\t\t\"I don’t live in London now.\": TENSE_PRESENT_SIMPLE,\n\t\t\"I don’t play the piano but I play the guitar.\": TENSE_PRESENT_SIMPLE,\n\t\t\"They don’t work at the weekend.\": TENSE_PRESENT_SIMPLE,\n\t\t\"John doesn’t live in Manchester.)\": TENSE_PRESENT_SIMPLE,\n\t\t\"Angela doesn’t drive to work.\": TENSE_PRESENT_SIMPLE,\n\t\t\"She goes by bus.\": TENSE_PRESENT_SIMPLE,\n\t\t\"I listen to the radio\": TENSE_PRESENT_SIMPLE,\n\t\t\"I have a radio\": TENSE_PRESENT_SIMPLE,\n\t\t\"She is crying.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"He is talking to his friend.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"The baby is sleeping in his crib.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"We are visiting the museum in the afternoon.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"He is not standing.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Anthony is sitting in the chair.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"You are not watching the movie.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Rose is reading a book.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"She is not going to the game tonight.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"He is meeting his friends after school.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Are you visiting your cousin this weekend?\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"I am not going to the meeting after work.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Is John playing football today?\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Marc is making pizza now.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"They are eating lunch right now.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Frances is talking on the phone at the moment.\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Is she laughing?\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Are they listening to the teacher?\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Is the baby drinking his bottle?\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"Are you going?\": TENSE_PRESENT_CONTINUOUS,\n\t\t\"I have been to France.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"I have been to France three times.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"I have never been to France.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"I think I have seen that movie before.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"He has never traveled by train.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Joan has studied two foreign languages.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Have you ever met him?\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"No, I have not met him.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"You have grown since the last time I saw you.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"The government has become more interested in arts education.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Japanese has become one of the most popular courses at the university since the Asian studies program was established.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"My English has really improved since I moved to Australia.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Man has walked on the Moon.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Our son has learned how to read.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Doctors have cured many deadly diseases.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Scientists have split the atom.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"James has not finished his homework yet.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"Susan hasn't mastered Japanese, but she can communicate.\": TENSE_PRESENT_PERFECT_SIMPLE,\n\t\t\"They have been talking for the last hour.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"She has been working at that company for three years.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"What have you been doing for the last 30 minutes?\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"James has been teaching at the university since June.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"We have been waiting here for over two hours!\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Why has Nancy not been taking her medicine for the last three days?\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Recently, I have been feeling really tired.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"She has been watching too much television lately.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Mary has been feeling a little depressed.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Lisa has not been practicing her English.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"You have only been waiting here for one hour.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Have you only been waiting here for one hour?\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Recently, John has been doing the work.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"Recently, the work has been being done by John.\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"What have you been doing?\": TENSE_PRESENT_PERFECT_CONTINUOUS,\n\t\t\"I didn't want to go to the dentist.\": TENSE_PAST_SIMPLE,\n\t\t\"She didn't have time.\": TENSE_PAST_SIMPLE,\n\t\t\"You didn't close the door.\": TENSE_PAST_SIMPLE,\n\t\t\"He didn't come to my party.\": TENSE_PAST_SIMPLE,\n\t\t\"They didn't study so they didn't pass the test.\": TENSE_PAST_SIMPLE,\n\t\t\"We didn't sleep well last night.\": TENSE_PAST_SIMPLE,\n\t\t\"Did she like the surprise?\": TENSE_PAST_SIMPLE,\n\t\t\"They went to the library.\": TENSE_PAST_SIMPLE,\n\t\t\"We didn't have any money.\": TENSE_PAST_SIMPLE,\n\t\t\"We didn't do our exercises this morning.\": TENSE_PAST_SIMPLE,\n\t\t\"Did you have a bicycle when you were young?\": TENSE_PAST_SIMPLE,\n\t\t\"Did you do much climbing in Switzerland?\": TENSE_PAST_SIMPLE,\n\t\t\"He didn't go to bed early last night.\": TENSE_PAST_SIMPLE,\n\t\t\"I had a radio\": TENSE_PAST_SIMPLE,\n\t\t\"I heard the radio\": TENSE_PAST_SIMPLE,\n\t\t\"I listened to the radio\": TENSE_PAST_SIMPLE,\n\t\t\"Did he come to your party last week?\": TENSE_PAST_SIMPLE,\n\t\t\"They went yesterday.\": TENSE_PAST_SIMPLE,\n\t\t\"The sun was shining every day that summer.\": TENSE_PAST_CONTINUOUS,\n\t\t\"As I spoke, the children were laughing at my cleverness.\": TENSE_PAST_CONTINUOUS,\n\t\t\"The audience was applauding until he fell off the stage.\": TENSE_PAST_CONTINUOUS,\n\t\t\"I was making dinner when she arrived.\": TENSE_PAST_CONTINUOUS,\n\t\t\"At 6 o’clock, I was eating dinner.\": TENSE_PAST_CONTINUOUS,\n\t\t\"She was talking constantly in class in those days.\": TENSE_PAST_CONTINUOUS,\n\t\t\"I was watching TV when she called.\": TENSE_PAST_CONTINUOUS,\n\t\t\"When the phone rang, she was writing a letter.\": TENSE_PAST_CONTINUOUS,\n\t\t\"While we were having the picnic, it started to rain.\": TENSE_PAST_CONTINUOUS,\n\t\t\"What were you doing when the earthquake started?\": TENSE_PAST_CONTINUOUS,\n\t\t\"I was listening to my iPod, so I didn't hear the fire alarm.\": TENSE_PAST_CONTINUOUS,\n\t\t\"You were not listening to me when I told you to turn the oven off.\": TENSE_PAST_CONTINUOUS,\n\t\t\"While John was sleeping last night, someone stole his car.\": TENSE_PAST_CONTINUOUS,\n\t\t\"The teacher asked if we had studied for the exam.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"The usher asked if we had purchased our tickets.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"My neighbor asked if we had seen her dog.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"The boss had said it would be a long meeting.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"We wished we had purchased the winning ticket\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"I wished I had told the truth.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"She wished she had seen her friend.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"The boy wished he had asked another question.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"She had just left the scene when the ambulance arrived.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"The bus had just left when we got to the stop.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"I had never seen such a beautiful sunset before I went to the island.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"Before he did his homework, he had stayed after school for help.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"She had lived in California before moving to Texas.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"We had just called home when my mom texted us about returning the car.\": TENSE_PAST_PERFECT_SIMPLE,\n\t\t\"He had been drinking milk out the carton when Mom walked into the kitchen.\": TENSE_PAST_PERFECT_CONTINUOUS,\n\t\t\"I had been working at the company for five years when I got the promotion.\": TENSE_PAST_PERFECT_CONTINUOUS,\n\t\t\"Martha had been walking three miles a day before she broke her leg.\": TENSE_PAST_PERFECT_CONTINUOUS,\n\t\t\"The program that was terminated had been working well since 1945.\": TENSE_PAST_PERFECT_CONTINUOUS,\n\t\t\"Cathy had been playing the piano for 35 years when she was finally asked to do a solo with the local orchestra.\": TENSE_PAST_PERFECT_CONTINUOUS,\n\t\t\"He had been throwing rocks at her window for five minutes before she finally came out on the balcony and said, “Hey, Romeo.”\": TENSE_PAST_PERFECT_CONTINUOUS,\n\t\t\"It will rain tomorrow.\": TENSE_FUTURE_SIMPLE,\n\t\t\"I'll pay for the tickets by credit card.\": TENSE_FUTURE_SIMPLE,\n\t\t\"I'll do the washing-up.\": TENSE_FUTURE_SIMPLE,\n\t\t\"He'll carry your bag for you.\": TENSE_FUTURE_SIMPLE,\n\t\t\"The baby won't eat his soup.\": TENSE_FUTURE_SIMPLE,\n\t\t\"I won't leave until I've seen the manager!\": TENSE_FUTURE_SIMPLE,\n\t\t\"Shall I open the window?\": TENSE_FUTURE_SIMPLE,\n\t\t\"Shall we go to the cinema tonight?\": TENSE_FUTURE_SIMPLE,\n\t\t\"What shall I tell the boss about this money?\": TENSE_FUTURE_SIMPLE,\n\t\t\"You will do exactly as I say.\": TENSE_FUTURE_SIMPLE,\n\t\t\"Will you come to the dance with me?\": TENSE_FUTURE_SIMPLE,\n\t\t\"Will you marry me?\": TENSE_FUTURE_SIMPLE,\n\t\t\" I will finish my report later today.\": TENSE_FUTURE_SIMPLE,\n\t\t\"The sun will rise at 6:03 am.\": TENSE_FUTURE_SIMPLE,\n\t\t\"I'll go to the market tomorrow.\": TENSE_FUTURE_SIMPLE,\n\t\t\"There will be another conference next month.\": TENSE_FUTURE_SIMPLE,\n\t\t\"I'll come to see you on Sunday.\": TENSE_FUTURE_SIMPLE,\n\t\t\"We'll be back on Friday afternoon.\": TENSE_FUTURE_SIMPLE,\n\t\t\"Tom will visit his parents next week.\": TENSE_FUTURE_SIMPLE,\n\t\t\"They will paint the fence blue.\": TENSE_FUTURE_SIMPLE,\n\t\t\"I will return in two hours.\": TENSE_FUTURE_SIMPLE,\n\t\t\"He will finish his homework in twenty minutes.\": TENSE_FUTURE_SIMPLE,\n\t\t\"Jane will turn 18 this year.\": TENSE_FUTURE_SIMPLE,\n\t\t\"Michael will be running a marathon this Saturday.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Eric will be competing against Michael in the race.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"I will be watching Michael and Eric race.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Robert will be reading various kinds of books.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"They will be playing football in that field.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"April will be having coffee in this coffee shop.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Bob will be going to the library.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"We will be shopping in that market this Monday.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"We will be watching a movie in this Cineplex on next Friday.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"You will be shopping at that market tomorrow.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"I will be singing different kinds of songs, especially modern.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"I will be attending a program of my varsity on Friday.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Jeff will be traveling around the world in March.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"They will be playing hockey in that field on Thursday.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"The poet will be writing a romantic poem for the program.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"The lyricist will be writing a realistic song for the film.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Will you be going to the concert of realistic songs?\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"I will not be attending the program because of my busy schedule.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Robin will be joining us at the meeting.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"I will be helping him to do the task\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"We will be going to enjoy the musical drama.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"I will be arranging all the necessary materials for the program.\": TENSE_FUTURE_CONTINUOUS,\n\t\t\"Jack will have finished his homework by the time his mother gets home.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"She will have gotten ready by the time they leave the house.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"Laura will have cleaned out the apartment before she gives back the key.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"By the time I get home, Zoe will have cooked dinner for both of us.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"The robbers will have taken all the money by the time anyone arrives.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"By the time he graduates, he will have completed five years of study.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"The snow will have stopped by April.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"We will have returned home by five o'clock.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"By tomorrow, their life will have changed completely.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"Her heel will have fully healed by the summer.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"By next month, you will have received your promotion.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"By the time he wakes up, we will have prepared lunch for everyone.\": TENSE_FUTURE_PERFECT_SIMPLE,\n\t\t\"In November, I will have been working at my company for three years.\": TENSE_FUTURE_PERFECT_CONTINUOUS,\n\t\t\"At five o’clock, I will have been waiting for thirty minutes.\": TENSE_FUTURE_PERFECT_CONTINUOUS,\n\t\t\"When I turn thirty, I will have been playing piano for twenty-one years.\": TENSE_FUTURE_PERFECT_CONTINUOUS,\n\t}\n)\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":951,"cells":{"blob_id":{"kind":"string","value":"864c573bafead004dc9c13e82f925f1d62fa3236"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"yskang/AlgorithmWithGo"},"path":{"kind":"string","value":"/baekjoon/numberTriangleDynamicProgramming.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1025,"string":"1,025"},"score":{"kind":"number","value":3.25,"string":"3.25"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// https://www.acmicpc.net/problem/1932\n\npackage baekjoon\n\nimport (\n\t\"fmt\"\n\t\"bufio\"\n\t\"os\"\n\t\"strings\"\n\t\"strconv\"\n)\n\nfunc NumberTriangleDynamicPrograming() {\n\ttriangle := make([][]int, 0)\n\tvar n int\n\tfmt.Scanf(\"%d\\n\", &n)\n\n\t//for i := 0 ; i < n ; i++ {\n\t//\ttriangle = append(triangle, []int{})\n\t//\tfor j := 0 ; j <= i ; j++ {\n\t//\t\tfmt.Scanf(\"%d\", &m)\n\t//\t\ttriangle[i] = append(triangle[i], m)\n\t//\t}\n\t//}\n\n\tinNums := make([]int, 0)\n\tscanner := bufio.NewScanner(os.Stdin)\n\ti := 0\n\n\tfor scanner.Scan() {\n\t\tinline := scanner.Text()\n\t\tinStrs := strings.Split(inline, \" \")\n\n\t\ttriangle = append(triangle, []int{})\n\t\tfor _, str := range inStrs {\n\t\t\tnum, _ := strconv.Atoi(str)\n\t\t\ttriangle[i] = append(triangle[i], num)\n\t\t}\n\n\t\tinNums = inNums[:0]\n\t\ti += 1\n\n\t\tif i == n {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i = n-2 ; i >= 0 ; i-- {\n\t\tfor j := 0 ; j < i+1 ; j++ {\n\t\t\ttriangle[i][j] = triangle[i][j] + max(triangle[i+1][j], triangle[i+1][j+1])\n\t\t}\n\t}\n\n\tfmt.Println(triangle[0][0])\n}\n\nfunc max(a int, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":952,"cells":{"blob_id":{"kind":"string","value":"5136314c730c6cdb907d813c531d58a4d932fd38"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"HDUerZhuBin/golang"},"path":{"kind":"string","value":"/temp_repo/for2.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":142,"string":"142"},"score":{"kind":"number","value":3.125,"string":"3.125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main(){\n\tvar i int = 5\n\n\tfor count:=i;count>0;count--{\n\t\tfmt.Println(\"the current count is:\",count)\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":953,"cells":{"blob_id":{"kind":"string","value":"bcb53096987025c76939cc6302fbdf7df1e88d29"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"HarryAlvarado28/mini-servers-hackrry"},"path":{"kind":"string","value":"/server-go.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":345,"string":"345"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"net/http\"\n\t\"github.com/labstack/echo\"\n)\n\nfunc main() {\n\tconst VAR_PORT = \":4321\" // Cont. indicador del puerto\n\te := echo.New()\n\te.GET(\"/\", func(c echo.Context) error {\n\t\treturn c.String(http.StatusOK, \"Hola, Mundo!\")\n\t})\n\te.Logger.Fatal(e.Start(VAR_PORT))\n}\n// Ver más del framework Echo en https://echo.labstack.com.\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":954,"cells":{"blob_id":{"kind":"string","value":"fc987bb5885343f81a672c639ab9818e44019bdd"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"openshift/cluster-kube-storage-version-migrator-operator"},"path":{"kind":"string","value":"/pkg/operator/deploymentcontroller/deployment_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1771,"string":"1,771"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package deploymentcontroller\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\toperatorv1 \"github.com/openshift/api/operator/v1\"\n\tappsv1 \"k8s.io/api/apps/v1\"\n\tcorev1 \"k8s.io/api/core/v1\"\n)\n\nfunc Test_setOperandLogLevel(t *testing.T) {\n\n\ttestCases := []struct {\n\t\tlogLevel operatorv1.LogLevel\n\t\tcommand []string\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\tlogLevel: operatorv1.Debug,\n\t\t\tcommand: []string{\"arg0\", \"arg1\", \"arg2\"},\n\t\t\texpected: []string{\"arg0\", \"arg1\", \"arg2\", \"--v=4\"},\n\t\t},\n\t\t{\n\t\t\tlogLevel: operatorv1.Trace,\n\t\t\tcommand: []string{\"arg0\", \"--v=2\", \"arg2\"},\n\t\t\texpected: []string{\"arg0\", \"--v=6\", \"arg2\"},\n\t\t},\n\t\t{\n\t\t\tlogLevel: operatorv1.TraceAll,\n\t\t\tcommand: []string{\"arg0\", \"arg1\", \"--v=2\"},\n\t\t\texpected: []string{\"arg0\", \"arg1\", \"--v=8\"},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tspec := &operatorv1.OperatorSpec{\n\t\t\t\tLogLevel: tc.logLevel,\n\t\t\t}\n\t\t\tdeployment := &appsv1.Deployment{\n\t\t\t\tSpec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tName: \"migrator\",\n\t\t\t\t\t\tCommand: tc.command,\n\t\t\t\t\t}},\n\t\t\t\t}}},\n\t\t\t}\n\t\t\t_ = setOperandLogLevel(spec, deployment)\n\t\t\tif !cmp.Equal(deployment.Spec.Template.Spec.Containers[0].Command, tc.expected) {\n\t\t\t\tt.Fatal(cmp.Diff(deployment.Spec.Template.Spec.Containers[0].Command, tc.expected))\n\t\t\t}\n\t\t})\n\t}\n\n\tt.Run(\"\", func(t *testing.T) {\n\t\tspec := &operatorv1.OperatorSpec{LogLevel: operatorv1.Debug}\n\t\tdeployment := &appsv1.Deployment{\n\t\t\tSpec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{\n\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\tName: \"not_migrator\",\n\t\t\t\t}},\n\t\t\t}}},\n\t\t}\n\t\tif err := setOperandLogLevel(spec, deployment); err == nil {\n\t\t\tt.Fatal(\"expected error\")\n\t\t}\n\t})\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":955,"cells":{"blob_id":{"kind":"string","value":"81074fa1f6c578848baf94f578766dba74eb2703"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"CrowdPower/fund"},"path":{"kind":"string","value":"/controllers/payment.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3818,"string":"3,818"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package controllers\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/satori/go.uuid\"\n\n\t\"github.com/crowdpower/fund/models\"\n\t\"github.com/crowdpower/fund/storage\"\n\t\"github.com/crowdpower/fund/utils\"\n)\n\nconst (\n\tpaymentPageSize = 20\n)\n\ntype PaymentController interface {\n\tPostPayment(w http.ResponseWriter, r *http.Request)\n\tGetPayment(w http.ResponseWriter, r *http.Request)\n\tGetPayments(w http.ResponseWriter, r *http.Request)\n\tGetPaymentsSum(w http.ResponseWriter, r *http.Request)\n}\n\ntype paymentController struct {\n\tdb storage.DB\n}\n\nfunc NewPaymentController(db storage.DB) PaymentController {\n\treturn &paymentController{db}\n}\n\nfunc (d *paymentController) PostPayment(w http.ResponseWriter, r *http.Request) {\n\tvar payment models.Payment\n\terr := json.NewDecoder(r.Body).Decode(&payment)\n\tif err != nil {\n\t\tlog.Printf(\"could not unmarshal PostPayment request body\\n%v\", err)\n\t\tutils.SendError(w, \"Could not parse body as JSON\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif payment.Amount <= 0 {\n\t\tutils.SendError(w, \"Payment amount must be greater than 0\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif payment.Url == \"\" {\n\t\tutils.SendError(w, \"Payment url cannot be empty\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpayment.Username = mux.Vars(r)[\"username\"]\n\tpayment.Id = uuid.NewV4().String()\n\tpayment.Time = time.Now().Format(storage.TimeFormat)\n\n\terr = d.db.CreatePayment(&payment)\n\tif err != nil {\n\t\tif storage.IsInsufficientFunds(err) {\n\t\t\tutils.SendError(w, \"Insufficient funds\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"could not insert payment %v into database\\n%v\", payment, err)\n\t\tutils.SendError(w, \"Error inserting payment into database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tutils.SendSuccess(w, nil, http.StatusNoContent)\n}\n\nfunc (d *paymentController) GetPayment(w http.ResponseWriter, r *http.Request) {\n\tusername := mux.Vars(r)[\"username\"]\n\n\tid := r.URL.Query().Get(\"id\")\n\tif id == \"\" {\n\t\tutils.SendError(w, \"Parameter 'id' required\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpayment, err := d.db.GetPayment(username, id)\n\tif storage.IsNotFound(err) {\n\t\tutils.SendError(w, fmt.Sprintf(\"Payment %v not found for user %v\", id, username), http.StatusNotFound)\n\t\treturn\n\t} else if err != nil {\n\t\tlog.Printf(\"could not get payment %v for user %v from the database\\n%v\", id, username, err)\n\t\tutils.SendError(w, \"Error getting payment from database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tutils.SendSuccess(w, payment, http.StatusOK)\n}\n\nfunc (d *paymentController) GetPayments(w http.ResponseWriter, r *http.Request) {\n\tusername := mux.Vars(r)[\"username\"]\n\n\targs := &models.PaymentArgs{}\n\terr := utils.ParseArgs(r, args)\n\tif err != nil {\n\t\tutils.SendError(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif args.Count == 0 {\n\t\targs.Count = paymentPageSize\n\t}\n\n\tpayments, err := d.db.GetPayments(username, args)\n\tif err != nil {\n\t\tlog.Printf(\"could not get payments for user %v from the database\\n%v\", username, err)\n\t\tutils.SendError(w, \"Error getting payments from database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tutils.SendPage(w, r, payments, args.Offset+paymentPageSize, paymentPageSize, len(payments) == args.Count)\n}\n\nfunc (d *paymentController) GetPaymentsSum(w http.ResponseWriter, r *http.Request) {\n\tusername := mux.Vars(r)[\"username\"]\n\n\targs := &models.PaymentArgs{}\n\terr := utils.ParseArgs(r, args)\n\tif err != nil {\n\t\tutils.SendError(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsum, err := d.db.GetPaymentsSum(username, args)\n\tif err != nil {\n\t\tlog.Printf(\"could not get payments sum for user %v from the database\\n%v\", username, err)\n\t\tutils.SendError(w, \"Error getting payments sum from database\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tutils.SendSuccess(w, map[string]int{\"sum\": sum}, http.StatusOK)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":956,"cells":{"blob_id":{"kind":"string","value":"53230bdcd4c3afb836617796602e3c15ae31fedb"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"kechako/gosw"},"path":{"kind":"string","value":"/env/option.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":601,"string":"601"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package env\n\nimport \"path/filepath\"\n\ntype Option interface {\n\tapply(env *Env)\n}\n\ntype optionFunc func(env *Env)\n\nfunc (f optionFunc) apply(env *Env) {\n\tf(env)\n}\n\nfunc WithEnvRoot(root string) Option {\n\treturn optionFunc(func(env *Env) {\n\t\tenv.envRoot = filepath.Clean(root)\n\t})\n}\n\nfunc WithVersionLinkName(name string) Option {\n\treturn optionFunc(func(env *Env) {\n\t\tenv.verLinkName = name\n\t})\n}\n\nfunc WithConfigDir(dir string) Option {\n\treturn optionFunc(func(env *Env) {\n\t\tenv.confDir = dir\n\t})\n}\n\nfunc WithCacheDir(dir string) Option {\n\treturn optionFunc(func(env *Env) {\n\t\tenv.cacheDir = dir\n\t})\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":957,"cells":{"blob_id":{"kind":"string","value":"7cbe9814d4b012edbdad097dba7ddd3a6cf25944"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"nettan20/hn"},"path":{"kind":"string","value":"/hackernews/getpage.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3151,"string":"3,151"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package hackernews\n\nimport (\n\t\"fmt\"\n\t\"html\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n)\n\n//Get a new page by passing a url\nfunc (c *Client) RetrievePage(url string) (*Page, error) {\n\t//Trim leading slash if necessary\n\tif url[0] == '/' {\n\t\turl = url[1:]\n\t}\n\n\t//All urls must start with YC root (or test)\n\turlForReq := fmt.Sprintf(\"%s/%s\", c.RootUrl, url)\n\treq, err := http.NewRequest(\"GET\", urlForReq, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating request for url %s: %v\", url, err)\n\t}\n\n\tdoc, err := c.doReq(req)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error doing request:\\n\\t %v\", err)\n\t}\n\n\t//Get all the trs with subtext for children then go back one (for the first row)\n\trows := doc.Find(\".subtext\").ParentsFilteredUntil(\"tr\", \"tbody\").Prev()\n\n\tp := NewPage(url)\n\n\t//Get the next url\n\tif nextUrl, found := doc.Find(\"td.title\").Last().Find(\"a\").Attr(\"href\"); found {\n\t\tp.NextUrl = nextUrl\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Could not retreive next hackernews page. Time to go outside?\")\n\t}\n\n\t//Make sure NextUrl doesn't start with forward slash\n\tfor len(p.NextUrl) > 0 && p.NextUrl[0] == '/' {\n\t\tp.NextUrl = p.NextUrl[1:]\n\t}\n\n\t//Parse articles\n\trows.Each(func(i int, row *goquery.Selection) {\n\t\tar := Article{\n\t\t\tRank: len(p.Articles) + i,\n\t\t}\n\n\t\ttitle := row.Find(\".title\").Eq(1)\n\t\tlink := title.Find(\"a\").First()\n\n\t\tar.Title = html.UnescapeString(link.Text())\n\n\t\tif url, exists := link.Attr(\"href\"); exists {\n\t\t\tar.Url = url\n\t\t}\n\n\t\t//Rows are used in pairs currently\n\t\trow = row.Next()\n\n\t\trow.Find(\"span\").Each(func(i int, s *goquery.Selection) {\n\t\t\tif karma, err := strconv.Atoi(strings.Split(s.Text(), \" \")[0]); err == nil {\n\t\t\t\tar.Karma = karma\n\t\t\t}\n\n\t\t\tif idSt, exists := s.Attr(\"id\"); exists {\n\t\t\t\tif id, err := strconv.Atoi(strings.Split(idSt, \"_\")[1]); err == nil {\n\t\t\t\t\tar.Id = id\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tsub := row.Find(\"td.subtext\")\n\t\tt := html.UnescapeString(sub.Text())\n\n\t\t//We can ignore the error safely here\n\t\tar.Created, _ = parseCreated(t)\n\n\t\t//Get the username\n\t\tar.User = html.UnescapeString(sub.Find(\"a\").First().Text())\n\n\t\t//Get number of comments\n\t\tcomStr := strings.Split(sub.Find(\"a\").Last().Text(), \" \")[0]\n\n\t\tif comNum, err := strconv.Atoi(comStr); err == nil {\n\t\t\tar.NumComments = comNum\n\t\t}\n\n\t\tp.Articles = append(p.Articles, &ar)\n\t})\n\n\treturn p, nil\n}\n\n//Parse out from a string the create time\nvar timeName = map[string]time.Duration{\n\t\"second\": time.Second,\n\t\"minute\": time.Minute,\n\t\"hour\": time.Hour,\n\t\"day\": 24 * time.Hour,\n}\n\nvar agoRegexp = regexp.MustCompile(`((?:\\w*\\W){2})(?:ago)`)\n\nfunc parseCreated(s string) (time.Time, error) {\n\tagoStr := agoRegexp.FindStringSubmatch(s)\n\n\tif len(agoStr) < 2 {\n\t\treturn time.Time{}, fmt.Errorf(`No \"ago\" string found in string %s`, s)\n\t}\n\n\twords := strings.Split(agoStr[1], \" \")\n\n\tif count, err := strconv.Atoi(words[0]); err == nil {\n\t\tdurText := words[1]\n\n\t\tif durText[len(durText)-1] == 's' {\n\t\t\tdurText = durText[:len(durText)-1]\n\t\t}\n\n\t\tdur := timeName[durText]\n\t\tdiff := -int64(count) * int64(dur)\n\t\treturn time.Now().Add(time.Duration(diff)).Round(dur), nil\n\t} else {\n\t\treturn time.Time{}, err\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":958,"cells":{"blob_id":{"kind":"string","value":"46a576474d73dd0642da79d493acbe26ab6f0273"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"sublimeye/100-days-of-code"},"path":{"kind":"string","value":"/thegobook/xkcd.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5063,"string":"5,063"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst FIRST = 1\nconst LAST = 1930 // 1930\nconst CONCURRENCY = 10\n\nconst CACHE_DIR = \"xkcd-cache\"\nconst CACHE_FILE = \"xkcd-index.json\"\n\ntype result struct {\n\tindex int\n\tres *Xkcd\n\terr error\n}\n\ntype Xkcd struct {\n\tSafeTitle string `json:\"safe_title\"`\n\tTitle string `json:\"title\"`\n\tTranscript string `json:\"transcript\"`\n\tAlt string `json:\"alt\"`\n\tImg string `json:\"img\"`\n\tUrl string\n}\n\n// Collection of xkcd stories\ntype Collection struct {\n\tItems []*Xkcd `json:\"items\"`\n}\n\nfunc initIndex(fetch bool) Collection {\n\tif fetch {\n\t\treturn buildIndex()\n\t}\n\n\tbIndex, err := readAndParseIndexFile()\n\tvar index Collection\n\n\tif err == nil {\n\t\tif jerr := json.Unmarshal(bIndex, &index); jerr != nil {\n\t\t\tfmt.Println(\"Unable to parse index file. Building index from scratch\")\n\t\t\treturn buildIndex()\n\t\t}\n\t\tfmt.Println(\"Using index file\")\n\t\treturn index\n\t} else {\n\t\tfmt.Println(\"Error parsing index file\", err)\n\t\treturn buildIndex()\n\t}\n}\n\nfunc buildIndex() Collection {\n\tvar urls []string\n\tvar collection Collection\n\tstart := time.Now()\n\n\tfmt.Println(\"fetching xkcd.com\")\n\tfor i := 1; i <= LAST; i++ {\n\t\turls = append(urls, \"https://xkcd.com/\"+strconv.Itoa(i)+\"/info.0.json\")\n\t}\n\n\tresults := fetchAll(urls, CONCURRENCY)\n\tfor _, result := range results {\n\t\tif result.res != nil {\n\t\t\tcollection.Items = append(collection.Items, result.res)\n\t\t}\n\t}\n\n\tsaveAsJson(collection, CACHE_DIR)\n\tfmt.Printf(\"Fetched %d items in %.2fs\\n\", len(collection.Items), time.Since(start).Seconds())\n\treturn collection\n}\n\nfunc saveAsJson(data Collection, dir string) {\n\tif _, err := os.Stat(dir); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tos.Mkdir(dir, 0755)\n\t\t} else {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\tpath := fmt.Sprint(dir, \"/\", CACHE_FILE)\n\tos.Remove(path)\n\n\t//fmt.Println(data)\n\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\t//fmt.Println(b)\n\n\tioutil.WriteFile(path, b, 0644)\n}\n\nfunc fetchAll(urls []string, concurrency int) []result {\n\t// buffered channel that will block at the concurrency limit\n\tsemaphoreChan := make(chan struct{}, concurrency)\n\n\t// unbuffered channel -> will not block and collect http request results\n\tresultsChan := make(chan *result)\n\n\tdefer func() {\n\t\tclose(semaphoreChan)\n\t\tclose(resultsChan)\n\t}()\n\n\tfor i, url := range urls {\n\n\t\t// start a go routine with the index\n\t\tgo func(i int, url string) {\n\t\t\t// this sends an empty struct into the semaphoreChan which\n\t\t\t// is basically saying add one to the limit, but when the\n\t\t\t// limit has been reached block until there is room\n\t\t\tsemaphoreChan <- struct{}{}\n\n\t\t\t// send the request and put the response in a result struct\n\t\t\t// along with the index so we can sort them later along with\n\t\t\t// any error that might have happened\n\t\t\tres, err := http.Get(url)\n\t\t\tvar item result\n\t\t\tvar myresult Xkcd\n\t\t\tif res.StatusCode != 200 {\n\t\t\t\tfmt.Println(\"Bad status code\", res.StatusCode, url)\n\t\t\t\titem = result{i, nil, err}\n\t\t\t} else if jsonErr := json.NewDecoder(res.Body).Decode(&myresult); jsonErr != nil {\n\t\t\t\t// res.Body.Close()\n\t\t\t\t// fmt.Println(jsonErr)\n\t\t\t\t// panic(\"JSON decoder unhandled error\")\n\t\t\t\titem = result{i, nil, jsonErr}\n\t\t\t} else {\n\t\t\t\tmyresult.Url = url\n\t\t\t\titem = result{i, &myresult, err}\n\t\t\t}\n\n\t\t\tres.Body.Close()\n\n\t\t\t// now we can send the result struct through the resultsChan\n\t\t\tresultsChan <- &item\n\n\t\t\t// once we're done it's we read from the semaphoreChan which\n\t\t\t// has the effect of removing one from the limit and allowing\n\t\t\t// another goroutine to start\n\t\t\t<-semaphoreChan\n\n\t\t}(i, url)\n\t}\n\n\tvar results []result\n\n\t// start listening to resultsChan, once arrived append it to the result slice\n\tfor {\n\t\tresult := <-resultsChan\n\t\tresults = append(results, *result)\n\n\t\t// stop when reached expected amount of urls\n\t\tif len(results) == len(urls) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// we can sort here\n\t// sort.Slice()\n\n\treturn results\n}\n\nfunc check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\n// Reads index from file into memory\nfunc readAndParseIndexFile() ([]byte, error) {\n\tconst indexFilePath = CACHE_DIR + \"/\" + CACHE_FILE\n\tbIndex, err := ioutil.ReadFile(indexFilePath)\n\tif err != nil {\n\t\tfmt.Println(\"Index file was not found\")\n\t\treturn nil, err\n\t}\n\n\tif bIndex != nil {\n\t\treturn bIndex, nil\n\t}\n\n\treturn nil, errors.New(\"file is empty\")\n}\n\nfunc searchIndex(text string, collection Collection) {\n\tvar foundIndexes []int\n\n\tfmt.Printf(\"Searching for %q\\n\", text)\n\tfor i, item := range collection.Items {\n\t\tif strings.Contains(item.Transcript, text) || strings.Contains(item.Title, text) {\n\t\t\tfoundIndexes = append(foundIndexes, i)\n\t\t\t// 0 url title text\n\t\t\tfmt.Printf(\"%4.4d %.20s %.20s %.20s\\n\", i, item.Url, item.Title, item.Transcript)\n\t\t}\n\t}\n\n\tif len(foundIndexes) == 0 {\n\t\tfmt.Printf(\"No items found\")\n\t}\n}\n\nfunc runXkcd() {\n\ttext := flag.String(\"text\", \"\", \"text to search in xkcd index\")\n\tfetch := flag.Bool(\"fetch\", false, \"force fetching index\")\n\tflag.Parse()\n\tindex := initIndex(*fetch)\n\tsearchIndex(*text, index)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":959,"cells":{"blob_id":{"kind":"string","value":"cb0d6fd246d2ef74488a0e54e3abc28546de3a64"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"akure/demo_exchange_api"},"path":{"kind":"string","value":"/lib/redis/redis.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3108,"string":"3,108"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package redis\n\n/*\n * Copyright © 2006-2019 Around25 SRL \n *\n * Licensed under the Around25 Exchange License Agreement (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.around25.com/licenses/EXCHANGE_LICENSE\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @author\t\tCosmin Harangus \n * @copyright 2006-2019 Around25 SRL \n * @license \tEXCHANGE_LICENSE\n */\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"time\"\n\n\tradix \"github.com/mediocregopher/radix/v3\"\n)\n\n// Config godoc\ntype Config struct {\n\tHost string\n\tUsername string\n\tPassword string\n\tPort int\n\tSSLEnabled bool `mapstructure:\"ssl_enabled\"`\n\tCACert string `mapstructure:\"cacert\"`\n\tPoolSize int\n}\n\n// Client connection to redis server\ntype Client struct {\n\tConfig Config\n\tPool *radix.Pool\n}\n\n// NewClient creates a new client\nfunc NewClient(config Config) *Client {\n\treturn &Client{Config: config}\n}\n\n// Connect to a redis server\nfunc (client *Client) Connect() error {\n\tsize := client.Config.PoolSize\n\tconnFunc := func(network, addr string) (radix.Conn, error) {\n\t\topts := []radix.DialOpt{}\n\t\tif client.Config.Password != \"\" {\n\t\t\topts = append(opts, radix.DialAuthPass(client.Config.Password))\n\t\t}\n\t\tif client.Config.SSLEnabled {\n\t\t\tif client.Config.CACert != \"\" {\n\t\t\t\troots := x509.NewCertPool()\n\t\t\t\tok := roots.AppendCertsFromPEM([]byte(client.Config.CACert))\n\t\t\t\tif !ok {\n\t\t\t\t\tpanic(\"failed to parse root certificate\")\n\t\t\t\t}\n\t\t\t\ttlsConfig := &tls.Config{RootCAs: roots}\n\t\t\t\topts = append(opts, radix.DialUseTLS(tlsConfig))\n\t\t\t} else {\n\t\t\t\ttlsConfig := &tls.Config{InsecureSkipVerify: true}\n\t\t\t\topts = append(opts, radix.DialUseTLS(tlsConfig))\n\t\t\t}\n\t\t}\n\t\treturn radix.Dial(network, addr, opts...)\n\t}\n\n\tdefaultPoolOpts := []radix.PoolOpt{\n\t\tradix.PoolConnFunc(connFunc),\n\t\tradix.PoolOnEmptyCreateAfter(1 * time.Second),\n\t\tradix.PoolRefillInterval(1 * time.Second),\n\t\tradix.PoolOnFullBuffer((size/3)+1, 1*time.Second),\n\t\tradix.PoolPingInterval(5 * time.Second / time.Duration(size+1)),\n\t\tradix.PoolPipelineConcurrency(size),\n\t\t// NOTE if 150us is changed the benchmarks need to be updated too\n\t\tradix.PoolPipelineWindow(150*time.Microsecond, 0),\n\t}\n\n\tpool, err := radix.NewPool(\"tcp\", fmt.Sprintf(\"%s:%d\", client.Config.Host, client.Config.Port), client.Config.PoolSize, defaultPoolOpts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient.Pool = pool\n\treturn nil\n}\n\n// Disconnect -- close the connection to the redis instance\nfunc (client *Client) Disconnect() error {\n\treturn client.Pool.Close()\n}\n\n// Exec processes a command on the redis server with the given arguments\nfunc (client *Client) Exec(val interface{}, command, key string, args ...interface{}) error {\n\treturn client.Pool.Do(radix.FlatCmd(val, command, key, args...))\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":960,"cells":{"blob_id":{"kind":"string","value":"5ed29cf052395347f06b4bb95b52ac5cbe2383b9"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"ethanfrogers/springo-config"},"path":{"kind":"string","value":"/pkg/parser_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2679,"string":"2,679"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package pkg\n\nimport (\n\t\"testing\"\n)\n\nvar baseCase = `\nfoo:\n bar: foobar\nfoo1:\n bar1: ${foo.bar}\n`\n\nvar baseResult = `\nfoo:\n bar: foobar\nfoo1:\n bar1: foobar\n`\n\nvar withEnvironmentVariablesCase = `\nfoo:\n bar: ${TEST_CASE:tacobell}\n`\n\nvar withEnvironmentVariablesResult = `\nfoo:\n bar: HELLOWORLD\n`\n\nvar selfReferentalWithDefaultBase = `\nservices:\n taco: bell\nfoo:\n bar: ${services.test:false}\n`\n\nvar selfReferentalWithDefaultResult = `\nservices:\n taco: bell\nfoo:\n bar: false\n`\n\nvar environmentVariableWithUrlBase = `\nfoo:\n bar: ${TEST_ME:http://test.io}\n`\n\nvar environmentVariableWithUrlResult = `\nfoo:\n bar: http://test.io\n`\n\nvar onlyEnvironmentVariableBase = `\nfoo:\n bar: ${TEST_CASE}\n`\n\nvar onlyEnvionmentVariableResult = `\nfoo:\n bar: HELLOWORLD\n`\n\nvar recursiveBase = `\nfoo:\n bar: ${car.dar}\ncar:\n dar: ${mar.lar}\nmar:\n lar: test\n`\n\nvar recursiveResult = `\nfoo:\n bar: test\ncar:\n dar: test\nmar:\n lar: test\n`\n\nvar withContextBase = `\nfoo:\n bar: ${fizz.buzz}\n`\n\nvar withContextResult = `\nfoo:\n bar: fizzbuzz\n`\n\nfunc TestParseAndEvaluateYAML(t *testing.T) {\n\tcases := []struct {\n\t\ttest string\n\t\texpected string\n\t\twithFunc []WithFunc\n\t\tname string\n\t\tcontext map[string]interface{}\n\t}{\n\t\t{\n\t\t\ttest: baseCase,\n\t\t\texpected: baseResult,\n\t\t\tname: \"base case\",\n\t\t},\n\t\t{\n\t\t\tname: \"case with environment variables\",\n\t\t\ttest: withEnvironmentVariablesCase,\n\t\t\texpected: withEnvironmentVariablesResult,\n\t\t\twithFunc: []WithFunc{func() (string, interface{}) {\n\t\t\t\treturn \"Env\", map[string]string{\"TEST_CASE\": \"HELLOWORLD\"}\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"self referential with default\",\n\t\t\ttest: selfReferentalWithDefaultBase,\n\t\t\texpected: selfReferentalWithDefaultResult,\n\t\t},\n\t\t{\n\t\t\tname: \"environment variable with url default\",\n\t\t\ttest: environmentVariableWithUrlBase,\n\t\t\texpected: environmentVariableWithUrlResult,\n\t\t},\n\t\t{\n\t\t\tname: \"only environment variable\",\n\t\t\ttest: onlyEnvironmentVariableBase,\n\t\t\texpected: onlyEnvionmentVariableResult,\n\t\t\twithFunc: []WithFunc{func() (string, interface{}) {\n\t\t\t\treturn \"Env\", map[string]string{\"TEST_CASE\": \"HELLOWORLD\"}\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"recursive\",\n\t\t\ttest: recursiveBase,\n\t\t\texpected: recursiveResult,\n\t\t},\n\t\t{\n\t\t\tname: \"with context\",\n\t\t\ttest: withContextBase,\n\t\t\texpected: withContextResult,\n\t\t\tcontext: map[string]interface{}{\"fizz\": map[string]string{\"buzz\": \"fizzbuzz\"}},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tr, err := ParseAndEvaluateYAML([]byte(c.test), c.context, c.withFunc...)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"case: %s, err: %s\", c.name, err.Error())\n\t\t}\n\n\t\tif string(r) != c.expected {\n\t\t\tt.Fatalf(\"expected: %s\\ngot: %s\\n\", c.expected, r)\n\t\t}\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":961,"cells":{"blob_id":{"kind":"string","value":"9d6cd25c7150d79e51cbff818fa08e09ccb9069e"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"isabst/zhihu"},"path":{"kind":"string","value":"/utils/utils.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2799,"string":"2,799"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package utils\n\nimport (\n\t\"crypto/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com/gitobhub/zhihu/config\"\n)\n\ntype Err struct {\n\tMessage string\n\tCode int\n}\n\nfunc (err *Err) Error() string {\n\treturn err.Message\n}\n\nconst (\n\tErrAccountNotFound = 100000 + iota\n\tErrIncorrectPassword\n\tErrDuplicatedEmail\n\tErrBadFullnameFormat\n\tErrBadEmailFormat\n\tErrBadPasswordFormat\n)\n\nfunc ValidateFullname(fullname string) *Err {\n\treg := regexp.MustCompile(`^[\\p{Han}\\w]+([\\p{Han}\\w\\s.-]*)$`)\n\tprintln(fullname)\n\tif !reg.MatchString(fullname) {\n\t\terr := &Err{\n\t\t\tMessage: \"名字中含有特殊字符\",\n\t\t\tCode: ErrBadFullnameFormat,\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ValidateUsername(username string) *Err {\n\treg := regexp.MustCompile(`^[a-zA-Z0-9]+@(\\w+).(\\w{2,5})$`) //Email\n\tif !reg.MatchString(username) {\n\t\terr := &Err{\n\t\t\tMessage: \"请输入正确的邮箱\",\n\t\t\tCode: ErrBadEmailFormat,\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc ValidatePassword(password string) *Err {\n\treg := regexp.MustCompile(`^(\\w+[\\w[:graph:]]*){6,}$`)\n\tif !reg.MatchString(password) {\n\t\terr := &Err{\n\t\t\tMessage: \"密码格式不正确\",\n\t\t\tCode: ErrBadPasswordFormat,\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc FormatUnixTime(dt int64) string {\n\tvar res string\n\tnow := time.Now()\n\tdatetime := time.Unix(dt, 0)\n\tyear, month, day := datetime.Date()\n\tnowYear, nowMonth, nowDay := now.Date()\n\tydaYear, ydaMonth, ydaDay := time.Unix((now.Unix() - 86400), 0).Date() //yesterday\n\n\tif nowYear == year && nowMonth == month && nowDay == day {\n\t\tres = datetime.Format(\"15:04\")\n\t} else if ydaYear == year && ydaMonth == month && ydaDay == day {\n\t\tres = \"昨天 \" + datetime.Format(\"15:04\")\n\t} else {\n\t\tres = datetime.Format(\"2006-01-02\")\n\t}\n\treturn res\n}\n\nconst (\n\tMinute = 60\n\tHour = 3600\n\tDay = 86400\n\tMonth = 86400 * 30\n\tYear = 86400 * 30 * 12\n)\n\nfunc FormatBeforeUnixTime(dt int64) string {\n\tvar res string\n\tnow := time.Now().Unix()\n\tdiff := now - dt\n\tswitch {\n\tcase diff < Minute:\n\t\tres = \"刚刚\"\n\tcase diff < Hour && diff >= Minute:\n\t\tres = fmt.Sprintf(\"%d分钟前\", diff/Minute)\n\tcase diff < Day && diff >= Hour:\n\t\tres = fmt.Sprintf(\"%d小时前\", diff/Hour)\n\tcase diff < Month && diff >= Day:\n\t\tres = fmt.Sprintf(\"%d天前\", diff/Day)\n\tcase diff < Year && diff >= Month:\n\t\tres = fmt.Sprintf(\"%d个月前\", diff/Month)\n\tcase diff >= Year:\n\t\tres = fmt.Sprintf(\"%d年前\", diff/Year)\n\t}\n\treturn res\n}\n\nfunc EncryptPassword(username, password string) string {\n\th := md5.New()\n\tio.WriteString(h, password)\n\tpwdMD5 := fmt.Sprintf(\"%x\", h.Sum(nil))\n\tio.WriteString(h, config.Server.Salt)\n\tio.WriteString(h, username)\n\tio.WriteString(h, pwdMD5)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc URLToken(urlToken *string, urlTokenCode int) {\n\tif urlTokenCode != 0 {\n\t\t*urlToken = fmt.Sprintf(\"%s-%d\", *urlToken, urlTokenCode)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":962,"cells":{"blob_id":{"kind":"string","value":"bf73083cae0706cb80b91c9f85de80b4aefb8e11"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"Dedalum/translate-klingon"},"path":{"kind":"string","value":"/http/client.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2971,"string":"2,971"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package http\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"time\"\n)\n\ntype (\n\t// Client holds the http client to query webpages\n\tClient struct {\n\t\tapiURL string\n\t\thttp.Client\n\t}\n\n\t// ClientConfig holds the configuration for the HTTP client\n\tClientConfig struct {\n\t\tAPIHost string `json:\"api_host\"`\n\t}\n)\n\nconst (\n\tapiPath = \"api/v1/rest\"\n\tapiCharacterSearch = \"character/search\"\n\tapiCharacter = \"character\"\n)\n\n// NewClient returns a pointer to a new client\nfunc NewClient(config *ClientConfig) *Client {\n\treturn &Client{\n\t\tfmt.Sprintf(\"http://%s/%s\", config.APIHost, apiPath),\n\t\thttp.Client{\n\t\t\tTimeout: time.Second * 3,\n\t\t},\n\t}\n}\n\n// GetCharacterUIDs queries the API for a given character name. It returns a\n// list of characters (e.g. \"Uhura\" returns 3 different UIDs).\nfunc (c *Client) GetCharacterUIDs(name string) ([]string, error) {\n\tvar characters []string\n\n\tif name == \"\" {\n\t\treturn characters, fmt.Errorf(\"character name is empty\")\n\t}\n\n\tvar dataStr = []byte(fmt.Sprintf(\"name=%s\", name))\n\tresp, err := c.Post(fmt.Sprintf(\"%s/%s\", c.apiURL, apiCharacterSearch),\n\t\t\"data\", bytes.NewBuffer(dataStr))\n\n\tif err != nil {\n\t\treturn characters, err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tuids, err := parseUIDs(body)\n\tif err != nil {\n\t\treturn characters, err\n\t}\n\n\treturn uids, nil\n}\n\n// parseUIDs returns the list of UIDs for a character given the JSON\n// response\nfunc parseUIDs(jsonData []byte) ([]string, error) {\n\tvar uids []string\n\n\ttype character struct {\n\t\tUID string `json:\"uid\"`\n\t}\n\tvar data struct {\n\t\tCharacters []character `json:\"characters\"`\n\t}\n\n\tif err := json.Unmarshal(jsonData, &data); err != nil {\n\t\treturn uids, err\n\t}\n\n\tfor _, character := range data.Characters {\n\t\tuids = append(uids, character.UID)\n\t}\n\n\treturn uids, nil\n}\n\n// GetCharacterSpeciesList returns the species for a given UID\nfunc (c *Client) GetCharacterSpeciesList(characterUID string) ([]string, error) {\n\n\tvar speciesList []string\n\n\tif characterUID == \"\" {\n\t\treturn speciesList, fmt.Errorf(\"character UID is empty\")\n\t}\n\n\tresp, err := c.Get(\n\t\tfmt.Sprintf(\"%s/%s?uid=%s\", c.apiURL, apiCharacter, characterUID))\n\tif err != nil {\n\t\treturn speciesList, err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tspeciesList, err = parseSpeciesList(body)\n\tif err != nil {\n\t\treturn speciesList, err\n\t}\n\n\treturn speciesList, nil\n\n}\n\n// parseSpecies returns the list of species for a character given the JSON\n// response\nfunc parseSpeciesList(jsonData []byte) ([]string, error) {\n\tvar speciesList []string\n\n\ttype character struct {\n\t\tSpeciesList []struct {\n\t\t\tName string `json:\"name\"`\n\t\t} `json:\"characterSpecies\"`\n\t}\n\n\tvar data struct {\n\t\tCharacter character `json:\"character\"`\n\t}\n\n\tif err := json.Unmarshal(jsonData, &data); err != nil {\n\t\treturn speciesList, err\n\t}\n\n\tfor _, species := range data.Character.SpeciesList {\n\t\tspeciesList = append(speciesList, species.Name)\n\t}\n\n\treturn speciesList, nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":963,"cells":{"blob_id":{"kind":"string","value":"b386298f7abc068b6f665822e9a5cbbb8641b680"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"mrpoundsign/adventofcode_2019"},"path":{"kind":"string","value":"/day10/step2/main_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1323,"string":"1,323"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport \"testing\"\n\nfunc Test_point_angleTo(t *testing.T) {\n\ttype fields struct {\n\t\tX int\n\t\tY int\n\t}\n\ttype args struct {\n\t\tp2 point\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t\twant float64\n\t}{\n\t\t{\n\t\t\tname: \"5,5 to 5,-16\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: 5, Y: -16}},\n\t\t\twant: 0,\n\t\t},\n\t\t{\n\t\t\tname: \"5,5 to 8,2\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: 8, Y: 2}},\n\t\t\twant: 45,\n\t\t},\n\t\t{\n\t\t\tname: \"5,5 to 16,5\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: 16, Y: 5}},\n\t\t\twant: 90,\n\t\t},\n\t\t{\n\t\t\tname: \"5,5 to 16,16\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: 16, Y: 16}},\n\t\t\twant: 135,\n\t\t},\n\t\t{\n\t\t\tname: \"5,5 to 5,16\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: 5, Y: 16}},\n\t\t\twant: 180,\n\t\t},\n\t\t{\n\t\t\tname: \"5,5 to -16,5\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: -16, Y: 5}},\n\t\t\twant: 270,\n\t\t},\n\t\t{\n\t\t\tname: \"5,5 to 0,0\",\n\t\t\tfields: fields{X: 5, Y: 5},\n\t\t\targs: args{point{X: 0, Y: 0}},\n\t\t\twant: 315,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tp := point{\n\t\t\t\tX: tt.fields.X,\n\t\t\t\tY: tt.fields.Y,\n\t\t\t}\n\t\t\tif got := p.angleTo(tt.args.p2); got != tt.want {\n\t\t\t\tt.Errorf(\"point.angleTo() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":964,"cells":{"blob_id":{"kind":"string","value":"58998b32b51a9ed00b5d007f6099a287ba637903"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"tpisani/clubinho-go"},"path":{"kind":"string","value":"/examples/err.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":169,"string":"169"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\tb, err := ioutil.ReadFile(\"missing.txt\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(\"bytes:\", b)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":965,"cells":{"blob_id":{"kind":"string","value":"28ea0a2d120879189a64e8ad654d15dc51b80561"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"huydinhle/golang-learning"},"path":{"kind":"string","value":"/HackerRank/Algorithms/warmup/4-a-very-big-sum/main.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":522,"string":"522"},"score":{"kind":"number","value":3.53125,"string":"3.53125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tslice, _ := readData()\n\tfmt.Println(Addition(slice))\n\n}\n\n// Addition get the sum of all numers\nfunc Addition(nums []int) int {\n\ttotal := 0\n\n\tfor _, v := range nums {\n\t\ttotal += v\n\t}\n\treturn total\n}\n\nfunc readData() ([]int, error) {\n\tvar length int\n\n\t_, err := fmt.Scanf(\"%d\", &length)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := make([]int, length)\n\n\tfor i := range data {\n\t\t_, err := fmt.Scanf(\"%d\", &data[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn data, nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":966,"cells":{"blob_id":{"kind":"string","value":"f3b5137ef218ed99196d3d25713fb3cf278b6dcb"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"NeuralSpaz/watcher"},"path":{"kind":"string","value":"/watcher.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2738,"string":"2,738"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"crypto/md5\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\nfunc init() {\n\tlog.SetOutput(os.Stdout)\n}\n\nvar fileStore *FileStateStore\n\nfunc main() {\n\tdir := flag.String(\"dir\", \"/root/\", \"the directory you want to monitor\")\n\tclean := flag.Bool(\"clean\", false, \"rebuild the database\")\n\t// store := flag.String(\"store\", \"store\", \"the file to store file states\")\n\tflag.Parse()\n\tfmt.Println(\"Adding Dirs to watch \", *dir)\n\n\tfileStore = NewFileStateStore(\"./filedb.json\")\n\tif !*clean {\n\t\tscandir, err := filepath.Abs(*dir)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\terr = filepath.Walk(scandir, visit)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"filepath.Walk() returned %v\\n\", err)\n\t\t}\n\t}\n\tif *clean {\n\t\tclose(fileStore.save)\n\t\tfmt.Println(\"Rehashing files\")\n\t\tfor key := range fileStore.files {\n\n\t\t\thash, err := hash_file_md5(key)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"problem hashing file: %s\\n\", key)\n\t\t\t\tdelete(fileStore.files, key)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tinfo, serr := os.Stat(key)\n\t\t\t\tif serr != nil {\n\t\t\t\t\tlog.Printf(\"problem getting stats on file: %s\\n\", key)\n\t\t\t\t\tdelete(fileStore.files, key)\n\t\t\t\t}\n\t\t\t\tif serr == nil {\n\t\t\t\t\tvar fs FileState\n\n\t\t\t\t\tfs.Hash = hash\n\t\t\t\t\tfs.LastModified = info.ModTime()\n\t\t\t\t\tfs.Path = key\n\t\t\t\t\tfileStore.files[key] = fs\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if err != nil {\n\t\t\t// \tlog.Printf(\"Error adding to clean db %s: %v\\n\", fs, err)\n\t\t\t// }\n\t\t}\n\t\tvar err = os.Remove(\"./filedb.json\")\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"unable to delete filedb\")\n\t\t}\n\t\tf, err := os.OpenFile(\"./filedb.json\", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\t\t// f, err := os.Open(\"./filedb.json\")\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"unable to write clean db file\")\n\t\t}\n\n\t\t// b := bufio.NewWriter(f)\n\t\te := json.NewEncoder(f)\n\t\tdefer f.Close()\n\t\t// defer b.Flush()\n\t\tfor key := range fileStore.files {\n\t\t\terr = e.Encode(fileStore.files[key])\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"FileStateStore Save:\", err)\n\t\t\t}\n\t\t}\n\n\t}\n\n}\n\nfunc visit(path string, f os.FileInfo, err error) error {\n\n\tif !f.IsDir() {\n\t\thash, err := hash_file_md5(path)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Hashing err %v of file %s\", err, path)\n\t\t\treturn err\n\t\t}\n\t\tvar fs FileState\n\t\tfs.Hash = hash\n\t\tfs.LastModified = f.ModTime()\n\t\tfs.Path = path\n\t\terr = fileStore.Put(fs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc hash_file_md5(filePath string) (string, error) {\n\tvar returnMD5String string\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn returnMD5String, err\n\t}\n\tdefer file.Close()\n\thash := md5.New()\n\tif _, err := io.Copy(hash, file); err != nil {\n\t\treturn returnMD5String, err\n\t}\n\thashInBytes := hash.Sum(nil)[:16]\n\treturnMD5String = hex.EncodeToString(hashInBytes)\n\treturn returnMD5String, nil\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":967,"cells":{"blob_id":{"kind":"string","value":"ab910bccdd90608cf88ad7823aa7ef9158806bbc"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"brongineers/pgcenter"},"path":{"kind":"string","value":"/internal/view/view_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6244,"string":"6,244"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package view\n\nimport (\n\t\"github.com/lesovsky/pgcenter/internal/query\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\nfunc TestNew(t *testing.T) {\n\tv := New()\n\tassert.Equal(t, 18, len(v)) // 18 is the total number of views have to be returned\n}\n\nfunc TestViews_Configure(t *testing.T) {\n\ttestcases := []struct {\n\t\tversion int\n\t\trecovery string\n\t\ttrackCommit string\n\t\tquerylen int\n\t}{\n\t\t// v13 matrix\n\t\t{version: 130000, recovery: \"f\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 130000, recovery: \"f\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 130000, recovery: \"f\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 130000, recovery: \"f\", trackCommit: \"off\", querylen: 0},\n\t\t{version: 130000, recovery: \"t\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 130000, recovery: \"t\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 130000, recovery: \"t\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 130000, recovery: \"t\", trackCommit: \"off\", querylen: 0},\n\t\t// v12 matrix\n\t\t{version: 120000, recovery: \"f\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 120000, recovery: \"f\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 120000, recovery: \"f\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 120000, recovery: \"f\", trackCommit: \"off\", querylen: 0},\n\t\t{version: 120000, recovery: \"t\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 120000, recovery: \"t\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 120000, recovery: \"t\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 120000, recovery: \"t\", trackCommit: \"off\", querylen: 0},\n\t\t// v11 matrix\n\t\t{version: 110000, recovery: \"f\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 110000, recovery: \"f\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 110000, recovery: \"f\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 110000, recovery: \"f\", trackCommit: \"off\", querylen: 0},\n\t\t{version: 110000, recovery: \"t\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 110000, recovery: \"t\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 110000, recovery: \"t\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 110000, recovery: \"t\", trackCommit: \"off\", querylen: 0},\n\t\t// v9.6 matrix\n\t\t{version: 90600, recovery: \"f\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 90600, recovery: \"f\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 90600, recovery: \"f\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 90600, recovery: \"f\", trackCommit: \"off\", querylen: 0},\n\t\t{version: 90600, recovery: \"t\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 90600, recovery: \"t\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 90600, recovery: \"t\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 90600, recovery: \"t\", trackCommit: \"off\", querylen: 0},\n\t\t// v9.5 matrix\n\t\t{version: 90500, recovery: \"f\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 90500, recovery: \"f\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 90500, recovery: \"f\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 90500, recovery: \"f\", trackCommit: \"off\", querylen: 0},\n\t\t{version: 90500, recovery: \"t\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 90500, recovery: \"t\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 90500, recovery: \"t\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 90500, recovery: \"t\", trackCommit: \"off\", querylen: 0},\n\t\t// v9.4 matrix\n\t\t{version: 90400, recovery: \"f\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 90400, recovery: \"f\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 90400, recovery: \"f\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 90400, recovery: \"f\", trackCommit: \"off\", querylen: 0},\n\t\t{version: 90400, recovery: \"t\", trackCommit: \"on\", querylen: 256},\n\t\t{version: 90400, recovery: \"t\", trackCommit: \"on\", querylen: 0},\n\t\t{version: 90400, recovery: \"t\", trackCommit: \"off\", querylen: 256},\n\t\t{version: 90400, recovery: \"t\", trackCommit: \"off\", querylen: 0},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tviews := New()\n\t\topts := query.NewOptions(tc.version, tc.recovery, tc.trackCommit, tc.querylen, \"public\")\n\t\terr := views.Configure(opts)\n\t\tassert.NoError(t, err)\n\n\t\tswitch tc.version {\n\t\tcase 130000:\n\t\t\tif tc.trackCommit == \"on\" {\n\t\t\t\tassert.Equal(t, query.PgStatReplicationExtended, views[\"replication\"].QueryTmpl)\n\t\t\t\tassert.Equal(t, 17, views[\"replication\"].Ncols)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, query.PgStatReplicationDefault, views[\"replication\"].QueryTmpl)\n\t\t\t}\n\t\tcase 120000:\n\t\t\tif tc.trackCommit == \"on\" {\n\t\t\t\tassert.Equal(t, query.PgStatReplicationExtended, views[\"replication\"].QueryTmpl)\n\t\t\t\tassert.Equal(t, 17, views[\"replication\"].Ncols)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, query.PgStatReplicationDefault, views[\"replication\"].QueryTmpl)\n\t\t\t}\n\t\t\tassert.Equal(t, query.PgStatStatementsTimingPG12, views[\"statements_timings\"].QueryTmpl)\n\t\tcase 110000:\n\t\t\tif tc.trackCommit == \"on\" {\n\t\t\t\tassert.Equal(t, query.PgStatReplicationExtended, views[\"replication\"].QueryTmpl)\n\t\t\t\tassert.Equal(t, 17, views[\"replication\"].Ncols)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, query.PgStatReplicationDefault, views[\"replication\"].QueryTmpl)\n\t\t\t}\n\t\t\tassert.Equal(t, query.PgStatDatabasePG11, views[\"databases\"].QueryTmpl)\n\t\t\tassert.Equal(t, 17, views[\"databases\"].Ncols)\n\t\t\tassert.Equal(t, [2]int{1, 15}, views[\"databases\"].DiffIntvl)\n\t\tcase 90600:\n\t\t\tif tc.trackCommit == \"on\" {\n\t\t\t\tassert.Equal(t, query.PgStatReplication96Extended, views[\"replication\"].QueryTmpl)\n\t\t\t\tassert.Equal(t, 14, views[\"replication\"].Ncols)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, query.PgStatReplication96, views[\"replication\"].QueryTmpl)\n\t\t\t\tassert.Equal(t, 12, views[\"replication\"].Ncols)\n\t\t\t}\n\t\t\tassert.Equal(t, query.PgStatActivity96, views[\"activity\"].QueryTmpl)\n\t\t\tassert.Equal(t, 13, views[\"activity\"].Ncols)\n\t\tcase 90500:\n\t\t\tassert.Equal(t, query.PgStatActivity95, views[\"activity\"].QueryTmpl)\n\t\t\tassert.Equal(t, 12, views[\"activity\"].Ncols)\n\t\t}\n\n\t\tfor _, v := range views {\n\t\t\tassert.NotEqual(t, \"\", v.Query)\n\t\t}\n\t}\n}\n\nfunc TestView_VersionOK(t *testing.T) {\n\ttestcases := []struct {\n\t\tversion int\n\t\ttotal int\n\t}{\n\t\t{version: 130000, total: 18},\n\t\t{version: 120000, total: 15},\n\t\t{version: 110000, total: 13},\n\t\t{version: 100000, total: 13},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tviews := New()\n\n\t\tvar total int\n\t\tfor _, v := range views {\n\t\t\tif v.VersionOK(tc.version) {\n\t\t\t\ttotal++\n\t\t\t}\n\t\t}\n\t\tassert.Equal(t, tc.total, total)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":968,"cells":{"blob_id":{"kind":"string","value":"794a7cfe36b161bb4925ebac7cca541c20ea730b"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"JasonSpeak/LearnGoWithTest"},"path":{"kind":"string","value":"/BaseKnowledge/maps/Dictionary.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":605,"string":"605"},"score":{"kind":"number","value":3.6875,"string":"3.6875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package maps\n\nimport \"errors\"\n\nvar (\n\tErrNotFound = errors.New(\"could not find the word you were looking for\")\n\tErrWordExists = errors.New(\"cannot add word because it already exists\")\n)\n\ntype Dictionary map[string]string\n\nfunc (dictionary Dictionary) Search(key string) (string, error) {\n\tdefinition, ok := dictionary[key]\n\n\tif !ok {\n\t\treturn \"\", ErrNotFound\n\t}\n\treturn definition, nil\n}\n\nfunc (d Dictionary) Add(key, value string) error {\n\t_, isExist := d.Search(key)\n\n\tswitch isExist {\n\tcase ErrNotFound:\n\t\td[key] = value\n\tcase nil:\n\t\treturn ErrWordExists\n\tdefault:\n\t\treturn isExist\n\t}\n\n\treturn nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":969,"cells":{"blob_id":{"kind":"string","value":"9f8be2bdcde3740fd06dce8dc51e08414944616b"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"shouliang/Development"},"path":{"kind":"string","value":"/Go/go_inaction/src/chapter6/listing07/listing07.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1172,"string":"1,172"},"score":{"kind":"number","value":4.15625,"string":"4.15625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// 展示如何创建goroutine以及调度器的行为\npackage main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n)\n\nfunc main() {\n\t// 分配2个逻辑处理器给调度器使用\n\t// 2个逻辑处理器,goroutine是真正的同时运行,而不是CPU时间片切换\n\truntime.GOMAXPROCS(2)\n\n\t// wg 用来等待程序完成\n\t// 计数加2,表示要等待2个goroutine\n\t// WaitGroup是一个计数信号量,值大于0,Wait()方法就会阻塞\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tfmt.Println(\"Start Goroutines\")\n\n\t// go关键字后声明一个匿名函数来运行一个goroutine\n\tgo func() {\n\t\t// Schedule the call to Done to tell main we are done\n\t\tdefer wg.Done()\n\n\t\tfor count := 0; count < 3; count++ {\n\t\t\tfor char := 'a'; char < 'a'+26; char++ {\n\t\t\t\tfmt.Printf(\"%c\", char)\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t// Dispaly the alphebet three times\n\t\tfor count := 0; count < 3; count++ {\n\t\t\tfor char := 'A'; char < 'A'+26; char++ {\n\t\t\t\tfmt.Printf(\"%c\", char)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// 等待goroutines结束\n\t// 各个goroutine是并发执行的,而不是按照代码编写的顺序\n\tfmt.Println(\"Waiting to Finish\")\n\twg.Wait()\n\n\tfmt.Printf(\"\\nTerminating Program\")\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":970,"cells":{"blob_id":{"kind":"string","value":"32be905c17e55a9d8ec8b85419bd909d91f4e310"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"konatu/study_tour_of_go"},"path":{"kind":"string","value":"/struct/field_access.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":119,"string":"119"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\nimport(\n \"fmt\"\n)\n\ntype st struct{\n x int\n y int\n}\n\nfunc main(){\n v := st{55, 18}\n fmt.Println(v.x)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":971,"cells":{"blob_id":{"kind":"string","value":"9715668ff9f96d3f467f1b1e49e9f104c0875da6"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"footprint-it-solutions/kube-annotate"},"path":{"kind":"string","value":"/annotator/mutator_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1098,"string":"1,098"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package annotator\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestCreatePatchFromAnnotations(t *testing.T) {\n\tpodAnnotations := map[string]string{\n\t\t\"hello\": \"world\",\n\t}\n\trulesAnnotations := map[string]string{\n\t\t\"log\": \"enabled\",\n\t}\n\tpatch := createPatchFromAnnotations(podAnnotations, rulesAnnotations)\n\tassert.Equal(t, \"replace\", patch.Op)\n\tassert.Equal(t, \"/metadata/annotations\", patch.Path)\n\tassert.IsType(t, podAnnotations, patch.Value)\n\n\tvaluesAsMap := patch.Value.(map[string]string)\n\tassert.Len(t, valuesAsMap, 2)\n\tassert.Equal(t, \"world\", valuesAsMap[\"hello\"])\n\tassert.Equal(t, \"enabled\", valuesAsMap[\"log\"])\n}\n\nfunc TestCreatePatchFromNilAnnotations(t *testing.T) {\n\trulesAnnotations := map[string]string{\n\t\t\"log\": \"enabled\",\n\t}\n\tpatch := createPatchFromAnnotations(nil, rulesAnnotations)\n\tassert.Equal(t, \"add\", patch.Op)\n\tassert.Equal(t, \"/metadata/annotations\", patch.Path)\n\tassert.IsType(t, make(map[string]string), patch.Value)\n\n\tvaluesAsMap := patch.Value.(map[string]string)\n\tassert.Len(t, valuesAsMap, 1)\n\tassert.Equal(t, \"enabled\", valuesAsMap[\"log\"])\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":972,"cells":{"blob_id":{"kind":"string","value":"99e76736862f0856b0b2aada93f189ee1bd7ab9a"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"philkry/drivers"},"path":{"kind":"string","value":"/tplink/hs1xx_hal.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1084,"string":"1,084"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package tplink\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/reef-pi/hal\"\n\t\"github.com/reef-pi/rpi/i2c\"\n)\n\ntype HS1xxPlugConfig struct {\n\tAddress string `json:\"address\"`\n}\n\nvar meta = hal.Metadata{\n\tName: \"tplink-hs1xx\",\n\tDescription: \"Supports tplink hs1xx series smart plugs\",\n\tCapabilities: []hal.Capability{\n\t\thal.Output,\n\t},\n}\n\nfunc HALAdapter(c []byte, _ i2c.Bus) (hal.Driver, error) {\n\tvar conf HS1xxPlugConfig\n\tif err := json.Unmarshal(c, &conf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewHS1xxPlug(conf.Address), nil\n}\n\nfunc (p *HS1xxPlug) Metadata() hal.Metadata {\n\treturn meta\n}\nfunc (p *HS1xxPlug) Name() string {\n\treturn meta.Name\n}\n\nfunc (p *HS1xxPlug) OutputPins() []hal.OutputPin {\n\treturn []hal.OutputPin{p}\n}\nfunc (p *HS1xxPlug) OutputPin(i int) (hal.OutputPin, error) {\n\tif i != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid pin: %d\", i)\n\t}\n\treturn p, nil\n}\n\nfunc (p *HS1xxPlug) Write(state bool) error {\n\tif state {\n\t\treturn p.On()\n\t}\n\treturn p.Off()\n}\n\nfunc (p *HS1xxPlug) LastState() bool {\n\treturn p.state\n}\nfunc (p *HS1xxPlug) Close() error {\n\treturn nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":973,"cells":{"blob_id":{"kind":"string","value":"def8d3abbb3204daeef2f5cac9cf095aba2ec9dc"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"Myavuz34/GoExamples"},"path":{"kind":"string","value":"/JSON/main.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2186,"string":"2,186"},"score":{"kind":"number","value":3.4375,"string":"3.4375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Name struct {\n\tFamily string\n\tPersonel string\n}\n\ntype Email struct {\n\tID int\n\tKind string\n\tAddress string\n}\n\ntype Interest struct {\n\tID int\n\tName string\n}\n\ntype Person struct {\n\tID int\n\tFirstName string\n\tLastName string\n\tUserName string\n\tGender string\n\tName Name\n\tEmail []Email\n\tInterest []Interest\n}\n\nfunc GetPerson(p *Person) string {\n\treturn p.FirstName + \" \" + p.LastName\n}\n\nfunc GetPersonEmailAddress(p *Person, i int) string {\n\treturn p.Email[i].Address\n}\n\nfunc GetPersonEmail(p *Person, i int) Email {\n\treturn p.Email[i]\n}\n\nfunc WriteMessage(msg string) {\n\tfmt.Println(msg)\n}\n\nfunc WriteStarLine() {\n\tfmt.Println(\"*************************\")\n}\n\nfunc CheckError(err error) {\n\tif err != nil {\n\t\tfmt.Println(\"Fata Error: \", err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\nfunc SaveJSON(fileName string, key interface{}) {\n\n\toutFile, err := os.Create(fileName)\n\tCheckError(err)\n\tencoder := json.NewEncoder(outFile)\n\terr = encoder.Encode(key)\n\tCheckError(err)\n\toutFile.Close()\n}\n\nfunc main() {\n\n\tperson := Person{\n\t\tID: 10,\n\t\tFirstName: \"Mustafa\",\n\t\tLastName: \"Yavuz\",\n\t\tUserName: \"Myavuz\",\n\t\tGender: \"E\",\n\t\tName: Name{Family: \"bididibid\", Personel: \"Mustafa\"},\n\t\tEmail: []Email{\n\t\t\tEmail{ID: 1, Kind: \"Work\", Address: \"myavuz53@gmail.com\"},\n\t\t\tEmail{ID: 2, Kind: \"Home\", Address: \"mustafayavuz34@hotmail.com.tr\"},\n\t\t},\n\t\tInterest: []Interest{\n\t\t\tInterest{ID: 1, Name: \"Go\"},\n\t\t\tInterest{ID: 2, Name: \"C#\"},\n\t\t\tInterest{ID: 3, Name: \"Python\"},\n\t\t},\n\t}\n\n\tWriteMessage(\"Reading Operation Started\")\n\n\tWriteMessage(\"Personel Fullname\")\n\tWriteStarLine()\n\tres := GetPerson(&person)\n\tWriteMessage(res)\n\tWriteStarLine()\n\n\tWriteMessage(\"\\n\")\n\n\tWriteMessage(\"Personel Emil With Index\")\n\tWriteStarLine()\n\tresEmail := GetPersonEmailAddress(&person, 1)\n\tWriteMessage(resEmail)\n\tWriteStarLine()\n\tWriteMessage(\"\\n\")\n\n\tWriteMessage(\"Personel Email Object winth Index\")\n\tWriteStarLine()\n\tresEmail2 := GetPersonEmail(&person, 0)\n\tfmt.Println(resEmail2)\n\tWriteStarLine()\n\n\tWriteMessage(\"Reading Operation Ended\")\n\tWriteMessage(\"\\n\")\n\tWriteMessage(\"Writing Operation Started\")\n\tSaveJSON(\"person.json\", person)\n\tWriteMessage(\"Writing Operation Ended\")\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":974,"cells":{"blob_id":{"kind":"string","value":"84a9d3c53a848f361a93707cbcc2b7e6c61423e0"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"CristoferNava/cardinal"},"path":{"kind":"string","value":"/db/removeTweet.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":598,"string":"598"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package db\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.mongodb.org/mongo-driver/bson\"\n\t\"go.mongodb.org/mongo-driver/bson/primitive\"\n)\n\n// RemoveTweet removes a tweet given an tweetID and a userID\nfunc RemoveTweet(tweetID, userID string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\tdefer cancel()\n\n\tdb := MongoConnection.Database(\"cardinal\")\n\ttweetsCollection := db.Collection(\"tweets\")\n\n\tobjID, _ := primitive.ObjectIDFromHex(tweetID)\n\tcondition := bson.M{\n\t\t\"_id\": objID,\n\t\t\"userID\": userID,\n\t}\n\n\t_, err := tweetsCollection.DeleteOne(ctx, condition)\n\treturn err\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":975,"cells":{"blob_id":{"kind":"string","value":"72340b645f48f7dc9259e6845482f8bd02c5cce5"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"chebrolus/golearn"},"path":{"kind":"string","value":"/stringutil/palindrome_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1010,"string":"1,010"},"score":{"kind":"number","value":3.40625,"string":"3.40625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package stringutil\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n)\n\nfunc TestIsPalindrome(t *testing.T) {\n\t// test data with expected result\n\tvar tests = []struct {\n\t\ts string\n\t\tisPalindrome bool\n\t}{\n\t\t{\"\", false},\n\t\t{\"m\", true},\n\t\t{\"ace\", false},\n\t\t{\"ana\", true},\n\t\t{\"anna\", true},\n\t\t{\"aloha\", false},\n\t\t{\"alola\", true},\n\t\t{\"civic\", true},\n\t\t{\"toyota\", false},\n\t\t{\"not a palindrome\", false},\n\t}\n\n\t// for each entry in test data apply function and compare with expected result\n\tfor _, c := range tests {\n\t\tgot := isPalindrome(c.s)\n\t\tif got != c.isPalindrome {\n\t\t\t// fail if the result doesn't match expected\n\t\t\tt.Errorf(\"isPalindrome(%v) == %v, want %v\", c.s, got, c.isPalindrome)\n\t\t}\n\t}\n}\n\nfunc BenchmarkIsPalindrome(b *testing.B) {\n\t// input array\n\tip := []string{\"\", \"civic\", \"a\", \"aloha\", \"ahoha\", \"palindrome\", \"verylongstringforpalindrometest\", \"aaaaabbbbcccddeddcccbbbbaaaaa\"}\n\tfor i := 1; i < b.N; i++ {\n\t\t// random input selection from the given input array\n\t\tisPalindrome(ip[rand.Intn(len(ip))])\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":976,"cells":{"blob_id":{"kind":"string","value":"3bfb325a91c6f1d57b623439d39a468bf5fe4f00"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"liampulles/cabiria"},"path":{"kind":"string","value":"/cmd/cabiria-generate/core/video.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4565,"string":"4,565"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package core\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com/liampulles/cabiria/pkg/array\"\n\t\"github.com/liampulles/cabiria/pkg/image\"\n\t\"github.com/liampulles/cabiria/pkg/intertitle\"\n\tcabiriaMath \"github.com/liampulles/cabiria/pkg/math\"\n\t\"github.com/liampulles/cabiria/pkg/video\"\n\n\t\"github.com/jinzhu/copier\"\n)\n\n// VideoConfiguration provides configuration options necessary to extract video information\ntype VideoConfiguration interface {\n\tVideoPath() string\n\tFrameOutputDirectory() string\n\tPredictorPath() string\n\tSmoothingClosingThreshold() uint\n\tSmoothingOpeningThreshold() uint\n}\n\n// VideoInformation provides relevant information about the video (including\n// the intertitles)\ntype VideoInformation struct {\n\tVideoFPS float64\n\tVideoWidth int\n\tVideoHeight int\n\tIntertitleRanges []intertitle.Range\n}\n\n// ExtractVideoInformation reads relevant information from the input video\nfunc ExtractVideoInformation(config VideoConfiguration) (VideoInformation, error) {\n\tfmt.Print(\"Extracting video information\")\n\t// Extract frames to configured dir\n\tframePaths, err := video.ExtractFrames(config.VideoPath(), config.FrameOutputDirectory())\n\tif err != nil {\n\t\treturn VideoInformation{}, err\n\t}\n\tprintProgressDot()\n\n\t// Predict intertitle frames\n\tpredictions, err := predictIntertitles(framePaths, config.PredictorPath())\n\tif err != nil {\n\t\treturn VideoInformation{}, err\n\t}\n\tprintProgressDot()\n\n\t// Smooth intertitle frames\n\tsmoothIntertitles(predictions, config.SmoothingClosingThreshold(), config.SmoothingOpeningThreshold())\n\tprintProgressDot()\n\n\t// Get some basic video info\n\tbasicInfo, err := video.GetBasicInformation(config.VideoPath())\n\tif err != nil {\n\t\treturn VideoInformation{}, err\n\t}\n\tprintProgressDot()\n\n\t// Extract intertitle timings\n\tinterRanges, err := intertitle.MapRanges(predictions, basicInfo.FPS, framePaths)\n\tif err != nil {\n\t\treturn VideoInformation{}, err\n\t}\n\tprintDone()\n\n\treturn VideoInformation{\n\t\tVideoFPS: basicInfo.FPS,\n\t\tVideoHeight: basicInfo.Height,\n\t\tVideoWidth: basicInfo.Width,\n\t\tIntertitleRanges: interRanges,\n\t}, nil\n}\n\nfunc predictIntertitles(framePaths []string, predictorPath string) ([]bool, error) {\n\tpredictor, err := intertitle.Load(predictorPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Split into workers\n\t_, workerCount := cabiriaMath.MinMaxInt(1, runtime.NumCPU()/2)\n\tvar wg sync.WaitGroup\n\tframePathsDivided := divideStringArray(framePaths, workerCount)\n\tpredictionsDivided := setupPredictionsArrays(len(framePaths), workerCount)\n\terrors := make([]error, workerCount)\n\tfor i := 0; i < workerCount; i++ {\n\t\twg.Add(1)\n\t\t// Setup vars\n\t\tvar predictorCopy intertitle.Predictor\n\t\tcopier.Copy(&predictorCopy, &predictor)\n\n\t\tgo predictIntertitlesWorker(&predictorCopy, framePathsDivided[i], predictionsDivided[i], errors[i], &wg)\n\t}\n\twg.Wait()\n\n\t// Check for errors\n\tfor _, err := range errors {\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Construct predictions array\n\tvar predictions []bool\n\tfor _, elem := range predictionsDivided {\n\t\tpredictions = append(predictions, elem...)\n\t}\n\treturn predictions, nil\n}\n\nfunc predictIntertitlesWorker(predictor *intertitle.Predictor, framePaths []string, predictions []bool, err error, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tfor i, path := range framePaths {\n\t\t// if i%3 == 0 {\n\t\t// \tfmt.Printf(\"Processing: %f%%\\n\", float64(i*100)/float64(len(framePaths)))\n\t\t// }\n\t\timg, potentialErr := image.GetPNG(path)\n\t\tif potentialErr != nil {\n\t\t\terr = potentialErr\n\t\t\treturn\n\t\t}\n\n\t\tprediction, potentialErr := predictor.PredictSingle(img)\n\t\tif potentialErr != nil {\n\t\t\terr = potentialErr\n\t\t\treturn\n\t\t}\n\t\tpredictions[i] = prediction\n\t}\n\tprintProgressDot()\n}\n\nfunc smoothIntertitles(intertitles []bool, closingThreshold, openingThreshold uint) {\n\tarray.CloseBoolArray(intertitles, closingThreshold)\n\tarray.OpenBoolArray(intertitles, openingThreshold)\n}\n\nfunc divideStringArray(many []string, parts int) [][]string {\n\tvar divided [][]string\n\tchunkSize := (len(many) + parts - 1) / parts\n\tfor i := 0; i < len(many); i += chunkSize {\n\t\tend := i + chunkSize\n\t\tif end > len(many) {\n\t\t\tend = len(many)\n\t\t}\n\t\tdivided = append(divided, many[i:end])\n\t}\n\treturn divided\n}\n\nfunc setupPredictionsArrays(total int, parts int) [][]bool {\n\tvar divided [][]bool\n\tchunkSize := (total + parts - 1) / parts\n\tfor i := 0; i < total; i += chunkSize {\n\t\tend := i + chunkSize\n\t\tif end > total {\n\t\t\tend = total\n\t\t}\n\t\tdivided = append(divided, make([]bool, end-i))\n\t}\n\treturn divided\n}\n\nfunc printProgressDot() {\n\tfmt.Print(\".\")\n}\n\nfunc printDone() {\n\tfmt.Print(\"DONE\\n\")\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":977,"cells":{"blob_id":{"kind":"string","value":"2ebcba280650d26bbb2e5f6cf79970dafeea7c1c"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"dhruv-bansal/golang-exploration"},"path":{"kind":"string","value":"/basic/datatypes/main.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":671,"string":"671"},"score":{"kind":"number","value":4.28125,"string":"4.28125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\n\t// explicit declaration\n\tvar i int\n\ti = 32 // explicit initialization\n\tfmt.Println(i)\n\n\t// explicit declaration and initialization\n\tvar f float32 = 3.14\n\tfmt.Println(f)\n\n\t// implicit declaration with initialization\n\ttitle := \"go data types\"\n\tfmt.Println(\"Title\", title)\n\n\t// implicit declaration of Boolean\n\tb := false\n\tfmt.Println(\"Boolean\", b)\n\n\t// complex data type is built in GO\n\tc := complex(3, 4)\n\tfmt.Println(\"Complex Variable\", c)\n\n\t// multi assignment in the go\n\t// two variables in the left and two functions in the right\n\treal, img := real(c), imag(c)\n\tfmt.Println(\"Real number and imaginary number\", real, img)\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":978,"cells":{"blob_id":{"kind":"string","value":"077aa6b7fc2a4582ed32c9af42c72fbb056f84d8"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"code-mv/logreporter-go-core"},"path":{"kind":"string","value":"/utils/utils.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":424,"string":"424"},"score":{"kind":"number","value":3.578125,"string":"3.578125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package utils\n\n// ItemInSlice is a utility function that returns true\n// if list contains the interface a\nfunc ItemInSlice(a interface{}, list []interface{}) bool {\n\tfor _, b := range list {\n\t\tif b == a {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// AddAll adds all map entries from a source map to a target map\nfunc AddAll(source map[string]string, target map[string]string) {\n\tfor k, v := range source {\n\t\ttarget[k] = v\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":979,"cells":{"blob_id":{"kind":"string","value":"97cb15ce143531c1e5f57428dc58ac94bd3b6bb6"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"BitonicNL/btcd"},"path":{"kind":"string","value":"/txscript/sigcache.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4109,"string":"4,109"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["ISC"],"string":"[\n \"ISC\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["ISC"],"string":"[\n \"ISC\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// Copyright (c) 2015 The btcsuite developers\n// Use of this source code is governed by an ISC\n// license that can be found in the LICENSE file.\n\npackage txscript\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"sync\"\n\n\t\"github.com/btcsuite/btcd/btcec\"\n\t\"github.com/btcsuite/btcd/wire\"\n)\n\n// sigInfo represents an entry in the SigCache. Entries in the sigcache are a\n// 3-tuple: (sigHash, sig, pubKey).\ntype sigInfo struct {\n\tsigHash wire.ShaHash\n\tsig string\n\tpubKey string\n}\n\n// SigCache implements an ECDSA signature verification cache with a randomized\n// entry eviction policy. Only valid signatures will be added to the cache. The\n// benefits of SigCache are two fold. Firstly, usage of SigCache mitigates a DoS\n// attack wherein an attack causes a victim's client to hang due to worst-case\n// behavior triggered while processing attacker crafted invalid transactions. A\n// detailed description of the mitigated DoS attack can be found here:\n// https://bitslog.wordpress.com/2013/01/23/fixed-bitcoin-vulnerability-explanation-why-the-signature-cache-is-a-dos-protection/.\n// Secondly, usage of the SigCache introduces a signature verification\n// optimization which speeds up the validation of transactions within a block,\n// if they've already been seen and verified within the mempool.\ntype SigCache struct {\n\tsync.RWMutex\n\tvalidSigs map[sigInfo]struct{}\n\tmaxEntries uint\n}\n\n// NewSigCache creates and initializes a new instance of SigCache. Its sole\n// parameter 'maxEntries' represents the maximum number of entries allowed to\n// exist in the SigCache at any particular moment. Random entries are evicted\n// to make room for new entries that would cause the number of entries in the\n// cache to exceed the max.\nfunc NewSigCache(maxEntries uint) *SigCache {\n\treturn &SigCache{validSigs: make(map[sigInfo]struct{}), maxEntries: maxEntries}\n}\n\n// Exists returns true if an existing entry of 'sig' over 'sigHash' for public\n// key 'pubKey' is found within the SigCache. Otherwise, false is returned.\n//\n// NOTE: This function is safe for concurrent access. Readers won't be blocked\n// unless there exists a writer, adding an entry to the SigCache.\nfunc (s *SigCache) Exists(sigHash wire.ShaHash, sig *btcec.Signature, pubKey *btcec.PublicKey) bool {\n\tinfo := sigInfo{sigHash, string(sig.Serialize()),\n\t\tstring(pubKey.SerializeCompressed())}\n\n\ts.RLock()\n\t_, ok := s.validSigs[info]\n\ts.RUnlock()\n\treturn ok\n}\n\n// Add adds an entry for a signature over 'sigHash' under public key 'pubKey'\n// to the signature cache. In the event that the SigCache is 'full', an\n// existing entry is randomly chosen to be evicted in order to make space for\n// the new entry.\n//\n// NOTE: This function is safe for concurrent access. Writers will block\n// simultaneous readers until function execution has concluded.\nfunc (s *SigCache) Add(sigHash wire.ShaHash, sig *btcec.Signature, pubKey *btcec.PublicKey) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.maxEntries <= 0 {\n\t\treturn\n\t}\n\n\t// If adding this new entry will put us over the max number of allowed\n\t// entries, then evict an entry.\n\tif uint(len(s.validSigs)+1) > s.maxEntries {\n\t\t// Generate a cryptographically random hash.\n\t\trandHashBytes := make([]byte, wire.HashSize)\n\t\t_, err := rand.Read(randHashBytes)\n\t\tif err != nil {\n\t\t\t// Failure to read a random hash results in the proposed\n\t\t\t// entry not being added to the cache since we are\n\t\t\t// unable to evict any existing entries.\n\t\t\treturn\n\t\t}\n\n\t\t// Try to find the first entry that is greater than the random\n\t\t// hash. Use the first entry (which is already pseudo random due\n\t\t// to Go's range statement over maps) as a fall back if none of\n\t\t// the hashes in the rejected transactions pool are larger than\n\t\t// the random hash.\n\t\tvar foundEntry sigInfo\n\t\tfor sigEntry := range s.validSigs {\n\t\t\tif foundEntry.sig == \"\" {\n\t\t\t\tfoundEntry = sigEntry\n\t\t\t}\n\t\t\tif bytes.Compare(sigEntry.sigHash.Bytes(), randHashBytes) > 0 {\n\t\t\t\tfoundEntry = sigEntry\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tdelete(s.validSigs, foundEntry)\n\t}\n\n\tinfo := sigInfo{sigHash, string(sig.Serialize()),\n\t\tstring(pubKey.SerializeCompressed())}\n\ts.validSigs[info] = struct{}{}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":980,"cells":{"blob_id":{"kind":"string","value":"99deb9dd1a9abd3994470325066b096f1a218005"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"nju04zq/pegasus"},"path":{"kind":"string","value":"/src/pegasus/cfgagent/meta.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1146,"string":"1,146"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"net/http\"\n\t\"pegasus/log\"\n\t\"pegasus/server\"\n\t\"pegasus/util\"\n\t\"sync\"\n)\n\ntype meta struct {\n\tmutex sync.Mutex\n\tmasterAddr string\n}\n\nvar cfgmeta = meta{}\n\nfunc registerMaster(addr string) (err error) {\n\tlog.Info(\"Handle register master request as %s\", addr)\n\tcfgmeta.mutex.Lock()\n\tdefer func() {\n\t\tcfgmeta.mutex.Unlock()\n\t\tif err == nil {\n\t\t\tlog.Info(\"Register master as %s\", addr)\n\t\t}\n\t}()\n\t// TODO comment out for test convenience\n\t//if cfgmeta.masterAddr != \"\" {\n\t//\terr = fmt.Errorf(\"Master already registered as %s\", cfgmeta.masterAddr)\n\t//\treturn\n\t//}\n\tcfgmeta.masterAddr = addr\n\treturn\n}\n\nfunc getMasterAddr() (addr string) {\n\tcfgmeta.mutex.Lock()\n\tdefer func() {\n\t\tcfgmeta.mutex.Unlock()\n\t\tlog.Info(\"Get master addr as %s\", addr)\n\t}()\n\taddr = cfgmeta.masterAddr\n\treturn\n}\n\nfunc getMasterAddrHandler(w http.ResponseWriter, r *http.Request) {\n\tserver.FmtResp(w, nil, getMasterAddr())\n}\n\nfunc postMasterHandler(w http.ResponseWriter, r *http.Request) {\n\taddr, err := util.HttpReadRequestTextBody(r)\n\tif err != nil {\n\t\tserver.FmtResp(w, err, \"\")\n\t\treturn\n\t}\n\terr = registerMaster(addr)\n\tserver.FmtResp(w, err, \"\")\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":981,"cells":{"blob_id":{"kind":"string","value":"60b67d7b715ad6a42d1831db6d9a7aaf2618b73d"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"fr34k8/hmgo"},"path":{"kind":"string","value":"/internal/hm/thermal/weatherevent.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1924,"string":"1,924"},"score":{"kind":"number","value":2.78125,"string":"2.78125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package thermal\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html/template\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n)\n\nvar (\n\tweatherEventTemperature = prometheus.NewGaugeVec(\n\t\tprometheus.GaugeOpts{\n\t\t\tNamespace: prometheusNamespace,\n\t\t\tName: \"WeatherEventTemperature\",\n\t\t\tHelp: \"Temperature in degC\",\n\t\t},\n\t\t[]string{\"address\", \"name\"})\n\n\tweatherEventHumidity = prometheus.NewGaugeVec(\n\t\tprometheus.GaugeOpts{\n\t\t\tNamespace: prometheusNamespace,\n\t\t\tName: \"WeatherEventHumidity\",\n\t\t\tHelp: \"Humidity in percentage points\",\n\t\t},\n\t\t[]string{\"address\", \"name\"})\n)\n\nfunc init() {\n\tprometheus.MustRegister(weatherEventTemperature)\n\tprometheus.MustRegister(weatherEventHumidity)\n}\n\ntype WeatherEvent struct {\n\tTemperature float64 // in degC\n\tHumidity uint64 // in percentage points\n}\n\nvar weTmpl = template.Must(template.New(\"weatherevent\").Parse(`\nWeather:
\nTemperature: {{ .Temperature }} ℃
\nHumidity: {{ .Humidity }}%
\n`))\n\nfunc (we *WeatherEvent) HTML() template.HTML {\n\tvar buf bytes.Buffer\n\tif err := weTmpl.Execute(&buf, we); err != nil {\n\t\treturn template.HTML(template.HTMLEscapeString(err.Error()))\n\t}\n\treturn template.HTML(buf.String())\n}\n\nfunc (tc *ThermalControl) DecodeWeatherEvent(payload []byte) (*WeatherEvent, error) {\n\t// c.f. in rftypes/tc.xml\n\tif got, want := len(payload), 3; got != want {\n\t\treturn nil, fmt.Errorf(\"unexpected payload size: got %d, want %d\", got, want)\n\t}\n\twe := &WeatherEvent{\n\t\tTemperature: float64((int16(payload[0])<<8|int16(payload[1]))&0x3FFF) / 10,\n\t\tHumidity: uint64(payload[2]),\n\t}\n\n\tweatherEventTemperature.With(prometheus.Labels{\"name\": tc.Name(), \"address\": tc.AddrHex()}).Set(we.Temperature)\n\tweatherEventHumidity.With(prometheus.Labels{\"name\": tc.Name(), \"address\": tc.AddrHex()}).Set(float64(we.Humidity))\n\n\ttc.latestMu.Lock()\n\tdefer tc.latestMu.Unlock()\n\ttc.latestWeatherEvent = we\n\treturn we, nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":982,"cells":{"blob_id":{"kind":"string","value":"7962f1bd173205e2eac0ec53ddffd06b6b36e59a"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"tmacbg/ask-gamblers-go-api"},"path":{"kind":"string","value":"/platform/data/data.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1968,"string":"1,968"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package data\n\nimport (\n\t\"database/sql\"\n\t\"fmt\"\n)\n\ntype Feed struct {\n\tDB *sql.DB\n}\n\ntype Item struct {\n\tName string `json:\"name\"`\n}\n\nfunc (feed *Feed) GetCountries() []Item {\n\titems := []Item{}\n\n\trows, _ := feed.DB.Query(\"SELECT name from countries\")\n\tvar country string\n\tfor rows.Next() {\n\t\trows.Scan(&country)\n\t\titem := Item{\n\t\t\tName: country,\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\treturn items\n}\n\nfunc (feed *Feed) GetCasinos() []Item {\n\tallCasinos := []Item{}\n\trows, _ := feed.DB.Query(\"Select DISTINCT(name) from websites\")\n\tvar casino string\n\tfor rows.Next() {\n\t\trows.Scan(&casino)\n\t\tcasinoItem := Item{\n\t\t\tName: casino,\n\t\t}\n\n\t\tallCasinos = append(allCasinos, casinoItem)\n\t}\n\n\treturn allCasinos\n}\n\nfunc (feed *Feed) Get(query string) []Item {\n\titems := []Item{}\n\tstm, _ := feed.DB.Prepare(`SELECT DISTINCT(w.name) from websites as w \n\t\t\t\t\t\t\t\tJOIN websites_countries as w_c on w_c.website_id = w.id \n\t\t\t\t\t\t\t\tJOIN countries as c on w_c.country_id = c.id\n\t\t\t\t\t\t\t\twhere c.name = ? `)\n\trows, _ := stm.Query(query)\n\tvar website string\n\tfor rows.Next() {\n\t\trows.Scan(&website)\n\t\titem := Item{\n\t\t\tName: website,\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\treturn items\n}\n\nfunc (feed *Feed) GetBlockedCountries(query string) []Item {\n\titems := []Item{}\n\tstm, _ := feed.DB.Prepare(`SELECT DISTINCT(lower(c.code) ) as code from websites as w \n\t\t\t\t\t\t\t\tJOIN websites_countries as w_c on w_c.website_id = w.id \n\t\t\t\t\t\t\t\tJOIN countries as c on w_c.country_id = c.id\n\t\t\t\t\t\t\t\twhere w.name like ?`)\n\tqueryString := fmt.Sprintf(\"%s%%\", query)\n\tfmt.Print(queryString)\n\trows, err := stm.Query(queryString)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t}\n\tvar countryCode string\n\tfor rows.Next() {\n\t\trows.Scan(&countryCode)\n\t\titem := Item{\n\t\t\tName: countryCode,\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\treturn items\n}\n\nfunc NewConnection(db *sql.DB) *Feed {\n\tstm, _ := db.Prepare(\"CREATE TABLE IF NOT EXISTS countries ( id integer PRIMARY KEY, name text);\")\n\n\tstm.Exec()\n\n\treturn &Feed{\n\t\tDB: db,\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":983,"cells":{"blob_id":{"kind":"string","value":"2fae87e56dea5cb05ef926970ca3a5b671fb9483"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"mazzegi/wasa"},"path":{"kind":"string","value":"/example/todomvc/app/app.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1213,"string":"1,213"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package app\n\nimport (\n\t\"github.com/mazzegi/wasa\"\n\t\"github.com/mazzegi/wasa/example/todomvc/backend\"\n\t\"github.com/mazzegi/wasa/wlog\"\n)\n\ntype App struct {\n\troot *wasa.Elt\n\tdoc *wasa.Document\n\tbackend *backend.Backend\n\theader *Header\n\tmain *Main\n\tfooter *Footer\n}\n\nfunc New(be *backend.Backend) (*App, error) {\n\tdoc, err := wasa.NewDocument(\"WASA / TodoMVC\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta := &App{\n\t\troot: wasa.NewElt(\"section\", wasa.Class(\"todoapp\")),\n\t\tdoc: doc,\n\t\tbackend: be,\n\t}\n\ta.backend.Subscribe(func() {\n\t\ta.render()\n\t})\n\n\tapi := doc.GetGlobal(\"wasaenv\", \"api\").String()\n\twlog.Infof(\"api=(%s)\", api)\n\tloc := doc.Location()\n\twlog.Infof(\"loc=(%s)\", loc)\n\n\ta.setupUI()\n\ta.render()\n\treturn a, nil\n}\n\nfunc (a *App) Run() {\n\twlog.Infof(\"app: run ...\")\n\ta.doc.Run(a.root)\n\twlog.Infof(\"app: run ... done\")\n}\n\nfunc (a *App) setupUI() {\n\ta.header = NewHeader(a.doc, a.backend)\n\ta.main = NewMain(a.doc, a.backend)\n\ta.footer = NewFooter(a.doc, a.backend)\n\ta.root.Append(a.header.Elt(), a.main.Elt(), a.footer.Elt())\n}\n\nfunc (a *App) render() {\n\twlog.Infof(\"app: render ...\")\n\ta.header.render()\n\ta.main.render()\n\ta.footer.render()\n\ta.root.Invalidate()\n\twlog.Infof(\"app: render ... done\")\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":984,"cells":{"blob_id":{"kind":"string","value":"1022351d34fb8428d01d3ac6bfdd324837a2fa6f"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"logic-building/functional-go"},"path":{"kind":"string","value":"/internal/template/dropwhile.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1008,"string":"1,008"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package template\n\n// DropWhile is template to generate function(DropWhhile) for user defined data type\nfunc DropWhile() string {\n\treturn `\nfunc DropWhile(f func() bool, list []) [] {\n\tif f == nil {\n\t\treturn []{}\n\t}\n\tvar newList []\n\tfor i, v := range list {\n\t\tif !f(v) {\n\t\t\tlistLen := len(list)\n\t\t\tnewList = make([], listLen-i)\n\t\t\tj := 0\n\t\t\tfor i < listLen {\n\t\t\t\tnewList[j] = list[i]\n\t\t\t\ti++\n\t\t\t\tj++\n\t\t\t}\n\t\t\treturn newList\n\t\t}\n\t}\n\treturn newList\n}\n`\n}\n\n// DropWhilePtr is template to generate function(DropWhhile) for user defined data type\nfunc DropWhilePtr() string {\n\treturn `\nfunc DropWhilePtr(f func(*) bool, list []*) []* {\n\tif f == nil {\n\t\treturn []*{}\n\t}\n\tvar newList []*\n\tfor i, v := range list {\n\t\tif !f(v) {\n\t\t\tlistLen := len(list)\n\t\t\tnewList = make([]*, listLen-i)\n\t\t\tj := 0\n\t\t\tfor i < listLen {\n\t\t\t\tnewList[j] = list[i]\n\t\t\t\ti++\n\t\t\t\tj++\n\t\t\t}\n\t\t\treturn newList\n\t\t}\n\t}\n\treturn newList\n}\n`\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":985,"cells":{"blob_id":{"kind":"string","value":"fc7190015e88744246fa4802c5f4eb65c2ba385b"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"robertpknight/knightlygo"},"path":{"kind":"string","value":"/GolangToddMcLeod/Exercises/ninja_level6/exercise9/Exercise9.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":580,"string":"580"},"score":{"kind":"number","value":4.0625,"string":"4.0625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package exercise9\n\nimport (\n\t\"fmt\"\n\n\t\"strings\"\n)\n\n// Exercise9 ... code for ninja level 6 exercise 9\nfunc Exercise9() {\n\tfmt.Println(\"\\nExercise 9:\")\n\tg := greeting(\"Rob\")\n\tfmt.Println(g)\n\n\tfmt.Println(\"Using shout function to shout a word returning func:\")\n\tfmt.Println(shout(greeting, \"Rob\"))\n\tfmt.Println(shout(swear, \"Rob\"))\n}\n\nfunc greeting(person string) string {\n\treturn \"Hello, \" + person\n}\n\nfunc swear(person string) string {\n\treturn \"Screw you, \" + person\n}\n\nfunc shout(words func(string) string, person string) string {\n\tw := words(person)\n\treturn strings.ToUpper(w)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":986,"cells":{"blob_id":{"kind":"string","value":"6a616845d430bb0727f5229947f998016579080e"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"Melenium2/inhumanCocain"},"path":{"kind":"string","value":"/auth/logic/grpc_transport_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2063,"string":"2,063"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package auth\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/BurntSushi/toml\"\n\t\"github.com/go-kit/kit/log\"\n\tpbs \"github.com/inhumanLightBackend/auth/pb\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar (\n\tnewConfig = func() (*Config, error) {\n\t\tvar configPath string = \"_config.toml\"\n\t\tconfig := NewConfig()\n\t\t_, err := toml.DecodeFile(configPath, config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn config, nil\n\t}\n)\n\nfunc TestGRPCGenerateShouldReturnNewTokenFromGivenRequest(t *testing.T) {\n\tconfig, err := newConfig()\n\tassert.NoError(t, err)\n\tep := NewEndpoints(NewService(config))\n\t\n\ttr := NewGRPCServer(ep, log.NewNopLogger())\n\treq := &pbs.GenerateRequest{\n\t\tUserId: 1,\n\t\tRole: \"admin\",\n\t}\n\tr, err := tr.Generate(context.Background(), req)\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, r.Token)\n}\n\nfunc TestGRPCGenerateShouldReturnNewTokenFromEmptyRequest(t *testing.T) {\n\tconfig, err := newConfig()\n\tassert.NoError(t, err)\n\tep := NewEndpoints(NewService(config))\n\t\n\ttr := NewGRPCServer(ep, log.NewNopLogger())\n\treq := &pbs.GenerateRequest{}\n\tr, err := tr.Generate(context.Background(), req)\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, r.Token)\n}\n\nfunc TestGRPCValidateShouldReturnClaimsFromGivenToken(t *testing.T) {\n\tconfig, err := newConfig()\n\tassert.NoError(t, err)\n\tep := NewEndpoints(NewService(config))\n\t\n\ttr := NewGRPCServer(ep, log.NewNopLogger())\n\treq := &pbs.GenerateRequest{\n\t\tUserId: 1,\n\t\tRole: \"admin\",\n\t}\n\tr, err := tr.Generate(context.Background(), req)\n\tassert.NoError(t, err)\n\ttoken := r.Token\n\tclaims, err := tr.Validate(context.Background(), &pbs.ValidateRequest{Token: token})\n\tassert.NoError(t, err)\n\tassert.Equal(t, claims.UserId, int32(1))\n\tassert.Equal(t, claims.Role, \"admin\")\n}\n\nfunc TestGRPCValidateShouldReturnErrorFromEmptyRequest(t *testing.T) {\n\tconfig, err := newConfig()\n\tassert.NoError(t, err)\n\tep := NewEndpoints(NewService(config))\n\t\n\ttr := NewGRPCServer(ep, log.NewNopLogger())\n\tclaims, err := tr.Validate(context.Background(), &pbs.ValidateRequest{})\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"Empty token\", claims.Err)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":987,"cells":{"blob_id":{"kind":"string","value":"f3a90607b9e9bb8365a7cd5e8f1aedfd2ff5e6ea"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"mbrt/gmailctl"},"path":{"kind":"string","value":"/cmd/gmailctl-config-migrate/v1alpha1/config_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1146,"string":"1,146"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package v1alpha1\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"gopkg.in/yaml.v3\"\n)\n\nfunc TestParse(t *testing.T) {\n\tyml := []byte(`\nversion: v1alpha1\nauthor:\n name: MB\n email: m@gmail.com\nrules:\n - filters:\n list:\n - foobar@g.com\n actions:\n labels:\n - MyList\n archive: true\n`)\n\tvar res Config\n\tdec := yaml.NewDecoder(bytes.NewBuffer(yml))\n\tdec.KnownFields(true)\n\tassert.NoError(t, dec.Decode(&res))\n\tfilters := Filters{\n\t\tCompositeFilters: CompositeFilters{\n\t\t\tMatchFilters: MatchFilters{\n\t\t\t\tList: []string{\"foobar@g.com\"},\n\t\t\t},\n\t\t},\n\t}\n\texpected := Config{\n\t\tVersion: \"v1alpha1\",\n\t\tAuthor: Author{Name: \"MB\", Email: \"m@gmail.com\"},\n\t\tRules: []Rule{\n\t\t\t{\n\t\t\t\tFilters: filters,\n\t\t\t\tActions: Actions{\n\t\t\t\t\tLabels: []string{\"MyList\"},\n\t\t\t\t\tArchive: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tassert.Equal(t, expected, res)\n}\n\nfunc TestParseUnknownField(t *testing.T) {\n\tyml := []byte(`\nversion: v1alpha1\nauthor:\n name: MB\n email: m@gmail.com\nrules:\n - filters:\n foobar:\n - foobar@g.com\n`)\n\tvar res Config\n\tdec := yaml.NewDecoder(bytes.NewBuffer(yml))\n\tdec.KnownFields(true)\n\tassert.NotNil(t, dec.Decode(&res))\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":988,"cells":{"blob_id":{"kind":"string","value":"f6eff0f106251d910ce56142342faf38295d24e8"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"sp-mario-quesada/hpack"},"path":{"kind":"string","value":"/type_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1084,"string":"1,084"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package hpack\n\nimport (\n\tassert \"github.com/Jxck/assertion\"\n\t\"testing\"\n)\n\nfunc TestNewIndexedHeader(t *testing.T) {\n\tvar index uint32 = 10\n\tvar frame *IndexedHeader\n\tframe = NewIndexedHeader(index)\n\n\tactual, expected := frame.Index, index\n\tassert.Equal(t, actual, expected)\n}\n\nfunc TestNewIndexedLiteral(t *testing.T) {\n\tvar indexing Indexing = WITH\n\tvar index uint32 = 10\n\tvar value string = \"var\"\n\tvar frame *IndexedLiteral = NewIndexedLiteral(indexing, index, value)\n\n\tassert.Equal(t, frame.Indexing, indexing)\n\tassert.Equal(t, frame.Index, index)\n\tassert.Equal(t, frame.ValueLength, uint32(len(value)))\n\tassert.Equal(t, frame.ValueString, value)\n}\n\nfunc TestNewStringLiteral(t *testing.T) {\n\tvar indexing Indexing = WITH\n\tvar name string = \"foo\"\n\tvar value string = \"var\"\n\tvar frame *StringLiteral = NewStringLiteral(indexing, name, value)\n\n\tassert.Equal(t, frame.Indexing, indexing)\n\tassert.Equal(t, frame.NameLength, uint32(len(name)))\n\tassert.Equal(t, frame.NameString, name)\n\tassert.Equal(t, frame.ValueLength, uint32(len(value)))\n\tassert.Equal(t, frame.ValueString, value)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":989,"cells":{"blob_id":{"kind":"string","value":"c5cf8a84ef5c15c3b9b35535733dbbb1dccc59d8"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"westonZhang/rank_util_api"},"path":{"kind":"string","value":"/services/keyword_include_extractor_service/sogou_pc.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1131,"string":"1,131"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package keyword_include_extractor_service\n\nimport (\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"gitlab.fxt.cn/fxt/rank-util/structs/include_extractor\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc KeywordIncludeExtractorSogouPc(req *include_extractor.IncludeExtractorRequest) (*include_extractor.KeywordIncludeExtractorResponse, error) {\n\tincludeExtractorResponse := &include_extractor.KeywordIncludeExtractorResponse{}\n\tre := regexp.MustCompile(`站内没有找到能和.*?匹配的内容。`)\n\tsubMatch := re.FindStringSubmatch(req.Body)\n\tif len(subMatch) != 0 {\n\t\treturn includeExtractorResponse, nil\n\t}\n\n\tdom, err := goquery.NewDocumentFromReader(strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdom.Find(\"div.results>div h3.pt a\").EachWithBreak(func(i int, selection *goquery.Selection) bool {\n\t\tif i == 0 {\n\t\t\tselectionHtml, err := selection.Html()\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tre := regexp.MustCompile(`.*?`)\n\t\t\tsubMatch := re.FindStringSubmatch(selectionHtml)\n\t\t\tif len(subMatch) != 0 {\n\t\t\t\tincludeExtractorResponse.IsIncluded = true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n\n\treturn includeExtractorResponse, nil\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":990,"cells":{"blob_id":{"kind":"string","value":"bc1dacce9e1a51327c5901c73ed96251e2bf1ed5"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"andywijaya260286/golangudemy"},"path":{"kind":"string","value":"/013-exercise-ninja-level-2/exercise-2-1.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":144,"string":"144"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\t//Program to print number in decimal, binary, hex\n\tx := 10\n\n\tfmt.Printf(\"%d,%b,%#x\", x, x, x)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":991,"cells":{"blob_id":{"kind":"string","value":"6718c1eb9de41473759b904b55394caacf8958c9"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"jonhadfield/gosn-v2"},"path":{"kind":"string","value":"/component.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7599,"string":"7,599"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package gosn\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc parseComponent(i DecryptedItem) Item {\n\tc := Component{}\n\tc.UUID = i.UUID\n\tc.ItemsKeyID = i.ItemsKeyID\n\tc.ContentType = i.ContentType\n\tc.Deleted = i.Deleted\n\tc.UpdatedAt = i.UpdatedAt\n\tc.UpdatedAtTimestamp = i.UpdatedAtTimestamp\n\tc.CreatedAtTimestamp = i.CreatedAtTimestamp\n\tc.CreatedAt = i.CreatedAt\n\tc.ContentSize = len(i.Content)\n\n\tvar err error\n\n\tif !c.Deleted {\n\t\tvar content Content\n\n\t\tcontent, err = processContentModel(i.ContentType, i.Content)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tc.Content = *content.(*ComponentContent)\n\t}\n\n\tvar cAt, uAt time.Time\n\n\tcAt, err = parseSNTime(i.CreatedAt)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.CreatedAt = cAt.Format(timeLayout)\n\n\tuAt, err = parseSNTime(i.UpdatedAt)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.UpdatedAt = uAt.Format(timeLayout)\n\n\treturn &c\n}\n\ntype ComponentContent struct {\n\tIdentifier string `json:\"identifier\"`\n\tLegacyURL string `json:\"legacy_url\"`\n\tHostedURL string `json:\"hosted_url\"`\n\tLocalURL string `json:\"local_url\"`\n\tURL string `json:\"url\"`\n\tValidUntil string `json:\"valid_until\"`\n\tOfflineOnly bool `json:\"offlineOnly\"`\n\tName string `json:\"name\"`\n\tArea string `json:\"area\"`\n\tPackageInfo interface{} `json:\"package_info\"`\n\tPermissions interface{} `json:\"permissions\"`\n\tActive interface{} `json:\"active\"`\n\tAutoUpdateDisabled string `json:\"autoupdateDisabled\"`\n\tComponentData interface{} `json:\"componentData\"`\n\tDissociatedItemIds []string `json:\"disassociatedItemIds\"`\n\tAssociatedItemIds []string `json:\"associatedItemIds\"`\n\tItemReferences ItemReferences `json:\"references\"`\n\tAppData AppDataContent `json:\"appData\"`\n}\n\ntype Component struct {\n\tItemCommon\n\tContent ComponentContent\n}\n\nfunc (c Component) IsDefault() bool {\n\treturn false\n}\n\nfunc (i Items) Components() (c Components) {\n\tfor _, x := range i {\n\t\tif x.GetContentType() == \"SN|Component\" {\n\t\t\tcomponent := x.(*Component)\n\t\t\tc = append(c, *component)\n\t\t}\n\t}\n\n\treturn c\n}\n\nfunc (c *Components) DeDupe() {\n\tvar encountered []string\n\n\tvar deDuped Components\n\n\tfor _, i := range *c {\n\t\tif !stringInSlice(i.UUID, encountered, true) {\n\t\t\tdeDuped = append(deDuped, i)\n\t\t}\n\n\t\tencountered = append(encountered, i.UUID)\n\t}\n\n\t*c = deDuped\n}\n\n// NewComponent returns an Item of type Component without content.\nfunc NewComponent() Component {\n\tnow := time.Now().UTC().Format(timeLayout)\n\n\tvar c Component\n\n\tc.ContentType = \"SN|Component\"\n\tc.CreatedAtTimestamp = time.Now().UTC().UnixMicro()\n\tc.CreatedAt = now\n\tc.UUID = GenUUID()\n\n\treturn c\n}\n\n// NewComponentContent returns an empty Tag content instance.\nfunc NewComponentContent() *ComponentContent {\n\tc := &ComponentContent{}\n\tc.SetUpdateTime(time.Now().UTC())\n\n\treturn c\n}\n\ntype Components []Component\n\nfunc (c Components) Validate() error {\n\tvar updatedTime time.Time\n\n\tvar err error\n\n\tfor _, item := range c {\n\t\t// validate content if being added\n\t\tif !item.Deleted {\n\t\t\tupdatedTime, err = item.Content.GetUpdateTime()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase item.Content.Name == \"\":\n\t\t\t\terr = fmt.Errorf(\"failed to create \\\"%s\\\" due to missing title: \\\"%s\\\"\",\n\t\t\t\t\titem.ContentType, item.UUID)\n\t\t\tcase updatedTime.IsZero():\n\t\t\t\terr = fmt.Errorf(\"failed to create \\\"%s\\\" due to missing content updated time: \\\"%s\\\"\",\n\t\t\t\t\titem.ContentType, item.Content.GetTitle())\n\t\t\tcase item.CreatedAt == \"\":\n\t\t\t\terr = fmt.Errorf(\"failed to create \\\"%s\\\" due to missing created at date: \\\"%s\\\"\",\n\t\t\t\t\titem.ContentType, item.Content.GetTitle())\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (c Component) IsDeleted() bool {\n\treturn c.Deleted\n}\n\nfunc (c *Component) SetDeleted(d bool) {\n\tc.Deleted = d\n}\n\nfunc (c Component) GetContent() Content {\n\treturn &c.Content\n}\n\nfunc (c *Component) SetContent(cc Content) {\n\tc.Content = *cc.(*ComponentContent)\n}\n\nfunc (c Component) GetItemsKeyID() string {\n\treturn c.ItemsKeyID\n}\n\nfunc (c Component) GetUUID() string {\n\treturn c.UUID\n}\n\nfunc (c *Component) SetUUID(u string) {\n\tc.UUID = u\n}\n\nfunc (c Component) GetContentType() string {\n\treturn c.ContentType\n}\n\nfunc (c Component) GetCreatedAt() string {\n\treturn c.CreatedAt\n}\n\nfunc (c *Component) SetCreatedAt(ca string) {\n\tc.CreatedAt = ca\n}\n\nfunc (c Component) GetUpdatedAt() string {\n\treturn c.UpdatedAt\n}\n\nfunc (c *Component) SetUpdatedAt(ca string) {\n\tc.UpdatedAt = ca\n}\n\nfunc (c Component) GetCreatedAtTimestamp() int64 {\n\treturn c.CreatedAtTimestamp\n}\n\nfunc (c *Component) SetCreatedAtTimestamp(ca int64) {\n\tc.CreatedAtTimestamp = ca\n}\n\nfunc (c Component) GetUpdatedAtTimestamp() int64 {\n\treturn c.UpdatedAtTimestamp\n}\n\nfunc (c *Component) SetUpdatedAtTimestamp(ca int64) {\n\tc.UpdatedAtTimestamp = ca\n}\n\nfunc (c *Component) SetContentType(ct string) {\n\tc.ContentType = ct\n}\n\nfunc (c Component) GetContentSize() int {\n\treturn c.ContentSize\n}\n\nfunc (c *Component) SetContentSize(s int) {\n\tc.ContentSize = s\n}\n\nfunc (cc *ComponentContent) AssociateItems(newItems []string) {\n\t// add to associated item ids\n\tfor _, newRef := range newItems {\n\t\tvar existingFound bool\n\n\t\tvar existingDFound bool\n\n\t\tfor _, existingRef := range cc.AssociatedItemIds {\n\t\t\tif existingRef == newRef {\n\t\t\t\texistingFound = true\n\t\t\t}\n\t\t}\n\n\t\tfor _, existingDRef := range cc.DissociatedItemIds {\n\t\t\tif existingDRef == newRef {\n\t\t\t\texistingDFound = true\n\t\t\t}\n\t\t}\n\n\t\t// add reference if it doesn't exist\n\t\tif !existingFound {\n\t\t\tcc.AssociatedItemIds = append(cc.AssociatedItemIds, newRef)\n\t\t}\n\n\t\t// remove reference (from disassociated) if it does exist in that list\n\t\tif existingDFound {\n\t\t\tcc.DissociatedItemIds = removeStringFromSlice(newRef, cc.DissociatedItemIds)\n\t\t}\n\t}\n}\n\nfunc (cc *ComponentContent) GetItemAssociations() []string {\n\treturn cc.AssociatedItemIds\n}\n\nfunc (cc *ComponentContent) GetItemDisassociations() []string {\n\treturn cc.DissociatedItemIds\n}\n\nfunc (cc *ComponentContent) DisassociateItems(itemsToRemove []string) {\n\t// remove from associated item ids\n\tfor _, delRef := range itemsToRemove {\n\t\tvar existingFound bool\n\n\t\tfor _, existingRef := range cc.AssociatedItemIds {\n\t\t\tif existingRef == delRef {\n\t\t\t\texistingFound = true\n\t\t\t}\n\t\t}\n\n\t\t// remove reference (from disassociated) if it does exist in that list\n\t\tif existingFound {\n\t\t\tcc.AssociatedItemIds = removeStringFromSlice(delRef, cc.AssociatedItemIds)\n\t\t}\n\t}\n}\n\nfunc (cc *ComponentContent) GetUpdateTime() (time.Time, error) {\n\tif cc.AppData.OrgStandardNotesSN.ClientUpdatedAt == \"\" {\n\t\treturn time.Time{}, fmt.Errorf(\"ClientUpdatedAt not set\")\n\t}\n\n\treturn time.Parse(timeLayout, cc.AppData.OrgStandardNotesSN.ClientUpdatedAt)\n}\n\nfunc (cc *ComponentContent) SetUpdateTime(uTime time.Time) {\n\tcc.AppData.OrgStandardNotesSN.ClientUpdatedAt = uTime.Format(timeLayout)\n}\n\nfunc (cc ComponentContent) GetTitle() string {\n\treturn \"\"\n}\n\nfunc (cc *ComponentContent) GetName() string {\n\treturn cc.Name\n}\n\nfunc (cc *ComponentContent) GetActive() bool {\n\treturn cc.Active.(bool)\n}\n\nfunc (cc *ComponentContent) SetTitle(title string) {\n}\n\nfunc (cc *ComponentContent) GetAppData() AppDataContent {\n\treturn cc.AppData\n}\n\nfunc (cc *ComponentContent) SetAppData(data AppDataContent) {\n\tcc.AppData = data\n}\n\nfunc (cc ComponentContent) References() ItemReferences {\n\treturn cc.ItemReferences\n}\n\nfunc (cc *ComponentContent) UpsertReferences(input ItemReferences) {\n\tpanic(\"implement me\")\n}\n\nfunc (cc *ComponentContent) SetReferences(input ItemReferences) {\n\tcc.ItemReferences = input\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":992,"cells":{"blob_id":{"kind":"string","value":"4d6b68da7f622b0a798c1fc38c51efe1b5158608"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"jcdny/goeuler"},"path":{"kind":"string","value":"/prob079_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1149,"string":"1,149"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package euler\n\nimport (\n\t\"log\"\n\t\"testing\"\n)\n\nfunc prob079() int {\n\t// I did this one by hand \n\t// sort -u < keylog.txt gives:\n\tkeys := []int{\n\t\t129, 160, 162, 168, 180, 289, 290,\n\t\t316, 318, 319, 362, 368, 380, 389,\n\t\t620, 629, 680, 689, 690, 710, 716,\n\t\t718, 719, 720, 728, 729, 731, 736,\n\t\t760, 762, 769, 790, 890}\n\t// Make a table per digit like so\n\t// before:D:after\n\t// 9876321 0\n\t// 73 1 02689\n\t// 7631 2 089\n\t// 7 3 012689\n\t// 731 6 289\n\t// 7 0123689\n\t// 76321 8 09\n\t// 876321 9 0\n\t//\n\t// from the above you can see 7 is the first digit removing 7 from\n\t// before all digits leaves 3 as the second digit and similiarly\n\t// removing 3 leaves 1 etc.\n\t//\n\t// once you have placed all the digits you end up with \n\t// 73162890.\n\t//\n\t// going back to the original keylog data you can see all the\n\t// triples are satisfied by this sequence and each digit occurs\n\t// once so it is a minimal length sequence.\n\tif false {\n\t\tlog.Print(keys)\n\t}\n\treturn 73162890\n}\n\nfunc TestProb079(t *testing.T) {\n\tout := prob079()\n\tValidate(t, 79, out)\n}\n\nfunc BenchmarkProb079(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tprob079()\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":993,"cells":{"blob_id":{"kind":"string","value":"9badad4c8f3757872f4997b40767293e87ad19af"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"logonmy/go-study"},"path":{"kind":"string","value":"/main/cal/deque_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3020,"string":"3,020"},"score":{"kind":"number","value":3.75,"string":"3.75"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package cal_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n// 链表的一个节点\ntype ListNode struct {\n\tprev *ListNode // 前一个节点\n\tnext *ListNode // 后一个节点\n\tvalue interface{} // 数据\n}\n\n// 创建一个节点\nfunc NewListNode(value interface{}) (listNode *ListNode) {\n\tlistNode = &ListNode{\n\t\tvalue: value,\n\t}\n\n\treturn\n}\n\n// 当前节点的前一个节点\nfunc (n *ListNode) Prev() (prev *ListNode) {\n\tprev = n.prev\n\n\treturn\n}\n\n// 当前节点的前一个节点\nfunc (n *ListNode) Next() (next *ListNode) {\n\tnext = n.next\n\n\treturn\n}\n\n// 获取节点的值\nfunc (n *ListNode) GetValue() (value interface{}) {\n\tif n == nil {\n\n\t\treturn\n\t}\n\tvalue = n.value\n\n\treturn\n}\n\n// 链表\ntype List struct {\n\thead *ListNode // 表头节点\n\ttail *ListNode // 表尾节点\n\tlen int // 链表的长度\n}\n\n// 创建一个空链表\nfunc NewList() (list *List) {\n\tlist = &List{}\n\treturn\n}\n\n// 返回链表头节点\nfunc (l *List) Head() (head *ListNode) {\n\thead = l.head\n\n\treturn\n}\n\n// 返回链表尾节点\nfunc (l *List) Tail() (tail *ListNode) {\n\ttail = l.tail\n\n\treturn\n}\n\n// 返回链表长度\nfunc (l *List) Len() (len int) {\n\tlen = l.len\n\n\treturn\n}\n\n// 在链表的右边插入一个元素\nfunc (l *List) RPush(value interface{}) {\n\n\tnode := NewListNode(value)\n\n\t// 链表未空的时候\n\tif l.Len() == 0 {\n\t\tl.head = node\n\t\tl.tail = node\n\t} else {\n\t\ttail := l.tail\n\t\ttail.next = node\n\t\tnode.prev = tail\n\n\t\tl.tail = node\n\t}\n\n\tl.len = l.len + 1\n\n\treturn\n}\n\n// 从链表左边取出一个节点\nfunc (l *List) LPop() (node *ListNode) {\n\n\t// 数据为空\n\tif l.len == 0 {\n\n\t\treturn\n\t}\n\n\tnode = l.head\n\n\tif node.next == nil {\n\t\t// 链表未空\n\t\tl.head = nil\n\t\tl.tail = nil\n\t} else {\n\t\tl.head = node.next\n\t}\n\tl.len = l.len - 1\n\n\treturn\n}\n\n// 从链表右边取出一个节点\nfunc (l *List) RPop() (node *ListNode) {\n\n\t// 数据为空\n\tif l.len == 0 {\n\n\t\treturn\n\t}\n\n\tnode = l.tail\n\tl.tail = node.prev\n\t//if node.next == nil {\n\t//\t// 链表未空\n\t//\tl.head = nil\n\t//\tl.tail = nil\n\t//} else {\n\t//\n\t//}\n\tl.len = l.len - 1\n\n\treturn\n}\n\nfunc Test_deque(t *testing.T) {\n\tnums := []int{1, 3, -1, -3, 5, 3, 6, 7}\n\tfmt.Println(maxSlidingWindow(nums, 3))\n}\n\nfunc maxSlidingWindow(nums []int, k int) []int {\n\td := NewList()\n\twindowCnt := len(nums) - k + 1\n\tresult := make([]int, 0, windowCnt)\n\tfor i := 0; i < windowCnt; i++ {\n\n\t\tfor j := 0; j < k; j++ {\n\t\t\tif i == 0 && j == 0 {\n\t\t\t\td.RPush(nums[i])\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmax := nums[i+j]\n\t\t\tfor t := i + j - 1; t >= i; t-- {\n\t\t\t\tif max > nums[t] {\n\t\t\t\t\td.RPop()\n\t\t\t\t\tif t == i {\n\t\t\t\t\t\td.RPush(i + j)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\td.RPush(t + 1)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif d.Head().value.(int) < i {\n\t\t\td.LPop()\n\t\t\tresult = append(result, nums[d.LPop().value.(int)])\n\t\t} else {\n\t\t\tresult = append(result, nums[d.Head().value.(int)])\n\t\t}\n\t}\n\n\treturn result\n}\n\n//func maxSlidingWindow1(nums []int, k int) []int {\n//\td:= NewList()\n//\twindowCnt := len(nums) - k + 1\n//\tresult := make([]int, 0, windowCnt)\n//\tfor i := k; i < len(nums); i ++ {\n//\n//\t}\n//\n//\n//\treturn result\n//}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":994,"cells":{"blob_id":{"kind":"string","value":"0d698d26f06e7f6b1324ddb724e766a9e6fe5c4c"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"offlinehacker/deployment-manager"},"path":{"kind":"string","value":"/util/httpclient_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3840,"string":"3,840"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","LicenseRef-scancode-generic-cla"],"string":"[\n \"Apache-2.0\",\n \"LicenseRef-scancode-generic-cla\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["Apache-2.0","LicenseRef-scancode-generic-cla"],"string":"[\n \"Apache-2.0\",\n \"LicenseRef-scancode-generic-cla\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/*\nCopyright 2015 The Kubernetes Authors All rights reserved.\n\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\n http://www.apache.org/licenses/LICENSE-2.0\n \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\npackage util\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype mockSleeper struct {\n\targs []time.Duration\n}\n\nfunc (m *mockSleeper) Sleep(d time.Duration) {\n\tm.args = append(m.args, d)\n}\n\ntype responseAndError struct {\n\terr error\n\tresp *http.Response\n}\n\ntype testBody struct {\n\tclosed bool\n\tbody io.Reader\n}\n\nfunc (tb *testBody) Read(p []byte) (n int, err error) {\n\treturn tb.body.Read(p)\n}\n\nfunc (tb *testBody) Close() error {\n\ttb.closed = true\n\treturn nil\n}\n\nfunc createResponse(err error, code int, body string, shouldClose bool,\n\theaders map[string]string) responseAndError {\n\thttpBody := testBody{body: strings.NewReader(body), closed: !shouldClose}\n\theader := http.Header{}\n\tfor k, v := range headers {\n\t\theader.Add(k, v)\n\t}\n\thttpResponse := &http.Response{\n\t\tBody: &httpBody,\n\t\tContentLength: int64(len(body)),\n\t\tStatusCode: code,\n\t\tHeader: header,\n\t}\n\treturn responseAndError{err: err, resp: httpResponse}\n}\n\ntype mockDoer struct {\n\tresp []responseAndError\n\tt *testing.T\n\turl string\n\theaders map[string]string\n}\n\nfunc (doer *mockDoer) Do(req *http.Request) (res *http.Response, err error) {\n\tif req.URL.String() != doer.url {\n\t\tdoer.t.Errorf(\"Expected url %s but got url %s\", doer.url, req.URL.String())\n\t}\n\n\tfor k, v := range doer.headers {\n\t\tif req.Header.Get(k) != v {\n\t\t\tdoer.t.Errorf(\"Expected header %s with value %s but found %s\", k, v, req.Header.Get(k))\n\t\t}\n\t}\n\n\tif len(doer.resp) == 0 {\n\t\tdoer.t.Errorf(\"Do method was called more times than expected.\")\n\t}\n\n\tres = doer.resp[0].resp\n\terr = doer.resp[0].err\n\tdoer.resp = doer.resp[1:]\n\treturn\n}\n\nfunc testClientDriver(md mockDoer, ms mockSleeper, expectedErr error, code int,\n\tresult string, t *testing.T) {\n\texpectedCalls := len(md.resp)\n\tclient := NewHTTPClient(uint(expectedCalls)-1, &md, &ms)\n\n\tr, c, e := client.Get(md.url)\n\n\tif expectedCalls-1 != len(ms.args) {\n\t\tt.Errorf(\"Expected %d calls to sleeper but found %d\", expectedCalls-1, len(ms.args))\n\t}\n\n\tif r != result {\n\t\tt.Errorf(\"Expected result %s but received %s\", result, r)\n\t}\n\n\tif c != code {\n\t\tt.Errorf(\"Expected status code %d but received %d\", code, c)\n\t}\n\n\tif e != expectedErr {\n\t\tt.Errorf(\"Expected error %s but received %s\", expectedErr, e)\n\t}\n}\n\nfunc TestGzip(t *testing.T) {\n\tdoer := mockDoer{}\n\tvar b bytes.Buffer\n\tgz := gzip.NewWriter(&b)\n\tgz.Write([]byte(\"Test\"))\n\tgz.Flush()\n\tgz.Close()\n\tresult := b.String()\n\n\tdoer.resp = []responseAndError{\n\t\tcreateResponse(nil, 200, result, true, map[string]string{\"Content-Encoding\": \"gzip\"}),\n\t}\n\n\tsleeper := mockSleeper{}\n\ttestClientDriver(doer, sleeper, nil, 200, \"Test\", t)\n}\n\nfunc TestRetry(t *testing.T) {\n\tdoer := mockDoer{}\n\tdoer.resp = []responseAndError{\n\t\tcreateResponse(nil, 404, \"\", true, map[string]string{}),\n\t\tcreateResponse(nil, 200, \"Test\", true, map[string]string{}),\n\t}\n\n\tsleeper := mockSleeper{}\n\ttestClientDriver(doer, sleeper, nil, 200, \"Test\", t)\n}\n\nfunc TestFail(t *testing.T) {\n\tdoer := mockDoer{}\n\terr := errors.New(\"Error\")\n\tdoer.resp = []responseAndError{\n\t\tcreateResponse(nil, 404, \"\", true, map[string]string{}),\n\t\tcreateResponse(err, 0, \"\", false, map[string]string{}),\n\t}\n\n\tsleeper := mockSleeper{}\n\ttestClientDriver(doer, sleeper, err, 0, \"\", t)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":995,"cells":{"blob_id":{"kind":"string","value":"1d5d8ce568637b9c91cc58bff877995e2795bde4"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"gophergala/echodb"},"path":{"kind":"string","value":"/dbcore/hashtable.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8204,"string":"8,204"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-2-Clause","MIT"],"string":"[\n \"BSD-2-Clause\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["BSD-2-Clause","MIT"],"string":"[\n \"BSD-2-Clause\",\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/*\nHash table file contains binary content; it implements a static hash table made of hash buckets and integer entries.\nEvery bucket has a fixed number of entries. When a bucket becomes full, a new bucket is chained to it in order to store\nmore entries. Every entry has an integer key and value.\nAn entry key may have multiple values assigned to it, however the combination of entry key and value must be unique\nacross the entire hash table.\n*/\n// Taken from tiedot hashtable implementation\npackage dbcore\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n)\n\nconst (\n\tHT_FILE_GROWTH = 32 * 1048576 // Hash table file initial size & file growth\n\tENTRY_SIZE = 1 + 10 + 10 // Hash entry size: validity (single byte), key (int 10 bytes), value (int 10 bytes)\n\tBUCKET_HEADER = 10 // Bucket header size: next chained bucket number (int 10 bytes)\n\tPER_BUCKET = 16 // Entries per bucket\n\tHASH_BITS = 16 // Number of hash key bits\n\tBUCKET_SIZE = BUCKET_HEADER + PER_BUCKET*ENTRY_SIZE // Size of a bucket\n\tINITIAL_BUCKETS = 65536 // Initial number of buckets == 2 ^ HASH_BITS\n)\n\n// Hash table file is a binary file containing buckets of hash entries.\ntype HashTable struct {\n\t*DataFile\n\tnumBuckets int\n\tLock *sync.RWMutex\n}\n\n// Smear the integer entry key and return the portion (first HASH_BITS bytes) used for allocating the entry.\nfunc HashKey(key int) int {\n\t/*\n\t\ttiedot should be compiled/run on x86-64 systems.\n\t\tIf you decide to compile tiedot on 32-bit systems, the following integer-smear algorithm will cause compilation failure\n\t\tdue to 32-bit interger overflow; therefore you must modify the algorithm.\n\t\tDo not remove the integer-smear process, and remember to run test cases to verify your mods.\n\t*/\n\t// ========== Integer-smear start =======\n\tkey = key ^ (key >> 4)\n\tkey = (key ^ 0xdeadbeef) + (key << 5)\n\tkey = key ^ (key >> 11)\n\t// ========== Integer-smear end =========\n\treturn key & ((1 << HASH_BITS) - 1) // Do not modify this line\n}\n\n// Open a hash table file.\nfunc OpenHashTable(path string) (ht *HashTable, err error) {\n\tht = &HashTable{Lock: new(sync.RWMutex)}\n\tif ht.DataFile, err = OpenDataFile(path, HT_FILE_GROWTH); err != nil {\n\t\treturn\n\t}\n\tht.calculateNumBuckets()\n\treturn\n}\n\n// Follow the longest bucket chain to calculate total number of buckets, hence the \"used size\" of hash table file.\nfunc (ht *HashTable) calculateNumBuckets() {\n\tht.numBuckets = ht.Size / BUCKET_SIZE\n\tlargestBucketNum := INITIAL_BUCKETS - 1\n\tfor i := 0; i < INITIAL_BUCKETS; i++ {\n\t\tlastBucket := ht.lastBucket(i)\n\t\tif lastBucket > largestBucketNum && lastBucket < ht.numBuckets {\n\t\t\tlargestBucketNum = lastBucket\n\t\t}\n\t}\n\tht.numBuckets = largestBucketNum + 1\n\tusedSize := ht.numBuckets * BUCKET_SIZE\n\tif usedSize > ht.Size {\n\t\tht.Used = ht.Size\n\t\tht.EnsureSize(usedSize - ht.Used)\n\t}\n\tht.Used = usedSize\n\tfmt.Printf(\"%s: calculated used size is %d\", ht.Path, usedSize)\n}\n\n// Return number of the next chained bucket.\nfunc (ht *HashTable) nextBucket(bucket int) int {\n\tif bucket >= ht.numBuckets {\n\t\treturn 0\n\t}\n\tbucketAddr := bucket * BUCKET_SIZE\n\tnextUint, err := binary.Varint(ht.Buf[bucketAddr : bucketAddr+10])\n\tnext := int(nextUint)\n\tif next == 0 {\n\t\treturn 0\n\t} else if err < 0 || next <= bucket || next >= ht.numBuckets || next < INITIAL_BUCKETS {\n\t\tfmt.Errorf(\"Bad hash table - repair ASAP %s\", ht.Path)\n\t\treturn 0\n\t} else {\n\t\treturn next\n\t}\n}\n\n// Return number of the last bucket in chain.\nfunc (ht *HashTable) lastBucket(bucket int) int {\n\tfor curr := bucket; ; {\n\t\tnext := ht.nextBucket(curr)\n\t\tif next == 0 {\n\t\t\treturn curr\n\t\t}\n\t\tcurr = next\n\t}\n}\n\n// Create and chain a new bucket.\nfunc (ht *HashTable) growBucket(bucket int) {\n\tht.EnsureSize(BUCKET_SIZE)\n\tlastBucketAddr := ht.lastBucket(bucket) * BUCKET_SIZE\n\tbinary.PutVarint(ht.Buf[lastBucketAddr:lastBucketAddr+10], int64(ht.numBuckets))\n\tht.Used += BUCKET_SIZE\n\tht.numBuckets++\n}\n\n// Clear the entire hash table.\nfunc (ht *HashTable) Clear() (err error) {\n\tif err = ht.DataFile.Clear(); err != nil {\n\t\treturn\n\t}\n\tht.calculateNumBuckets()\n\treturn\n}\n\n// Sync Hashtable mmap to file\nfunc (ht *HashTable) Sync() (err error) {\n\tif err = ht.DataFile.Sync(); err != nil {\n\t\treturn\n\t}\n\treturn nil\n}\n\n// Store the entry into a vacant (invalidated or empty) place in the appropriate bucket.\nfunc (ht *HashTable) Put(key, val int) {\n\tfor bucket, entry := HashKey(key), 0; ; {\n\t\tentryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE\n\t\tif ht.Buf[entryAddr] != 1 {\n\t\t\tht.Buf[entryAddr] = 1\n\t\t\tbinary.PutVarint(ht.Buf[entryAddr+1:entryAddr+11], int64(key))\n\t\t\tbinary.PutVarint(ht.Buf[entryAddr+11:entryAddr+21], int64(val))\n\t\t\treturn\n\t\t}\n\t\tif entry++; entry == PER_BUCKET {\n\t\t\tentry = 0\n\t\t\tif bucket = ht.nextBucket(bucket); bucket == 0 {\n\t\t\t\tht.growBucket(HashKey(key))\n\t\t\t\tht.Put(key, val)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Look up values by key.\nfunc (ht *HashTable) Get(key, limit int) (vals []int) {\n\tif limit == 0 {\n\t\tvals = make([]int, 0, 10)\n\t} else {\n\t\tvals = make([]int, 0, limit)\n\t}\n\tfor count, entry, bucket := 0, 0, HashKey(key); ; {\n\t\tentryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE\n\t\tentryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])\n\t\tentryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])\n\t\tif ht.Buf[entryAddr] == 1 {\n\t\t\tif int(entryKey) == key {\n\t\t\t\tvals = append(vals, int(entryVal))\n\t\t\t\tif count++; count == limit {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else if entryKey == 0 && entryVal == 0 {\n\t\t\treturn\n\t\t}\n\t\tif entry++; entry == PER_BUCKET {\n\t\t\tentry = 0\n\t\t\tif bucket = ht.nextBucket(bucket); bucket == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Flag an entry as invalid, so that Get will not return it later on.\nfunc (ht *HashTable) Remove(key, val int) {\n\tfor entry, bucket := 0, HashKey(key); ; {\n\t\tentryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE\n\t\tentryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])\n\t\tentryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])\n\t\tif ht.Buf[entryAddr] == 1 {\n\t\t\tif int(entryKey) == key && int(entryVal) == val {\n\t\t\t\tht.Buf[entryAddr] = 0\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if entryKey == 0 && entryVal == 0 {\n\t\t\treturn\n\t\t}\n\t\tif entry++; entry == PER_BUCKET {\n\t\t\tentry = 0\n\t\t\tif bucket = ht.nextBucket(bucket); bucket == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Divide the entire hash table into roughly equally sized partitions, and return the start/end key range of the chosen partition.\nfunc GetPartitionRange(partNum, totalParts int) (start int, end int) {\n\tperPart := INITIAL_BUCKETS / totalParts\n\tleftOver := INITIAL_BUCKETS % totalParts\n\tstart = partNum * perPart\n\tif leftOver > 0 {\n\t\tif partNum == 0 {\n\t\t\tend += 1\n\t\t} else if partNum < leftOver {\n\t\t\tstart += partNum\n\t\t\tend += 1\n\t\t} else {\n\t\t\tstart += leftOver\n\t\t}\n\t}\n\tend += start + perPart\n\tif partNum == totalParts-1 {\n\t\tend = INITIAL_BUCKETS\n\t}\n\treturn\n}\n\n// Collect entries all the way from \"head\" bucket to the end of its chained buckets.\nfunc (ht *HashTable) collectEntries(head int) (keys, vals []int) {\n\tkeys = make([]int, 0, PER_BUCKET)\n\tvals = make([]int, 0, PER_BUCKET)\n\tvar entry, bucket int = 0, head\n\tfor {\n\t\tentryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE\n\t\tentryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])\n\t\tentryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])\n\t\tif ht.Buf[entryAddr] == 1 {\n\t\t\tkeys = append(keys, int(entryKey))\n\t\t\tvals = append(vals, int(entryVal))\n\t\t} else if entryKey == 0 && entryVal == 0 {\n\t\t\treturn\n\t\t}\n\t\tif entry++; entry == PER_BUCKET {\n\t\t\tentry = 0\n\t\t\tif bucket = ht.nextBucket(bucket); bucket == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Return all entries in the chosen partition.\nfunc (ht *HashTable) GetPartition(partNum, partSize int) (keys, vals []int) {\n\trangeStart, rangeEnd := GetPartitionRange(partNum, partSize)\n\tprealloc := (rangeEnd - rangeStart) * PER_BUCKET\n\tkeys = make([]int, 0, prealloc)\n\tvals = make([]int, 0, prealloc)\n\tfor head := rangeStart; head < rangeEnd; head++ {\n\t\tk, v := ht.collectEntries(head)\n\t\tkeys = append(keys, k...)\n\t\tvals = append(vals, v...)\n\t}\n\treturn\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":996,"cells":{"blob_id":{"kind":"string","value":"33103ea11a8f8a8d194ea755b7c745c91ba86d15"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"patsoffice/aliasman"},"path":{"kind":"string","value":"/internal/cmd/aliascmd/create.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6153,"string":"6,153"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// Copyright © 2020 Patrick Lawrence \n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\npackage aliascmd\n\nimport (\n\t\"crypto/md5\"\n\t\"crypto/rand\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/patsoffice/aliasman/internal/alias\"\n\t\"github.com/patsoffice/aliasman/internal/cmd\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\n// aliasCreateCmd represents the create command\nvar (\n\taliasCreateCmd = &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create an email alias\",\n\t\tRun: aliasCreateRun,\n\t}\n\taliasCreateFlags = struct {\n\t\talias string\n\t\tdomain string\n\t\taddresses []string\n\t\tdescription string\n\t\trandomAlias bool\n\t\trandomAliasLength int\n\t\tuseBase64Encoding bool\n\t}{}\n)\n\nfunc init() {\n\taliasCmd := cmd.AliasCmd()\n\taliasCmd.AddCommand(aliasCreateCmd)\n\n\taliasCreateCmd.Flags().StringSliceVarP(&aliasCreateFlags.addresses, \"email-address\", \"e\", []string{}, \"Address(es) for alias to send email to (fully qualified)\")\n\taliasCreateCmd.Flags().StringVarP(&aliasCreateFlags.domain, \"domain\", \"d\", \"\", \"Domain to attach the alias to\")\n\taliasCreateCmd.Flags().StringVarP(&aliasCreateFlags.alias, \"alias\", \"a\", \"\", \"Alias name (minus domain)\")\n\taliasCreateCmd.Flags().StringVarP(&aliasCreateFlags.description, \"description\", \"D\", \"\", \"Description\")\n\taliasCreateCmd.Flags().BoolVarP(&aliasCreateFlags.randomAlias, \"random-alias\", \"r\", false, \"Create a random alias\")\n\taliasCreateCmd.Flags().IntVarP(&aliasCreateFlags.randomAliasLength, \"random-length\", \"l\", 16, \"Length of the randomly generated alias\")\n\taliasCreateCmd.Flags().BoolVarP(&aliasCreateFlags.useBase64Encoding, \"use-base64\", \"b\", false, \"Use RFC 4648 encoding for the alias\")\n\taliasCreateCmd.Flags().SortFlags = false\n}\n\ntype randReader interface {\n\tRead([]byte) (int, error)\n}\n\ntype realRandReader struct{}\n\nfunc (r realRandReader) Read(b []byte) (int, error) {\n\treturn rand.Read(b)\n}\n\nfunc randomAlias(r randReader, randomAliasLength int, useBase64Encoding bool) (string, error) {\n\t// Make a bas64 encoding set that only consists of a-z0-9 -- not an even distribution\n\t// but should not matter for our use case. Using lowercase letters since most email\n\t// systems don't distinguish between upper and lowercase latters.\n\tconst encodeSet = \"abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz01\"\n\n\tb := make([]byte, 256)\n\t_, err := r.Read(b)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"generating random data\")\n\t}\n\n\tvar alias string\n\tif useBase64Encoding {\n\t\tfmt.Println(\"HERE\")\n\t\talias = base64.NewEncoding(encodeSet).WithPadding(base64.NoPadding).EncodeToString(b)\n\t\talias = alias[:randomAliasLength]\n\t} else {\n\t\talias = fmt.Sprintf(\"%x\", md5.Sum(b))\n\t\talias = alias[:randomAliasLength]\n\t}\n\n\treturn alias, nil\n}\n\nfunc aliasCreateRun(cobraCmd *cobra.Command, args []string) {\n\t// Validate inputs\n\terr := cmd.ValidateInputs(&aliasCreateFlags.domain, nil, &aliasCreateFlags.addresses)\n\tif err != nil {\n\t\tcmd.ErrorExit(err, cobraCmd)\n\t}\n\n\tif aliasCreateFlags.randomAliasLength > 32 {\n\t\tcmd.ErrorExit(fmt.Errorf(\"max random alias length of 32 bytes\"), cobraCmd)\n\t}\n\n\tif !aliasCreateFlags.randomAlias && aliasCreateFlags.alias == \"\" {\n\t\tcmd.ErrorExit(fmt.Errorf(\"alias needed or specify generating a random alias\"), cobraCmd)\n\t}\n\n\t// If --random-alias is set, we generate a random set of bytes to feed to\n\t// the encoding generators.\n\tif aliasCreateFlags.randomAlias && aliasCreateFlags.alias == \"\" {\n\t\tvar err error\n\t\taliasCreateFlags.alias, err = randomAlias(realRandReader{}, aliasCreateFlags.randomAliasLength, aliasCreateFlags.useBase64Encoding)\n\t\tif err != nil {\n\t\t\tcmd.ErrorExit(err, nil)\n\t\t}\n\t}\n\n\tsp, err := cmd.StorageProvider()\n\tif err != nil {\n\t\tcmd.ErrorExit(err, nil)\n\t}\n\tep, err := cmd.EmailProvider()\n\tif err != nil {\n\t\tcmd.ErrorExit(err, nil)\n\t}\n\n\ta := alias.Alias{\n\t\tAlias: aliasCreateFlags.alias,\n\t\tDomain: aliasCreateFlags.domain,\n\t\tEmailAddresses: aliasCreateFlags.addresses,\n\t\tDescription: aliasCreateFlags.description,\n\t}\n\n\treadOnly := viper.GetBool(\"readonly\")\n\tif readOnly {\n\t\tcmd.ErrorExit(fmt.Errorf(\"alias create requires %s to not be readonly\", sp.Type()), nil)\n\t}\n\tif err := sp.Open(readOnly); err != nil {\n\t\tcmd.ErrorExit(fmt.Errorf(\"failure opening %s storage: %v\", sp.Type(), err), nil)\n\t}\n\n\t// Check if the alias already exists\n\talias, err := sp.Get(aliasCreateFlags.alias, aliasCreateFlags.domain)\n\tif err != nil {\n\t\tcmd.ErrorExit(err, nil)\n\t}\n\tif alias != nil {\n\t\tcmd.ErrorExit(fmt.Errorf(\"alias %s for domain %s already exists\", aliasCreateFlags.alias, aliasCreateFlags.domain), nil)\n\t}\n\n\terr = ep.AliasCreate(aliasCreateFlags.alias, aliasCreateFlags.domain, aliasCreateFlags.addresses...)\n\tif err != nil {\n\t\tcmd.ErrorExit(err, nil)\n\t}\n\tfmt.Printf(\"Created alias %s that points to %s\\n\", fmt.Sprintf(\"%s@%s\", aliasCreateFlags.alias, aliasCreateFlags.domain), strings.Join(aliasCreateFlags.addresses, \", \"))\n\n\tif err := sp.Put(a, true); err != nil {\n\t\tcmd.ErrorExit(fmt.Errorf(\"failure adding to %s storage: %v\", sp.Type(), err), nil)\n\t}\n\tif err := sp.Close(); err != nil {\n\t\tcmd.ErrorExit(fmt.Errorf(\"failure closing %s storage: %v\", sp.Type(), err), nil)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":997,"cells":{"blob_id":{"kind":"string","value":"9274ac48db8cf83e841acba7da561735afcf2732"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"zhaopeilin1/go-excercise"},"path":{"kind":"string","value":"/practice/home-system/internal/model/item.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1809,"string":"1,809"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"detected_licenses_right":{"kind":"list like","value":[],"string":"[]"},"license_type_right":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"package model\n\nimport (\n\t\"github.com/jinzhu/gorm\"\n)\n\ntype Item struct {\n\t*Model\n\t// 物品名称\n\tName string `json:\"name\"`\n\n\t// 状态\n\tState string `json:\"state\"`\n\tCategory string `json:\"category\"`\n\t//类目\n\tCategoryId uint32 `json:\"category_id\"`\n\n\tHomeId uint32 `json:\"home_id\"`\n\t//计量单位\n\tUnit string `json:\"unit\"`\n\t//消耗速度\n\tConsumptionSpeed float64 `json:\"consumption_speed\"`\n}\n\nfunc (model Item) TableName() string {\n\treturn \"item\"\n}\n\nfunc (t Item) Count(db *gorm.DB) (int, error) {\n\tvar count int\n\tif t.Name != \"\" {\n\t\tdb = db.Where(\"name like '%?%'\", t.Name)\n\t}\n\tif t.HomeId != 0 {\n\t\tdb = db.Where(\"home_id=?\", t.HomeId)\n\t}\n\tif t.CategoryId != 0 {\n\t\tdb = db.Where(\"category_id=?\", t.CategoryId)\n\t}\n\n\tif t.State != \"\" {\n\t\tdb = db.Where(\"state = ?\", t.State)\n\t}\n\n\tif err := db.Model(&t).Where(\"is_del = ?\", 0).Count(&count).Error; err != nil {\n\t\treturn 0, err\n\t}\n\treturn count, nil\n}\n\nfunc (t Item) List(db *gorm.DB, pageOffset, pageSize int) ([]*Item, error) {\n\tvar tags []*Item\n\tvar err error\n\n\tif pageOffset >= 0 && pageSize > 0 {\n\t\tdb = db.Offset(pageOffset).Limit(pageSize)\n\n\t}\n\tif t.Name != \"\" {\n\t\tdb = db.Where(\"name like '%?%'\", t.Name)\n\t}\n\tif t.HomeId != 0 {\n\t\tdb = db.Where(\"home_id=?\", t.HomeId)\n\t}\n\tif t.CategoryId != 0 {\n\t\tdb = db.Where(\"category_id=?\", t.CategoryId)\n\t}\n\n\tif t.State != \"\" {\n\t\tdb = db.Where(\"state = ?\", t.State)\n\t}\n\n\tif err = db.Where(\"is_del = ?\", 0).Find(&tags).Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn tags, nil\n\n}\n\nfunc (t Item) Create(db *gorm.DB) error {\n\treturn db.Create(&t).Error\n}\n\nfunc (t Item) Update(db *gorm.DB, values interface{}) error {\n\treturn db.Model(&t).Where(\"id = ? and is_del=?\", t.Id, 0).Updates(values).Error\n}\n\nfunc (t Item) Delete(db *gorm.DB) error {\n\treturn db.Where(\"id=? and is_del = ?\", t.Id, 0).Delete(&t).Error\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":998,"cells":{"blob_id":{"kind":"string","value":"ed97feb7965ba90386e2bf7999a3af404ad6819d"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"stooke/fabric8-wit"},"path":{"kind":"string","value":"/workitem/number_sequence/work_item_number_sequence_repository_test.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2097,"string":"2,097"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package numbersequence_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/fabric8-services/fabric8-wit/application\"\n\t\"github.com/fabric8-services/fabric8-wit/gormtestsupport\"\n\t\"github.com/fabric8-services/fabric8-wit/resource\"\n\ttf \"github.com/fabric8-services/fabric8-wit/test/testfixture\"\n\t. \"github.com/fabric8-services/fabric8-wit/workitem/number_sequence\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/suite\"\n)\n\ntype workItemNumberSequenceTest struct {\n\tgormtestsupport.DBTestSuite\n\trepo WorkItemNumberSequenceRepository\n}\n\nfunc TestWorkItemNumberSequenceTest(t *testing.T) {\n\tresource.Require(t, resource.Database)\n\tsuite.Run(t, &workItemNumberSequenceTest{DBTestSuite: gormtestsupport.NewDBTestSuite()})\n}\n\nfunc (s *workItemNumberSequenceTest) SetupTest() {\n\ts.DBTestSuite.SetupTest()\n\ts.repo = NewWorkItemNumberSequenceRepository(s.DB)\n}\n\nfunc (s *workItemNumberSequenceTest) TestConcurrentNextVal() {\n\t// given\n\tfxt := tf.NewTestFixture(s.T(), s.DB, tf.Spaces(1))\n\ttype Report struct {\n\t\tid int\n\t\ttotal int\n\t\tfailures int\n\t}\n\troutines := 10\n\titemsPerRoutine := 50\n\treports := make([]Report, routines)\n\t// when running concurrent go routines simultaneously\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < routines; i++ {\n\t\twg.Add(1)\n\t\t// in each go rountine, run 10 creations\n\t\tgo func(routineID int) {\n\t\t\tdefer wg.Done()\n\t\t\treport := Report{id: routineID}\n\t\t\tfor j := 0; j < itemsPerRoutine; j++ {\n\t\t\t\tif err := application.Transactional(s.GormDB, func(app application.Application) error {\n\t\t\t\t\t_, err := s.repo.NextVal(context.Background(), fxt.Spaces[0].ID)\n\t\t\t\t\treturn err\n\t\t\t\t}); err != nil {\n\t\t\t\t\ts.T().Logf(\"Creation failed: %s\", err.Error())\n\t\t\t\t\treport.failures++\n\t\t\t\t}\n\t\t\t\treport.total++\n\t\t\t}\n\t\t\treports[routineID] = report\n\t\t}(i)\n\t}\n\twg.Wait()\n\t// then\n\t// wait for all items to be created\n\tfor _, report := range reports {\n\t\tfmt.Printf(\"Routine #%d done: %d creations, including %d failure(s)\\n\", report.id, report.total, report.failures)\n\t\tassert.Equal(s.T(), itemsPerRoutine, report.total)\n\t\tassert.Equal(s.T(), 0, report.failures)\n\t}\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":999,"cells":{"blob_id":{"kind":"string","value":"a43f37f880285e8a5e1c2dc566f1dcab736845c7"},"language":{"kind":"string","value":"Go"},"repo_name":{"kind":"string","value":"justdomepaul/leetcode-golang"},"path":{"kind":"string","value":"/solutions/324.go"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":483,"string":"483"},"score":{"kind":"number","value":3.15625,"string":"3.15625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"detected_licenses_right":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type_right":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"package solutions\n\nimport (\n \"sort\"\n)\n\nfunc wiggleSort(nums []int) {\n if len(nums) <= 1 {\n return\n }\n\n sort.Ints(nums)\n\n middle := len(nums) / 2 + len(nums) % 2\n\n var result []int\n\n for i := 0; i < middle; i++ {\n result = append(result, nums[middle - i - 1])\n\n if middle + i < len(nums){\n result = append(result, nums[len(nums) - i - 1])\n }\n }\n\n for i := 0; i < len(result); i++ {\n nums[i] = result[i]\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":9,"numItemsPerPage":100,"numTotalItems":1917163,"offset":900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc2NTYyNjY1OCwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9nbyIsImV4cCI6MTc2NTYzMDI1OCwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.JMMQOCVSCRZztQKBEixbIIqcB6NhiH-jQfJminCxia-YBkDBYb2Kb39l6VxP_cmW4R37BCtHMFySDmDGm1KCAg","displayUrls":true,"splitSizeSummaries":[{"config":"default","split":"train","numRows":1917163,"numBytesParquet":2171209041}]},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
108
path
stringlengths
2
210
src_encoding
stringclasses
12 values
length_bytes
int64
13
5.82M
score
float64
2.52
5.22
int_score
int64
3
5
detected_licenses
listlengths
0
161
license_type
stringclasses
2 values
detected_licenses_right
listlengths
0
161
license_type_right
stringclasses
2 values
text
stringlengths
13
6.48M
download_success
bool
1 class
65b1a12e038adff49e594cf123831a27f1e02b3d
Go
ruckstack/ruckstack
/server/system_control/internal/server/monitor/tracker.go
UTF-8
3,423
3.0625
3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
package monitor import ( "context" "strings" ) type Tracker struct { Name string Check func(*Tracker) Context context.Context currentProblems map[string]string seenProblems map[string]bool currentWarnings map[string]string seenWarnings map[string]bool updateChannel chan *Tracker receivedData bool } func (tracker *Tracker) FoundProblem(component string, problemKey string, description string) { tracker.receivedData = true problemKey = component + ":" + problemKey tracker.seenProblems[problemKey] = true existingDesc, problemExists := tracker.currentProblems[problemKey] if !problemExists || existingDesc != description { message := problemKey if description != "" { message += " -- " + description } logger.Println("PROBLEM: " + message) tracker.currentProblems[problemKey] = description tracker.updateChannel <- tracker } } func (tracker *Tracker) ResolveProblem(component string, problemKey string, resolvedMessage string) { tracker.receivedData = true problemKey = component + ":" + problemKey _, problemExists := tracker.currentProblems[problemKey] if problemExists { delete(tracker.currentProblems, problemKey) logger.Println("RESOLVED: " + resolvedMessage) tracker.updateChannel <- tracker } else { if !tracker.seenProblems[problemKey] { logger.Println("RESOLVED: " + resolvedMessage) tracker.seenProblems[problemKey] = true tracker.updateChannel <- tracker } } } func (tracker *Tracker) FoundWarning(component string, warningKey string, description string) { tracker.receivedData = true warningKey = component + ":" + warningKey tracker.seenWarnings[warningKey] = true existingDesc, warningExists := tracker.currentWarnings[warningKey] if !warningExists || existingDesc != description { message := warningKey if description != "" { message += " -- " + description } logger.Println("WARNING: " + message) tracker.currentWarnings[warningKey] = description tracker.updateChannel <- tracker } } func (tracker *Tracker) ResolveWarning(component string, warningKey string, resolvedMessage string) { tracker.receivedData = true warningKey = component + ":" + warningKey _, warningExists := tracker.currentWarnings[warningKey] if warningExists { delete(tracker.currentWarnings, warningKey) logger.Println("RESOLVED: " + resolvedMessage) tracker.updateChannel <- tracker } else { if !tracker.seenWarnings[warningKey] { logger.Println("RESOLVED: " + resolvedMessage) tracker.seenWarnings[warningKey] = true tracker.updateChannel <- tracker } } } func (tracker *Tracker) Log(message string) { logger.Println(message) } func (tracker *Tracker) Logf(format string, v interface{}) { logger.Printf(format, v) } func (tracker *Tracker) ResolveComponent(component string) { for _, trackerMap := range []map[string]string{tracker.currentProblems, tracker.currentWarnings} { for key, _ := range trackerMap { if strings.HasPrefix(key, component+":") { delete(trackerMap, key) } } } for _, trackerMap := range []map[string]bool{tracker.seenProblems, tracker.seenWarnings} { for key, _ := range trackerMap { if strings.HasPrefix(key, component+":") { delete(trackerMap, key) } } } tracker.updateChannel <- tracker } func (tracker *Tracker) IsHealthy() bool { if !tracker.receivedData { return false } return len(tracker.currentProblems) == 0 }
true
bf3e134a04a37b11eac3c01a623ead3e65bf2a70
Go
vk0n/exago
/task4/main.go
UTF-8
1,739
3.78125
4
[]
no_license
[]
no_license
package main import ( "bufio" "fmt" "os" "strings" ) func cipher(text string, shft int, direction int) string { shift, offset := rune(shft), rune(26) runes := []rune(text) for index, char := range runes { switch direction { case -1: // encoding if char >= 'a' && char+shift <= 'z' || char >= 'A' && char+shift <= 'Z' { char = char + shift } else if char > 'z'-shift && char <= 'z' || char > 'Z'-shift && char <= 'Z' { char = char + shift - offset } case +1: // decoding if char >= 'a'+shift && char <= 'z' || char >= 'A'+shift && char <= 'Z' { char = char - shift } else if char >= 'a' && char < 'a'+shift || char >= 'A' && char < 'A'+shift { char = char - shift + offset } } runes[index] = char } return string(runes) } func encode(text string, shift int) string { return cipher(text, shift, -1) } func decode(text string, shift int) string { return cipher(text, shift, +1) } func main() { var text string var words string var words_list []string fmt.Println("Enter your text:") reader := bufio.NewReader(os.Stdin) text, _ = reader.ReadString('\n') text = strings.Replace(text, "\n", "", -1) fmt.Println("Enter 5 source words (comma-separated):") words, _ = reader.ReadString('\n') words = strings.Replace(words, "\n", "", -1) words_list = strings.Split(words, ",") shift_found := false shift := -1 for shift < 25 && !shift_found { shift++ shift_found = true for _, w := range words_list { w = strings.TrimSpace(w) if !strings.Contains(text, encode(w, shift)) { shift_found = false } } } if shift_found { fmt.Println("Shift:", shift) fmt.Println(decode(text, shift)) } else { fmt.Println("Decoding failed!") } }
true
624966f846ccc512c18c033dbafc051c0612c44f
Go
taozhang-tt/StudyGo
/leet_code/0111-minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.go
UTF-8
1,836
3.953125
4
[]
no_license
[]
no_license
package main import "fmt" /** 111. 二叉树的最小深度 https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/ 题目描述: 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func main() { root := &TreeNode{ Val: 3, Left: &TreeNode{ Val: 5, Left: &TreeNode{ Val: 6, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 2, Left: &TreeNode{ Val: 7, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 4, Left: nil, Right: nil, }, }, }, Right: &TreeNode{ Val: 1, Left: &TreeNode{ Val: 0, Left: nil, Right: nil, }, Right: &TreeNode{ Val: 8, Left: nil, Right: nil, }, }, } fmt.Println(minDepth2(root)) } //利用广度优先搜索 func minDepth(root *TreeNode) int { if root == nil { return 0 } queue := make([]*TreeNode, 0) queue = append(queue, root) min := 0 for len(queue) > 0 { min++ currLevelSize := len(queue) for i := 0; i < currLevelSize; i++ { curr := queue[0] if curr.Left == nil && curr.Right == nil { return min } if curr.Left != nil { queue = append(queue, curr.Left) } if curr.Right != nil { queue = append(queue, curr.Right) } queue = queue[1:] } } return min } //利用深度优先搜索 func minDepth2(root *TreeNode) int { if root == nil { return 0 } if root.Left == nil { return minDepth2(root.Right) + 1 } if root.Right == nil { return minDepth2(root.Left) + 1 } lMin := minDepth2(root.Left) rMin := minDepth2(root.Right) if lMin < rMin { return lMin + 1 } return rMin + 1 }
true
9587f6280bd0cc0ce9fd47d83adc3926b083149f
Go
furushchev/mgomgo
/mgomgo.go
UTF-8
3,597
2.6875
3
[]
no_license
[]
no_license
package mgomgo import ( "fmt" "github.com/Sirupsen/logrus" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "net/url" "strings" "time" "io" ) type DBParams struct { Host string Database string Collection string UserName string Password string } func NewDBParamsFromURI(uri string) (*DBParams, error) { u, err := url.Parse(uri) if err != nil { return nil, err } if u.Scheme != "mongodb" { return nil, fmt.Errorf("mongodb:// scheme is only supported") } path := strings.Split(u.Path, "/") if len(path) == 2 { return nil, fmt.Errorf("No collection name specified") } else if len(path) != 3 { return nil, fmt.Errorf("database name and collection name must be specified") } var username = "" var password = "" if u.User != nil { username = u.User.Username() password, _ = u.User.Password() } return &DBParams{ Host: u.Host, Database: path[1], Collection: path[2], UserName: username, Password: password, }, nil } func Migrate(from, to string, conn int, timeout time.Duration) error { fromParams, err := NewDBParamsFromURI(from) if err != nil { return err } toParams, err := NewDBParamsFromURI(to) if err != nil { return err } logrus.Infof("connect as source to: %s\n", fromParams.Host) fromSession, err := mgo.DialWithTimeout(fromParams.Host, timeout) if err != nil { return err } defer fromSession.Clone() fromSession.SetMode(mgo.Monotonic, true) logrus.Infof("connect as destination to: %s\n", toParams.Host) toSession, err := mgo.DialWithTimeout(toParams.Host, timeout) if err != nil { return err } defer toSession.Close() toSession.SetMode(mgo.Monotonic, true) fromDB := fromSession.DB(fromParams.Database) if fromParams.UserName != "" { if err := fromDB.Login(fromParams.UserName, fromParams.Password); err != nil { return err } } fromC := fromDB.C(fromParams.Collection) logrus.Infof("connected source to %s.%s\n", fromC.Database.Name, fromC.Name) logrus.Infof("generating %d routines...", conn) iter := fromC.Find(bson.M{}).Iter() datachan := make(chan bson.M, conn) infochan := make(chan string, conn) errchan := make(chan error, conn) for i := 0; i < conn; i++ { go func(rnum int, s *mgo.Session, p *DBParams) { copySession := s.Copy() defer copySession.Close() copySession.SetMode(mgo.Monotonic, true) toDB := copySession.DB(p.Database) if toParams.UserName != "" { if err := toDB.Login(p.UserName, p.Password); err != nil { errchan <- err } } c := toDB.C(p.Collection) logrus.Infof("%d: connected to %s.%s\n", rnum, c.Database.Name, c.Name) for { rdata, ok := <- datachan if ok { if err := c.Insert(rdata); err != nil { if mgo.IsDup(err) { if oid, ok := rdata["_id"].(bson.ObjectId); ok { infochan <- fmt.Sprintf("%d: skipped %s", rnum, oid.Hex()) } continue } if err == io.EOF { copySession.Refresh() continue } errchan <- err return } else { if oid, ok := rdata["_id"].(bson.ObjectId); ok { infochan <- fmt.Sprintf("%d: migrated %s", rnum, oid.Hex()) } else { infochan <- fmt.Sprintf("%d: warn: cannot get _id: %v", rnum, rdata) } } } } }(i, toSession, toParams) } go func() { for { select { case info := <- infochan: logrus.Infoln(info) case err := <- errchan: logrus.Errorln(err) } } }() for { var data bson.M if ok := iter.Next(&data); !ok { logrus.Fatalf("no next data") close(datachan) } else { datachan <- data } } return nil }
true
dc59aeaa56acb4e1f0404aab32b483a41945ed24
Go
thebsdbox/kuiz
/pkg/server/questionManager.go
UTF-8
3,287
2.90625
3
[]
no_license
[]
no_license
package server import ( "sort" "time" "github.com/thebsdbox/kuiz/pkg/quiz/types" ) type questionManager struct { question types.Question receipts []types.QuizReceipt answers []types.QuizAnswer fastestAnswer int64 fastestUser string } func (m *Manager) processAnswers() { var correctAnswer string question := m.qm.question switch question.Type { case types.QUIZMULTI: correctAnswer = question.MultiChoiceQuestion.Answer //question.MultiChoiceQuestion.Answer = "" case types.QUIZYESNO: correctAnswer = question.YesNoChoiceQuestion.Answer //question.YesNoChoiceQuestion.Answer = "" } // Set the fastest time to something big :-) m.qm.fastestAnswer = time.Hour.Milliseconds() //->DEBUG //fmt.Printf("receipts [%d] / answers [%d]\n", len(m.qm.receipts), len(m.qm.answers)) // Go through all answers for x := range m.qm.answers { // If this answer was correct, find when the question was recieved by the client //fmt.Printf("%s = %s\n", m.qm.answers[x].Answer, correctAnswer) if m.qm.answers[x].Answer == correctAnswer { // Find the UID and determine time duration for y := range m.qm.receipts { if m.qm.answers[x].User.UID == m.qm.receipts[y].User.UID { // How long did the answer take? // ->DEBUG //fmt.Printf("Match for [%s]\n", m.qm.answers[x].User.Username) questionDuration := m.qm.answers[x].ReceiptTime.Sub(m.qm.receipts[y].ReceiptTime) score := (questionDuration - m.qm.question.TimeToReveal).Milliseconds() // ->DEBUG //questionDuration1 := m.qm.receipts[x].ReceiptTime.Sub(m.qm.answers[y].ReceiptTime) // ->DEBUG //fmt.Printf("%d vs %d", questionDuration.Milliseconds(), questionDuration1) // Was this the fastest answer if m.qm.fastestAnswer > score { m.qm.fastestAnswer = score m.qm.fastestUser = m.qm.answers[x].User.Username } // Add to score board m.updateScore(&m.qm.answers[x].User, score) } } } } } // Update the scoreboard func (m *Manager) updateScore(u *types.User, score int64) { // 10000000000 // 5000000000 -- // 7783488000 --|_ 2783 // 10000000000 // 5000000000 -- // 5423501000 --|_ 423 // question time = 10 seconds // remove the time we wait, leaving the time to see and answer teh question // remove how long the user took //fmt.Printf("\n%d\n%d\n%d\n", time.Second*10, m.qm.question.TimeToReveal, questionDuration) //score := time.Second*10 - // Was this the fastest answer if m.s.FastestAnswer > score { m.s.FastestAnswer = score m.s.FastestUser = u.Username } // Turn the time into a score score = (time.Second * 10).Milliseconds() - score var found bool for x := range m.s.Users { if u.UID == m.s.Users[x].User.UID { found = true m.s.Users[x].Score += score } } if found == false { newScore := types.UserScore{ User: u, Score: score, } m.s.Users = append(m.s.Users, newScore) } } func (m *Manager) postScore() { sort.Slice(m.s.Users, func(i, j int) bool { return m.s.Users[i].Score > m.s.Users[j].Score }) // Wrap the data to send to clients wrappedData := types.EncodeData(types.TYPESCORE, m.s) for x := range clients { // send to all clients (ignore the dead or failed clients) go clients[x].WriteJSON(wrappedData) } }
true
1290abc3ba709ecd8d9779dce029c38271425f17
Go
premeidoworks/components
/kanatasupport/uuid.gouuid.go
UTF-8
299
2.53125
3
[]
no_license
[]
no_license
package kanatasupport import "github.com/satori/go.uuid" type uuidGenerator struct { } func newUUIDGenerator() uuidGenerator { return uuidGenerator{} } func (this uuidGenerator) Generate() (string, error) { u, err := uuid.NewV1() if err != nil { return "", err } return u.String(), err }
true
0c5ac22eb2dbbc6caa357d27aa2d641bc798d385
Go
sean-purcell/wg-docker-net
/wg/wg.go
UTF-8
2,717
2.578125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package wg import ( "fmt" "log" "net" "os/exec" "runtime" "strings" "github.com/docker/go-plugins-helpers/network" "github.com/vishvananda/netlink" "github.com/vishvananda/netns" "gopkg.in/go-ini/ini.v1" ) type WgConfig struct { Path string ListenPort uint Net *net.IPNet PeerNets []*net.IPNet } func ParseWgConfig(path string) (*WgConfig, error) { ini, err := ini.LoadSources(ini.LoadOptions{AllowNonUniqueSections: true}, path) if err != nil { return nil, err } intf := ini.Section("Interface") if intf == nil { return nil, fmt.Errorf("[Interface] section missing in config: %s\n", path) } key, err := intf.GetKey("ListenPort") if err != nil { return nil, err } ListenPort, err := key.Uint() if err != nil { return nil, err } key, err = intf.GetKey("Address") if err != nil { return nil, err } ip, Net, err := net.ParseCIDR(key.String()) Net.IP = ip if err != nil { return nil, err } sections, err := ini.SectionsByName("Peer") if err != nil { return nil, err } fmt.Printf("Num sections: %v\n", len(sections)) PeerNets := make([]*net.IPNet, 0) for _, section := range sections { key, err := section.GetKey("AllowedIPs") if err != nil { return nil, err } fmt.Printf("AllowedIps: %s\n", key.Value()) for _, addr := range key.Strings(",") { _, peerNet, err := net.ParseCIDR(strings.TrimSpace(addr)) if err != nil { return nil, err } PeerNets = append(PeerNets, peerNet) } } Path := path return &WgConfig{Path, ListenPort, Net, PeerNets}, nil } func (t *WgConfig) StartInterface(nl *netlink.Handle) (netlink.Link, error) { runtime.LockOSThread() defer runtime.UnlockOSThread() currentNs, err := netns.Get() if err != nil { return nil, err } defer func() { netns.Set(currentNs) _ = currentNs.Close() }() // TODO: We should maybe set the netns here log.Printf("Bringing up wireguard interface at %s\n", t.Path) cmd := exec.Command("wg-quick", "up", t.Path) output, err := cmd.CombinedOutput() if err != nil { log.Printf("Command failed: %v\n", err) return nil, err } log.Printf("Output: %s\n", string(output)) links, err := nl.LinkList() if err != nil { return nil, fmt.Errorf("Failed to enumerate links %v", err) } for _, link := range links { if link.Type() == "wireguard" { return link, nil } } return nil, fmt.Errorf("Wireguard interface not found") } func (t *WgConfig) GetRoutes(gateway net.IP) []*network.StaticRoute { routes := make([]*network.StaticRoute, len(t.PeerNets)) for i, peer := range t.PeerNets { routes[i] = &network.StaticRoute{ Destination: peer.String(), RouteType: 0, NextHop: gateway.String(), } } return routes }
true
0a898deb8a0165d4c3752390815c70a88b6133b4
Go
LaPingvino/peercat
/main.go
UTF-8
485
3.265625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Peercat is a tool for connecting random computers on the internet in a netcat like style // using a shared connection string. package main import ( "os" "io" ) func main() { var ( in io.Reader = os.Stdin out io.Writer = os.Stdout ) if len(os.Args) > 1 { ins := make([]io.Reader, len(os.Args)-1) for i, file := range os.Args[1:] { f, err := os.Open(file) if err != nil { panic(err) } ins[i] = f } in = io.MultiReader(ins...) } io.Copy(out, in) }
true
784f08b2d28818d729a1cd22c5debc0fcf9fb618
Go
otera99/go_copy_slices_and_maps_at_boundaries_checker
/testdata/src/a/a.go
UTF-8
859
3.984375
4
[]
no_license
[]
no_license
package a import ( "fmt" ) type Container struct { Values []string } func (c *Container) SetValues(values []string) { // 引数のスライスで受け取ったスライスがそのままフィールドに保存されている c.Values = values } func (c *Container) CorrectSetValues(values []string) { // 正しい書き方をしている場合 vs := make([]string, len(values)) copy(vs, values) c.Values = vs } func main() { c := &Container{} d := &Container{} list := []string{"hello", "world"} list1 := []string{"hello", "world"} c.SetValues(list) d.CorrectSetValues(list1) fmt.Println(c) // その関数の引数に渡したスライスがあとで要素が変更されている list[1] = "tenntenn" // want "WARN: Slice or map taken as an argument and stored in a field may be rewritten." list1[1] = "tenntenn" fmt.Println(c) }
true
faced72adb395933eaf75254a7f2b80f938a70d3
Go
HeoJinHo/golanStudy
/src/section09/go_sync_ex3.go
UTF-8
986
3.578125
4
[]
no_license
[]
no_license
package main import ( "fmt" "runtime" "sync" ) // 고루틴 고급(3) func main() { // 고루틴 동기화 고급 // 원자성 사용 -> 트렌젝션과 같음 : 모두 성공, 모두 실패 즉, 롤백 // 기능적으로 분할 불가능한 완전 보증된 일련의 조작, 모두 성공하거나 모두 실패 // 모든 조작이 완료 될 때까지 다른 프로세스 개입 불가 // sync/atomic 에서 원자적 연산자 제공 // https://golang.org/pkg/sync/atomic 에서 계열 확인 가능 // 주로 공용 변수에 관한 계산 사용 // 원자성 사용 안할 경우 계제 runtime.GOMAXPROCS(runtime.NumCPU()) var cnt int64 = 0 wg := new(sync.WaitGroup) for i := 0; i < 5000; i++ { wg.Add(1) go func(n int) { cnt += 1 wg.Done() }(i) } for i := 0; i < 2000; i++ { wg.Add(1) go func(n int) { cnt -= 1 wg.Done() }(i) } // Add == Done 횟수가 같아야한다 wg.Wait() fmt.Println("WaitGroup End! >>>>> ", cnt) }
true
9c2221fc42a42b6cf03c24e1bb68a542560fd365
Go
armfazh/h2c-go-ref
/mapping/mapping.go
UTF-8
1,867
2.9375
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// Package mapping contains a set of functions to construct functions that take // a field element and return a point on an elliptic curve. Certain mappings // restrict the form of the curve or its parameters. // // Choosing a mapping function // // If the target elliptic curve is: // - a supersingular curve, then use either the Boneh-Franklin method (NewBF) or the Elligator 2 method for A == 0 (newWA0Ell2); // - a Montgomery or twisted Edwards curve, then use the Elligator 2 (NewElligator2); // - a Weierstrass curve, then use either the Simplified SWU (NewSSWU), even if either A or B is zero; // - if none of the above applies, then use the Shallue-van de Woestijne method (NewSVDW). // // Note: the mappings must not be used standalone, since its correct and secure // usage is determined by each hash to curve suite. package mapping import ( C "github.com/armfazh/tozan-ecc/curve" GF "github.com/armfazh/tozan-ecc/field" ) // MapToCurve maps a field element into a elliptic curve point. type MapToCurve interface { Map(GF.Elt) C.Point } // ID is an identifier of a mapping. type ID uint const ( // BF is the Boneh-Franklin method BF ID = iota // SSWU is the Simplified SWU method. SSWU // ELL2 is Elligator2 method. ELL2 // SVDW is Shallue-van de Woestijne method. SVDW ) // MapDescriptor describes parameters of a mapping to curve. type MapDescriptor struct { ID ID Z interface{} Iso func() C.Isogeny } // Get returns a MapToCurve implementation based on ID provided. Some arguments // can be set to nil if there are not required by the mapping. func (d MapDescriptor) Get(e C.EllCurve) MapToCurve { switch d.ID { case BF: return NewBF(e) case SSWU: z := e.Field().Elt(d.Z) return NewSSWU(e, z, d.Iso) case SVDW: return NewSVDW(e) case ELL2: return NewElligator2(e) default: panic("Mapping not supported") } }
true
02337ae018c6ea5be4f60b34e2ecb05a80fecca4
Go
phillipchengh/dnd_beyond_party
/src/server/assets.go
UTF-8
1,110
2.609375
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) func requestJSON(url string) interface{} { response, err := http.Get(url) if err != nil { log.Printf("%s", err) } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) if err != nil { log.Printf("%s", err) } var jsonData interface{} jsonErr := json.Unmarshal(body, &jsonData) if jsonErr != nil { log.Printf("%s", jsonErr) } return jsonData } func requestAssetManifest() interface{} { return requestJSON("http://nginx/asset/asset-manifest.json") } func getEntrypointAssets(entrypoint string) interface{} { manifest := requestAssetManifest() entrypoints := manifest.(map[string]interface{})["entrypoints"].(map[string]interface{})[entrypoint] return entrypoints } func assetManifestHTTPHandler(writer http.ResponseWriter, r *http.Request) { assetManifestJSON := requestAssetManifest() assetManifest, err := json.Marshal(assetManifestJSON) if err != nil { log.Printf("%s", err) } writer.Header().Set("Content-Type", "application/json") fmt.Fprintf(writer, string(assetManifest)) }
true
0c17fb73e2aeba0482a245e1d75e3cf5a336d118
Go
rogpeppe/annotatedcsv
/reader.go
UTF-8
4,919
3.140625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package annotatedcsv import ( "encoding/csv" "fmt" "io" "math" "os" "strconv" "strings" "time" ) type Column struct { Name string Group bool Default interface{} Type string } func NewReader(r io.Reader) *Reader { r1 := &Reader{ r: csv.NewReader(r), } r1.r.FieldsPerRecord = -1 return r1 } type Reader struct { cols []Column row []interface{} err error hasPeeked bool peekRow []string peekErr error r *csv.Reader line int } // NextTable advances to the next table and reports whether // there is one. func (r *Reader) NextTable() bool { if r.err != nil { return false } // Read all the current rows. for r.NextRow() { } _, err := r.peek() if err != nil { r.err = err return false } cols, err := r.readHeader() if err != nil { r.err = err return false } r.cols = cols return true } // Err returns any error encountered when parsing. func (r *Reader) Err() error { if r.err == io.EOF { return nil } return r.err } // Columns returns the columns in the current table. func (r *Reader) Columns() []Column { return r.cols } // NextRow advances to the next row in the current table // and reports whether there is one. func (r *Reader) NextRow() bool { if r.cols == nil || r.err != nil { return false } row, err := r.readRow() r.row = row if row == nil { r.err = err r.cols = nil return false } return true } // Row returns the items in the current row of the current table. func (r *Reader) Row() []interface{} { return r.row } func (r *Reader) readRow() ([]interface{}, error) { row, err := r.peek() if err != nil { return nil, nil } if len(row) > 0 && strings.HasPrefix(row[0], "#") { // Start of next table. return nil, nil } r.read() if len(row) != len(r.cols) { return nil, fmt.Errorf("inconsistent number of columns at line %d; got %d want %d", r.line, len(row), len(r.cols)) } rowVals := make([]interface{}, len(row)) for i, val := range row { col := r.cols[i] if col.Default != nil && val == "" { rowVals[i] = col.Default continue } if val == "" && col.Name == "" { continue } x, err := convertToType(val, col.Type) if err != nil { return nil, fmt.Errorf("cannot parse %q as type %q at line %d", val, col.Type, r.line) } rowVals[i] = x } return rowVals, nil } func (r *Reader) readHeader() ([]Column, error) { var cols []Column var defaults []string for { row, err := r.peek() if err != nil { if len(cols) > 0 { err = nil } return cols, err } r.read() if cols == nil { if len(row) == 0 { return nil, fmt.Errorf("no columns in table header at line %d", r.line) } cols = make([]Column, len(row)) } else if len(row) != len(cols) { return nil, fmt.Errorf("inconsistent table header (got %d items want %d)", len(row), len(cols)) } if !strings.HasPrefix(row[0], "#") { for i, col := range row { cols[i].Name = col } break } switch row[0] { case "#datatype": for i := 1; i < len(row); i++ { cols[i].Type = row[i] } case "#group": for i := 1; i < len(row); i++ { // TODO parse bool? cols[i].Group = row[i] == "true" } case "#default": defaults = row default: fmt.Fprintf(os.Stderr, "unknown column annotation %q\n", row[0]) } } if defaults != nil { for i := 1; i < len(defaults); i++ { if defaults[i] == "" { continue } x, err := convertToType(defaults[i], cols[i].Type) if err != nil { return nil, fmt.Errorf("cannot convert default value %q to type %q: %v", defaults[i], cols[i].Type, err) } cols[i].Default = x } } return cols, nil } func convertToType(s string, typ string) (interface{}, error) { switch typ { case "boolean": return strconv.ParseBool(s) case "long": return strconv.ParseInt(s, 10, 64) case "unsignedLong": return strconv.ParseUint(s, 10, 64) case "double": x, err := strconv.ParseFloat(s, 64) if err != nil { return nil, err } if math.IsInf(x, 0) || math.IsNaN(x) { return s, nil } return x, nil case "string", "tag", "": return s, nil } if timeFormat := strings.TrimPrefix(typ, "dateTime:"); len(timeFormat) != len(typ) { layout := timeFormats[timeFormat] if layout == "" { return nil, fmt.Errorf("unknown time format %q", typ) } return time.Parse(layout, s) } fmt.Fprintf(os.Stderr, "unknown datatype %q\n", typ) return s, nil } var timeFormats = map[string]string{ "RFC3339": time.RFC3339, "RFC3339Nano": time.RFC3339Nano, } func (r *Reader) read() (_r []string, _err error) { if r.hasPeeked { row, err := r.peekRow, r.peekErr r.peekRow, r.peekErr, r.hasPeeked = nil, nil, false return row, err } r.line++ return r.r.Read() } func (r *Reader) peek() (_r []string, _err error) { if r.hasPeeked { return r.peekRow, r.peekErr } row, err := r.r.Read() r.line++ r.peekRow, r.peekErr, r.hasPeeked = row, err, true return row, err }
true
3e366df9087309558bd962ca801b19a2c1e68828
Go
sky0621/aws-describe-prj
/config/config.go
UTF-8
2,429
2.71875
3
[]
no_license
[]
no_license
package config import "github.com/spf13/viper" // Config ... type Config struct { Aws *AwsConfig } // NewConfig ... func NewConfig() *Config { return &Config{ Aws: NewAwsConfig(), } } type AwsConfig struct { Sqs *SqsConfig } func NewAwsConfig() *AwsConfig { return &AwsConfig{ Sqs: NewSqsConfig(), } } type SqsConfig struct { Template string Filter Filter Supplements map[string]Supplement } func NewSqsConfig() *SqsConfig { var s map[string]Supplement err := viper.UnmarshalKey("aws.sqs.supplement", &s) if err != nil { panic(err) } var f Filter err = viper.UnmarshalKey("aws.sqs.filter", &f) if err != nil { panic(err) } return &SqsConfig{ Template: viper.GetString("aws.sqs.template"), Filter: f, Supplements: s, } } type Ec2Config struct { Template string Filter Filter Supplements map[string]Supplement } func NewEc2Config() *Ec2Config { var s map[string]Supplement err := viper.UnmarshalKey("aws.ec2.supplement", &s) if err != nil { panic(err) } var f Filter err = viper.UnmarshalKey("aws.ec2.filter", &f) if err != nil { panic(err) } return &Ec2Config{ Template: viper.GetString("aws.ec2.template"), Filter: f, Supplements: s, } } type RdsConfig struct { Template string Filter Filter Supplements map[string]Supplement } func NewRdsConfig() *RdsConfig { var s map[string]Supplement err := viper.UnmarshalKey("aws.rds.supplement", &s) if err != nil { panic(err) } var f Filter err = viper.UnmarshalKey("aws.rds.filter", &f) if err != nil { panic(err) } return &RdsConfig{ Template: viper.GetString("aws.rds.template"), Filter: f, Supplements: s, } } type DynamoDBConfig struct { Template string Filter Filter Supplements map[string]Supplement } func NewDynamoDBConfig() *DynamoDBConfig { var s map[string]Supplement err := viper.UnmarshalKey("aws.dynamodb.supplement", &s) if err != nil { panic(err) } var f Filter err = viper.UnmarshalKey("aws.dynamodb.filter", &f) if err != nil { panic(err) } return &DynamoDBConfig{ Template: viper.GetString("aws.dynamodb.template"), Filter: f, Supplements: s, } } type Filter struct { In string Out []string } type Supplement struct { Usecase, Environment string } // ReadConfig ... func ReadConfig(configFilePath string) error { viper.SetConfigFile(configFilePath) return viper.ReadInConfig() }
true
83fb1e9bc8739e31785c38f0dd6587b33b910437
Go
xSavitar/GoPL
/chapter_2/tempconv0.go
UTF-8
550
3.53125
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Author: Alangi Derick // Description: Package tempconv0 performs Celsius and Fahrenheit temperature computations. // package name is: tempconv0 package tempconv import "fmt" // Two UD Types in this package type Celsius float64 type Fahrenheit float64 // constants const ( AbsoluteZeroC Celsius = -273.15 FreezingC Celsius = 0 BoilingC Celsius = 100 ) // Celsius to Fahrenheit func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) } // Fahrenheit to Celsius func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
true
9189095ec3b6280e56efce37b7a028226b484c0b
Go
MacroPower/tfdocs
/providers/upcloud/d.go
UTF-8
10,157
2.53125
3
[]
no_license
[]
no_license
package upcloud import ( "fmt" "github.com/cycloidio/tfdocs/resource" ) var ( DataSources = []*resource.Resource{ &resource.Resource{ Name: "", Type: "upcloud_hosts", Category: "Data Sources", ShortDescription: `Provides an UpCloud hosts datasource`, Description: ``, Keywords: []string{}, Arguments: []resource.Attribute{}, Attributes: []resource.Attribute{ resource.Attribute{ Name: "hosts", Description: `A list of hosts within your private cloud that can be accessed by the account ### hosts Each entry in the ` + "`" + `hosts` + "`" + ` attribute represents an individual host from your account. The following attributes are available. Each ` + "`" + `hosts` + "`" + ` entry provides the following:`, }, resource.Attribute{ Name: "host_id", Description: `The unique ID representing the host`, }, resource.Attribute{ Name: "description", Description: `Freeform comment string for the host`, }, resource.Attribute{ Name: "zone", Description: `The zone ID where the hosts is located.`, }, }, }, &resource.Resource{ Name: "", Type: "upcloud_ip_addresses", Category: "Data Sources", ShortDescription: `Provides an UpCloud IP Addresses datasource`, Description: ``, Keywords: []string{}, Arguments: []resource.Attribute{}, Attributes: []resource.Attribute{}, }, &resource.Resource{ Name: "", Type: "upcloud_networks", Category: "Data Sources", ShortDescription: `Get information on available UpCloud networks.`, Description: ``, Keywords: []string{}, Arguments: []resource.Attribute{ resource.Attribute{ Name: "zone", Description: `(Optional) Limit returned networks to this UpCloud zone.`, }, resource.Attribute{ Name: "filter_name", Description: `(Optional) A regular-expression allowing filtering of networks by name. ## Attributes Reference`, }, resource.Attribute{ Name: "networks", Description: `A set of the available networks. ### networks`, }, resource.Attribute{ Name: "ip_network", Description: `A set of the IP subnets within the network.`, }, resource.Attribute{ Name: "name", Description: `The name of the network.`, }, resource.Attribute{ Name: "type", Description: `The type of network (one of ` + "`" + `public` + "`" + `, ` + "`" + `utility` + "`" + `, ` + "`" + `private` + "`" + `)`, }, resource.Attribute{ Name: "id", Description: `The unique identifier of the network.`, }, resource.Attribute{ Name: "zone", Description: `The zone in which this network resides.`, }, resource.Attribute{ Name: "servers", Description: `A set of the servers joined to this network. ### ip_network`, }, resource.Attribute{ Name: "address", Description: `The CIRD range of the subnet.`, }, resource.Attribute{ Name: "dhcp", Description: `Is DHCP enabled?`, }, resource.Attribute{ Name: "dhcp_default_route", Description: `Is the ` + "`" + `gateway` + "`" + ` the DHCP default route?`, }, resource.Attribute{ Name: "dhcp_dns", Description: `A set of the DNS servers given by DHCP.`, }, resource.Attribute{ Name: "family", Description: `The IP address familty (one of ` + "`" + `IPv4` + "`" + ` or ` + "`" + `IPv6` + "`" + `)`, }, resource.Attribute{ Name: "gateway", Description: `The gateway address given by DHCP. ### servers`, }, resource.Attribute{ Name: "id", Description: `The unique identifier of the server.`, }, resource.Attribute{ Name: "title", Description: `The short description of the server. [1]: https://upcloud.com/products/software-defined-networking/`, }, }, Attributes: []resource.Attribute{ resource.Attribute{ Name: "networks", Description: `A set of the available networks. ### networks`, }, resource.Attribute{ Name: "ip_network", Description: `A set of the IP subnets within the network.`, }, resource.Attribute{ Name: "name", Description: `The name of the network.`, }, resource.Attribute{ Name: "type", Description: `The type of network (one of ` + "`" + `public` + "`" + `, ` + "`" + `utility` + "`" + `, ` + "`" + `private` + "`" + `)`, }, resource.Attribute{ Name: "id", Description: `The unique identifier of the network.`, }, resource.Attribute{ Name: "zone", Description: `The zone in which this network resides.`, }, resource.Attribute{ Name: "servers", Description: `A set of the servers joined to this network. ### ip_network`, }, resource.Attribute{ Name: "address", Description: `The CIRD range of the subnet.`, }, resource.Attribute{ Name: "dhcp", Description: `Is DHCP enabled?`, }, resource.Attribute{ Name: "dhcp_default_route", Description: `Is the ` + "`" + `gateway` + "`" + ` the DHCP default route?`, }, resource.Attribute{ Name: "dhcp_dns", Description: `A set of the DNS servers given by DHCP.`, }, resource.Attribute{ Name: "family", Description: `The IP address familty (one of ` + "`" + `IPv4` + "`" + ` or ` + "`" + `IPv6` + "`" + `)`, }, resource.Attribute{ Name: "gateway", Description: `The gateway address given by DHCP. ### servers`, }, resource.Attribute{ Name: "id", Description: `The unique identifier of the server.`, }, resource.Attribute{ Name: "title", Description: `The short description of the server. [1]: https://upcloud.com/products/software-defined-networking/`, }, }, }, &resource.Resource{ Name: "", Type: "upcloud_tags", Category: "Data Sources", ShortDescription: `Provides an UpCloud tags datasource`, Description: ``, Keywords: []string{}, Arguments: []resource.Attribute{}, Attributes: []resource.Attribute{ resource.Attribute{ Name: "tags", Description: `A set of tags Each element of the tags set provides the following attributes`, }, resource.Attribute{ Name: "name", Description: `The value representing the tag`, }, resource.Attribute{ Name: "description", Description: `Free form text representing the meaning of the tag`, }, resource.Attribute{ Name: "servers", Description: `A collection of servers that have been assigned the tag`, }, }, }, &resource.Resource{ Name: "", Type: "upcloud_zone", Category: "Data Sources", ShortDescription: `Provides an UpCloud zone datasource`, Description: ``, Keywords: []string{}, Arguments: []resource.Attribute{ resource.Attribute{ Name: "name", Description: `(Required) The UpCloud value that represents the zone. ## Attributes Reference`, }, resource.Attribute{ Name: "id", Description: `Unique label for the zone (same as ` + "`" + `name` + "`" + `)`, }, resource.Attribute{ Name: "description", Description: `A real world value representing the zone, for example ` + "`" + `London #1` + "`" + `.`, }, resource.Attribute{ Name: "public", Description: `Identifies the zone as either public ` + "`" + `true` + "`" + ` or private ` + "`" + `false` + "`" + `.`, }, }, Attributes: []resource.Attribute{ resource.Attribute{ Name: "id", Description: `Unique label for the zone (same as ` + "`" + `name` + "`" + `)`, }, resource.Attribute{ Name: "description", Description: `A real world value representing the zone, for example ` + "`" + `London #1` + "`" + `.`, }, resource.Attribute{ Name: "public", Description: `Identifies the zone as either public ` + "`" + `true` + "`" + ` or private ` + "`" + `false` + "`" + `.`, }, }, }, &resource.Resource{ Name: "", Type: "upcloud_zones", Category: "Data Sources", ShortDescription: `Provides an UpCloud zones datasource`, Description: ``, Keywords: []string{}, Arguments: []resource.Attribute{ resource.Attribute{ Name: "filter_type", Description: `(Optional) Allows the zone_ids to be filtered by type, (public, private or all). Defaults to ` + "`" + `all` + "`" + ` ## Attributes Reference`, }, resource.Attribute{ Name: "id", Description: `UTC timestamp when the request was completed; used only for identifying the request in Terraform.`, }, resource.Attribute{ Name: "zone_ids", Description: `A Collection of ids representing the available zones within UpCloud.`, }, }, Attributes: []resource.Attribute{ resource.Attribute{ Name: "id", Description: `UTC timestamp when the request was completed; used only for identifying the request in Terraform.`, }, resource.Attribute{ Name: "zone_ids", Description: `A Collection of ids representing the available zones within UpCloud.`, }, }, }, } dataSourcesMap = map[string]int{ "upcloud_hosts": 0, "upcloud_ip_addresses": 1, "upcloud_networks": 2, "upcloud_tags": 3, "upcloud_zone": 4, "upcloud_zones": 5, } ) func GetDataSource(r string) (*resource.Resource, error) { rs, ok := dataSourcesMap[r] if !ok { return nil, fmt.Errorf("datasource %q not found", r) } return DataSources[rs], nil }
true
69423d1e3e51753440f91d1a67ab73196bd941d1
Go
alihanyalcin/micgo
/base/internal/service/config/config.go
UTF-8
834
2.625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package config import ( "{project}/internal/pkg/bootstrap/interfaces" "{project}/internal/pkg/config" ) type ConfigurationStruct struct { Service config.ServiceInfo Logging config.LoggingInfo Startup config.StartupInfo Databases config.DatabaseInfo } // GetBootstrap returns the configuration elements required by the bootstrap. func (c *ConfigurationStruct) GetBootstrap() interfaces.BootstrapConfiguration { return interfaces.BootstrapConfiguration{ Service: c.Service, Logging: c.Logging, Startup: c.Startup, } } // GetLogLevel returns the current ConfigurationStruct's log level. func (c *ConfigurationStruct) GetLogLevel() string { return c.Logging.LogLevel } // GetDatabaseInfo returns a database information. func (c *ConfigurationStruct) GetDatabaseInfo() config.DatabaseInfo { return c.Databases }
true
d51ab2ba0d1dcb678c201c1c00da595ee37fc114
Go
gempir/logstv-cassandra
/common/dotenv.go
UTF-8
422
2.75
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package common import ( "os" "github.com/joho/godotenv" ) // LoadEnv values from .env file into environment variables func LoadEnv() { err := godotenv.Load("/etc/logstv/.env") if err != nil { panic("Error loading .env file") } } // GetEnv retrieve a value from environment variables func GetEnv(key string) string { if value, ok := os.LookupEnv(key); ok { return value } panic("Missing env var: " + key) }
true
f990b7a2ff0c9a7da76b97fc32e04c87b8d007dd
Go
nattaponra/logz
/logz.go
UTF-8
1,750
3.015625
3
[]
no_license
[]
no_license
package logz import ( "fmt" "os" "path/filepath" "sync" "time" "github.com/apex/log" "github.com/lestrrat-go/strftime" ) type Logz struct { fileName string pathFile *strftime.Strftime locker sync.Locker file *os.File symlink *strftime.Strftime dateTimePattern string } func NewLogz(fileName, dateTimePattern string) *Logz { pathFile, err := strftime.New(fileName + "." + dateTimePattern) if err != nil { fmt.Println(err.Error()) } return &Logz{ pathFile: pathFile, fileName: fileName, dateTimePattern: dateTimePattern, locker: new(sync.Mutex), symlink: nil, } } func (logz *Logz) Write(b []byte) error { logz.locker.Lock() defer logz.locker.Unlock() go func(fp *os.File) { if fp == nil { return } fp.Close() }(logz.file) filePath := logz.pathFile.FormatString(time.Now()) fmt.Println(filePath) //Create directory. err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm) if err != nil { return err } fp, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { log.Error(err.Error()) } //defer fp.Close() logz.createSymlink(time.Now(), filePath) _, err = fp.Write(b) return err } func (logz *Logz) createSymlink(t time.Time, path string) { symlinkPath, err := strftime.New(logz.fileName) if err != nil { fmt.Println(err.Error()) return } symlink := symlinkPath.FormatString(t) fmt.Println(symlink) if symlink == path { return } if _, err := os.Stat(symlink); err == nil { if err := os.Remove(symlink); err != nil { fmt.Println(err.Error()) return } } if err := os.Symlink(path, symlink); err != nil { fmt.Println(err.Error()) return } }
true
1bcb7d4c104449d6bafb5a3bbe339578ced2bbc9
Go
lpvm/codewars
/alphabeticaladdiction/alphabeticaladdiction.go
UTF-8
872
3.71875
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "fmt" // rune "z" == 122 // AddLetters function func AddLetters(letters []rune) rune { if len(letters) == 0 { return 'z' } nrLetters := 26 offset := 96 acum := 0 for _, v := range letters { acum += int(v) - offset } timesRolled := (acum - 1) / nrLetters acum = acum - timesRolled*nrLetters + offset runes := []rune(string(acum)) return runes[0] } func main() { fmt.Println(string(AddLetters([]rune{}))) fmt.Println(string(AddLetters([]rune{'a', 'b', 'c'}))) fmt.Println(string(AddLetters([]rune{'y', 'c', 'b'}))) fmt.Println(string(AddLetters([]rune{'z'}))) } // AddLetters([]rune{'a', 'b', 'c'}) = 'f' // AddLetters([]rune{'a', 'b'}) = 'c' // AddLetters([]rune{'z'}) = 'z' // AddLetters([]rune{'z', 'a'}) = 'a' // AddLetters([]rune{'y', 'c', 'b'}) = 'd' // notice the letters overflowing // AddLetters([]rune{}) = 'z'
true
3705151b3a10361b23a706d259d9500cdfacf439
Go
osteele/liquid
/values/docs.go
UTF-8
456
2.578125
3
[ "Apache-2.0", "MIT" ]
permissive
[ "Apache-2.0", "MIT" ]
permissive
// Package values is an internal package that defines methods such as sorting, comparison, and type conversion, that apply to interface types. // // It is similar to, and makes heavy use of, the reflect package. // // Since the intent is to provide runtime services for the Liquid expression interpreter, // this package does not implement "generic" generics. // It attempts to implement Liquid semantics (which are largely Ruby semantics). package values
true
ba178ef5be88e2eca31c066981e77bb19d711bf3
Go
guang19860922/golang-pratice
/basic-io.go
UTF-8
529
3.8125
4
[]
no_license
[]
no_license
package main import "fmt" func main(){ // fmt.Println(3, "Hello", true) /* var x int fmt.Println("請輸入一個數字") fmt.Scanln(&x) fmt.Println(x) */ /* var x, y int fmt.Print("請輸入第一個數字") fmt.Scanln(&x) fmt.Print("請輸入第二個數字") fmt.Scanln(&y) var result int = x + y fmt.Print(result) */ var x, y int fmt.Println("請輸入兩個數字用空格隔開") fmt.Scanln(&x, &y) var result int = x + y fmt.Print(result) if true { fmt.Println("Yes") } else{ fmt.Println("NO") } }
true
07cccb86aa7ec987c90de59027c2e977d6bf4779
Go
ECAllen/debatehub
/actions/hashtags.go
UTF-8
5,971
2.765625
3
[]
no_license
[]
no_license
package actions import ( "github.com/ECAllen/debatehub/models" "github.com/gobuffalo/buffalo" "github.com/markbates/pop" "github.com/pkg/errors" ) // This file is generated by Buffalo. It offers a basic structure for // adding, editing and deleting a page. If your model is more // complex or you need more than the basic implementation you need to // edit this file. // Following naming logic is implemented in Buffalo: // Model: Singular (Hashtag) // DB Table: Plural (hashtags) // Resource: Plural (Hashtags) // Path: Plural (/hashtags) // View Template Folder: Plural (/templates/hashtags/) // HashtagsResource is the resource for the hashtag model type HashtagsResource struct { buffalo.Resource } // List gets all Hashtags. This function is mapped to the path // GET /hashtags func (v HashtagsResource) List(c buffalo.Context) error { // Get the DB connection from the context tx := c.Value("tx").(*pop.Connection) hashtags := &models.Hashtags{} // Paginate results. Params "page" and "per_page" control pagination. // Default values are "page=1" and "per_page=20". q := tx.PaginateFromParams(c.Params()) // You can order your list here. Just change err := q.All(hashtags) // to: // err := q.Order("created_at desc").All(hashtags) if err != nil { return errors.WithStack(err) } // Make Hashtags available inside the html template c.Set("hashtags", hashtags) // Add the paginator to the context so it can be used in the template. c.Set("pagination", q.Paginator) return c.Render(200, r.HTML("hashtags/index.html")) } // Show gets the data for one Hashtag. This function is mapped to // the path GET /hashtags/{hashtag_id} func (v HashtagsResource) Show(c buffalo.Context) error { // Get the DB connection from the context tx := c.Value("tx").(*pop.Connection) // Allocate an empty Hashtag hashtag := &models.Hashtag{} // To find the Hashtag the parameter hashtag_id is used. err := tx.Find(hashtag, c.Param("hashtag_id")) if err != nil { return errors.WithStack(err) } // Make hashtag available inside the html template c.Set("hashtag", hashtag) return c.Render(200, r.HTML("hashtags/show.html")) } // New renders the form for creating a new Hashtag. // This function is mapped to the path GET /hashtags/new func (v HashtagsResource) New(c buffalo.Context) error { // Make hashtag available inside the html template c.Set("hashtag", &models.Hashtag{}) return c.Render(200, r.HTML("hashtags/new.html")) } // Create adds a Hashtag to the DB. This function is mapped to the // path POST /hashtags func (v HashtagsResource) Create(c buffalo.Context) error { // Allocate an empty Hashtag hashtag := &models.Hashtag{} // Bind hashtag to the html form elements err := c.Bind(hashtag) if err != nil { return errors.WithStack(err) } // Get the DB connection from the context tx := c.Value("tx").(*pop.Connection) // Validate the data from the html form verrs, err := tx.ValidateAndCreate(hashtag) if err != nil { return errors.WithStack(err) } if verrs.HasAny() { // Make hashtag available inside the html template c.Set("hashtag", hashtag) // Make the errors available inside the html template c.Set("errors", verrs) // Render again the new.html template that the user can // correct the input. return c.Render(422, r.HTML("hashtags/new.html")) } // If there are no errors set a success message c.Flash().Add("success", "Hashtag was created successfully") // and redirect to the hashtags index page return c.Redirect(302, "/hashtags/%s", hashtag.ID) } // Edit renders a edit form for a hashtag. This function is // mapped to the path GET /hashtags/{hashtag_id}/edit func (v HashtagsResource) Edit(c buffalo.Context) error { // Get the DB connection from the context tx := c.Value("tx").(*pop.Connection) // Allocate an empty Hashtag hashtag := &models.Hashtag{} err := tx.Find(hashtag, c.Param("hashtag_id")) if err != nil { return errors.WithStack(err) } // Make hashtag available inside the html template c.Set("hashtag", hashtag) return c.Render(200, r.HTML("hashtags/edit.html")) } // Update changes a hashtag in the DB. This function is mapped to // the path PUT /hashtags/{hashtag_id} func (v HashtagsResource) Update(c buffalo.Context) error { // Get the DB connection from the context tx := c.Value("tx").(*pop.Connection) // Allocate an empty Hashtag hashtag := &models.Hashtag{} err := tx.Find(hashtag, c.Param("hashtag_id")) if err != nil { return errors.WithStack(err) } // Bind Hashtag to the html form elements err = c.Bind(hashtag) if err != nil { return errors.WithStack(err) } verrs, err := tx.ValidateAndUpdate(hashtag) if err != nil { return errors.WithStack(err) } if verrs.HasAny() { // Make hashtag available inside the html template c.Set("hashtag", hashtag) // Make the errors available inside the html template c.Set("errors", verrs) // Render again the edit.html template that the user can // correct the input. return c.Render(422, r.HTML("hashtags/edit.html")) } // If there are no errors set a success message c.Flash().Add("success", "Hashtag was updated successfully") // and redirect to the hashtags index page return c.Redirect(302, "/hashtags/%s", hashtag.ID) } // Destroy deletes a hashtag from the DB. This function is mapped // to the path DELETE /hashtags/{hashtag_id} func (v HashtagsResource) Destroy(c buffalo.Context) error { // Get the DB connection from the context tx := c.Value("tx").(*pop.Connection) // Allocate an empty Hashtag hashtag := &models.Hashtag{} // To find the Hashtag the parameter hashtag_id is used. err := tx.Find(hashtag, c.Param("hashtag_id")) if err != nil { return errors.WithStack(err) } err = tx.Destroy(hashtag) if err != nil { return errors.WithStack(err) } // If there are no errors set a flash message c.Flash().Add("success", "Hashtag was destroyed successfully") // Redirect to the hashtags index page return c.Redirect(302, "/hashtags") }
true
b8d27c49ed60a93ad278c247731100d969fc2b64
Go
lab259/go-migration
/target_psql_test.go
UTF-8
4,546
2.828125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package migration_test import ( "database/sql" "fmt" "time" "github.com/lib/pq" "github.com/lab259/go-migration" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func getDB() (*sql.DB, error) { db, err := sql.Open("postgres", "dbname=postgres user=postgres password=postgres host=localhost sslmode=disable") if err != nil { return nil, err } return db, nil } var _ = Describe("PostgreSQLTarget", func() { var ( db *sql.DB m1, m2, m3, m4, m5 *migration.DefaultMigration source *migration.CodeSource ) BeforeEach(func() { d, err := getDB() Expect(err).ToNot(HaveOccurred()) db = d // Drops the _migrations table _, err = db.Exec(fmt.Sprintf(`DROP TABLE IF EXISTS %s`, pq.QuoteIdentifier(migration.DefaultMigrationTable))) Expect(err).ToNot(HaveOccurred()) source = migration.NewCodeSource() baseTime := time.Date(2000, 0, 0, 0, 0, 0, 0, time.UTC) m1 = migration.NewMigration(baseTime, "Migration 1") m2 = migration.NewMigration(baseTime.Add(time.Second), "Migration 2") m3 = migration.NewMigration(baseTime.Add(time.Hour), "Migration 3") m4 = migration.NewMigration(baseTime.Add(time.Hour*24), "Migration 4") m5 = migration.NewMigration(baseTime.Add(time.Hour*24*10), "Migration 5") source.Register(m1) source.Register(m2) source.Register(m3) source.Register(m4) source.Register(m5) }) AfterEach(func() { db.Close() db = nil }) It("should return a new instance of a MongoDBTarget", func() { target := migration.NewPostgreSQLTarget(db) Expect(target).NotTo(BeNil()) }) It("should add migrations to the execution list", func() { target := migration.NewPostgreSQLTarget(db) target.AddMigration(migration.NewSummary(m1)) target.AddMigration(migration.NewSummary(m2)) target.AddMigration(migration.NewSummary(m5)) migrations := make([]*migrationFromDB, 0, 3) rows, err := db.Query(fmt.Sprintf(`SELECT id FROM %s ORDER BY id`, pq.QuoteIdentifier(migration.DefaultMigrationTable))) Expect(err).ToNot(HaveOccurred()) defer rows.Close() for rows.Next() { var id time.Time Expect(rows.Scan(&id)).To(Succeed()) migrations = append(migrations, &migrationFromDB{id}) } Expect(rows.Err()).ToNot(HaveOccurred()) Expect(migrations).To(HaveLen(3)) Expect(migrations[0].ID).To(Equal(m1.GetID())) Expect(migrations[1].ID).To(Equal(m2.GetID())) Expect(migrations[2].ID).To(Equal(m5.GetID())) }) It("should return NoVersion when there is no migrations ran", func() { target := migration.NewPostgreSQLTarget(db) version, err := target.Version() Expect(err).ToNot(HaveOccurred()) Expect(version).To(Equal(migration.NoVersion)) }) It("should return the current version", func() { target := migration.NewPostgreSQLTarget(db) target.AddMigration(migration.NewSummary(m1)) target.AddMigration(migration.NewSummary(m2)) target.AddMigration(migration.NewSummary(m5)) version, err := target.Version() Expect(err).ToNot(HaveOccurred()) Expect(version).To(Equal(m5.GetID())) }) It("should return the current version with an arbitrary addition of migrations", func() { target := migration.NewPostgreSQLTarget(db) target.AddMigration(migration.NewSummary(m5)) target.AddMigration(migration.NewSummary(m3)) target.AddMigration(migration.NewSummary(m1)) version, err := target.Version() Expect(err).ToNot(HaveOccurred()) Expect(version).To(Equal(m5.GetID())) }) It("should return the current version with an arbitrary addition of migrations", func() { target := migration.NewPostgreSQLTarget(db) target.AddMigration(migration.NewSummary(m5)) target.AddMigration(migration.NewSummary(m3)) target.AddMigration(migration.NewSummary(m1)) migrations, err := target.MigrationsExecuted() Expect(err).ToNot(HaveOccurred()) Expect(migrations).To(HaveLen(3)) Expect(migrations[0]).To(Equal(m1.GetID())) Expect(migrations[1]).To(Equal(m3.GetID())) Expect(migrations[2]).To(Equal(m5.GetID())) }) It("should remove a migration from the database", func() { target := migration.NewPostgreSQLTarget(db) target.AddMigration(migration.NewSummary(m5)) target.AddMigration(migration.NewSummary(m3)) target.AddMigration(migration.NewSummary(m1)) err := target.RemoveMigration(migration.NewSummary(m3)) Expect(err).NotTo(HaveOccurred()) migrations, err := target.MigrationsExecuted() Expect(err).ToNot(HaveOccurred()) Expect(migrations).To(HaveLen(2)) Expect(migrations[0]).To(Equal(m1.GetID())) Expect(migrations[1]).To(Equal(m5.GetID())) }) })
true
365ff586e7e1a7da6a6eae669a5dcf4317e26b82
Go
gford1000/factoryExample
/exemplars/new_instance.go
UTF-8
836
3.40625
3
[]
no_license
[]
no_license
package exemplars import ( "crypto/sha256" "fmt" "github.com/gford1000/factory" "reflect" ) // Creates an Exemplar that can create new instances of the // supplied srcPtr Type. srcPtr must be a pointer to the Type. func NewInstanceExemplar(srcPtr interface{}) factory.Exemplar { typ := reflect.TypeOf(srcPtr) if typ.Kind() != reflect.Ptr { panic("Should be a pointer") } typ = typ.Elem() return &nie{ typ: typ, h: fmt.Sprintf("%x", sha256.Sum256([]byte(typ.String()))), } } // Hidden class, implements Exemplar type nie struct { typ reflect.Type h string } func (n *nie) Hash() string { return n.h } func (n *nie) Implements(t reflect.Type) bool { return reflect.TypeOf(reflect.New(n.typ).Interface()).Implements(t) } func (n *nie) GetInstance() interface{} { return reflect.New(n.typ).Interface() }
true
03fde28f4952b096a174cf92cc07f572ac75e596
Go
joker-bai/rboot
/robot.go
UTF-8
7,481
2.546875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package rboot import ( "fmt" "os" "os/signal" "runtime" "strconv" "strings" "sync" "syscall" "time" "github.com/fatih/color" "github.com/sirupsen/logrus" ) const ( rbootLogo = ` =================================================================== * ________ ____ ____ ____ ______ ________ ____ ______ * * ___/ __ \/ __ )/ __ \/ __ \/_ __/ ___/ __ )/ __ \/_ __/ * * __/ /_/ / __ / / / / / / / / / __/ __ / / / / / / * * _/ _ _/ /_/ / /_/ / /_/ / / / _/ /_/ / /_/ / / / * * /_/ |_/_____/\____/\____/ /_/ /_____/\____/ /_/ * * * * Powerful and Happy * =================================================================== ` version = "2.0.1" ) var defaultCachePath = ".data" // Robot 是 rboot 的一个实例,它包含了聊天转接器,规则处理器,缓存器,路由适配器和消息的进出通道 type Robot struct { // 路由,支持脚本自定义添加新路由 Router *Router // 缓存 Brain Brain // 钩子 Hooks Hooks // 缓存文件夹 CachePath string // 调试信息 Debug bool // 终端 adapter Adapter // 传入消息 inputChan chan *Message // 传出消息 outputChan chan *Message // 规则匹配器 rule Rule // 操作系统信号 signalChan chan os.Signal } // New 获取一个Robot实例, func New() *Robot { bot := &Robot{ Hooks: make(Hooks), inputChan: make(chan *Message), outputChan: make(chan *Message), signalChan: make(chan os.Signal), rule: new(Regex), } bot.CachePath = defaultCachePath if len(os.Getenv("CACHE_PATH")) > 0 { bot.CachePath = os.Getenv("CACHE_PATH") } debug, _ := strconv.ParseBool(os.Getenv("DEBUG")) bot.Debug = debug bot.Router = newRouter() // 初始化 bot.initialize() return bot } var processOnce sync.Once // process 消息处理函数 func process(bot *Robot) { processOnce.Do(func() { // 监听传入消息 for in := range bot.inputChan { go func(bot *Robot, msg *Message) { defer func() { if r := recover(); r != nil { logrus.WithFields(logrus.Fields{ "mod": "rboot", "msg": msg, }).Errorf("panic recovered when parsing message: %#v. \nPanic: %v", msg, r) } }() if msg.From == "" { msg.From = "rboot" } if msg.To == "" { msg.To = "rboot" } if msg.Time.IsZero() { msg.Time = time.Now() } if msg.Channel == "" { msg.Channel = GetMsgChannel(msg.From, msg.To) } // 处理消息前的Hook bot.fireHooks(HOOK_BEFORE_INCOMING, msg) // 匹配消息 if plug, rule, args, ok := bot.matchPlugin(strings.TrimSpace(msg.String())); ok { if bot.Debug { logrus.Debugf("- 插件: %s\n- 规则: %s\n- 参数: %v\n\n", plug, rule, args[1:]) } // 获取插件执行函数 action, err := DirectivePlugin(plug) if err != nil { logrus.WithFields(logrus.Fields{ "mod": "rboot", "plug": plug, "ruleset": rule, "msg": msg, }).WithError(err).Error("listen: directive plugin error") } msg.Header.Set("rule", rule) msg.Header["args"] = args // 执行脚本, 附带ctx, 并获取输出 response := action(bot, msg) for _, resp := range response { // 将消息发送到 outputChan // 指定输出消息的接收者 resp.From = msg.To resp.To = msg.From resp.Channel = msg.Channel if msg.KeepHeader { for hn, hv := range msg.Header { if len(resp.Header[hn]) <= 0 { resp.Header[hn] = hv } } } if bot.Debug { logrus.Debugf("\nOutgoing: \n- 类型: %s \n- 接收人: %v\n- 抄送: %v\n- 发送人: %v\n- 内容: %s\n\n", resp.Header.Get("MsgType"), resp.To, resp.Cc(), resp.From, resp) } // send ... bot.outputChan <- resp // 如果存在抄送人,将消息抄送给对方 if len(resp.Cc()) > 0 { for _, cc := range resp.Cc() { resp.To = cc bot.outputChan <- resp } } // 处理消息后的Hook bot.fireHooks(HOOK_AFTER_OUTGOING, resp) } } }(bot, in) } }) } // Go 皮皮虾,我们走~~~~~~~~~ func (bot *Robot) Go() { fmt.Println("Rboot Version ", version) fmt.Println("皮皮虾,我们走~~~~~~~") // 开启web服务 go bot.Router.run() // 消息处理 go process(bot) signal.Notify(bot.signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP) stop := false for !stop { select { case sig := <-bot.signalChan: switch sig { case syscall.SIGINT, syscall.SIGTERM: stop = true } } } signal.Stop(bot.signalChan) bot.Stop() } // Stop 皮皮虾,快停下~~~~~~~~~ func (bot *Robot) Stop() { runtime.SetFinalizer(bot, nil) fmt.Println("皮皮虾,快停下~~~~~~~~") os.Exit(0) } // Incoming 获取传入消息通道 func (bot *Robot) Incoming() chan *Message { return bot.inputChan } // Outgoing 发送消息 func (bot *Robot) Outgoing(msg *Message) { bot.outputChan <- msg } // SendText 发送文本消息 func (bot *Robot) SendText(text string, to string) { msg := NewMessage(text) msg.To = to bot.outputChan <- msg } // SetBrain 设置储存器 func (bot *Robot) SetBrain(brain Brain) { bot.Brain = brain } // AddHook 新增钩子 func (bot *Robot) AddHook(hook Hook) { bot.Hooks.Add(hook) } // fireHooks 执行钩子 func (bot *Robot) fireHooks(typ int, msg *Message) { err := bot.Hooks.Fire(typ, bot, msg) if err != nil { logrus.WithFields(logrus.Fields{ "mod": "rboot", "type": hookType[typ], "msg": msg, }).WithError(err).Error("fireHooks: fire hooks failed") } } // matchScript 匹配消息内容,获取相应的脚本名称(script), 对应规则名称(matchRule), 提取的匹配内容(matchArgs) // 当消息不匹配时,matched 返回false func (bot *Robot) matchPlugin(msg string) (script, matchRule string, matchArgs []string, matched bool) { for script, rules := range ruleset { for m, r := range rules { if match, ok := bot.rule.Match(r, msg); ok { return script, m, match, true } } } return ``, ``, nil, false } // initialize 初始化 Robot func (bot *Robot) initialize() { // 指定消息提供者,如果配置文件没有指定,则默认使用 cli adpName := os.Getenv(`ROBOT_ADAPTER`) // 默认使用 cli if adpName == "" { fmt.Println("未指定 adapter,默认使用 cli") adpName = "cli" } fmt.Println("已连接适配器 ", adpName) adp, err := DetectAdapter(adpName) if err != nil { panic(`Detect adapter error: ` + err.Error()) } // 获取转接器实例 adapter := adp(bot) // 建立消息通道连接 bot.inputChan = adapter.Incoming() bot.outputChan = adapter.Outgoing() // 储存器 brainName := os.Getenv(`ROBOT_BRAIN`) // 默认使用 memory if brainName == "" { brainName = "bolt" } brain, err := DetectBrain(brainName) if err != nil { panic(`Detect brain error: ` + err.Error()) } bot.Brain = brain() // 监听 http 入站消息的 ResultFul API bot.Router.HandleFunc("/incoming", bot.listenIncoming).Methods("POST") bot.Router.HandleFunc("/outgoing", bot.listenOutgoing).Methods("POST") } func init() { _, _ = color.New(color.FgGreen).Fprintln(os.Stdout, rbootLogo) // 加载配置 _ = LoadEnv() }
true
4d9cd501a10733e76fa4f142c7f877404eed232b
Go
Asutorufa/leetcode_practice
/剑指 Offer 32 - I. 从上到下打印二叉树/Offer 32 - I.go
UTF-8
1,115
3.796875
4
[]
no_license
[]
no_license
package main /** 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回: [3,9,20,15,7] 提示: 节点总数 <= 1000 */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 剑指Offer 28写过了 就不测试了 func levelOrder(root *TreeNode) (res []int) { que := newQueue() que.push(root) for que.size() != 0 { x := que.pop() if x != nil { res = append(res, x.Val) que.push(x.Left) que.push(x.Right) } } return res } type queue struct { qu []*TreeNode } func newQueue() *queue { return &queue{ qu: []*TreeNode{}, } } func (q *queue) pop() *TreeNode { if len(q.qu) == 0 { return &TreeNode{} } x := q.qu[0] q.qu = q.qu[1:] return x } func (q *queue) push(x *TreeNode) { q.qu = append(q.qu, x) } func (q *queue) size() int { return len(q.qu) } func main() {}
true
8b48d661d61dd892608d8c7141d5cbdab1fd67c5
Go
eatPorkAndSeePigRun/SingleProcessingOfLargeFile
/src/handleFile.go
UTF-8
3,323
3.3125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "bufio" "os" ) const readFileNum = 14 const bufSize = 100 * (1 << 30) / readFileNum // 分次I/O读取大文件,并对每次读取的词调用相关函数维护位图和队列 func HandleLargeFile(filePath string, hashFunc []func(string) int) { largeFile, err := os.Open(filePath) defer largeFile.Close() if err != nil { panic(err) } rd := bufio.NewReaderSize(largeFile, bufSize) for { word, err := rd.ReadString('\n') if err != nil { panic(err) } if len(word) == 0 { break } handleWord(word, hashFunc) } } // 处理每个词 // 对于位图bitmap1,实际上是一个布隆算法原理,它相当于一个hashset,存放着大文件中词 // 对于位图bitmap2,也是一个布隆算法原理,它也相当于一个hashset,存放大文件中重复出现的词 // 它进行的流程是: // 如果是第一次访问该词,则将bitmap1的相应比特位置1,加入队列,快爆内存时则将队列写到硬盘,清空队列内存 // 如果是重复访问,则将bitmap2的相应比特位置1,从队列出队 func handleWord(word string, hashFunc []func(string) int) { if hasWord(bitmap1, word, hashFunc) { addWord(bitmap2, word, hashFunc) popFromDueue(word) } else { addWord(bitmap1, word, hashFunc) pushToDueue(word) if len(dueue) > bufSize/100 { writeToDisk() } } } // 将队列数据存储到内存 func writeToDisk() { f, _ := os.OpenFile("spare.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) defer f.Close() for _, word := range dueue { _, err := f.Write([]byte(word + "\r\n")) if err != nil { panic(err) } } dueue = dueue[0:0] } func pushToDueue(word string) { dueue = append(dueue, word) } func popFromDueue(word string) { for i := 0; i < len(dueue); { if dueue[i] == word { dueue = append(dueue[:i], dueue[i+1:]...) } else { i++ } } } // 用布隆过滤器算法查询元素是否访问过 func hasWord(bitmap *BitMap, word string, hashFunc []func(string) int) bool { for i := 0; i < len(hashFunc); i++ { num := hashFunc[i](word) if !bitmap.IsExist(uint(num % bitmap.max)) { return false } } return true } // 维护布隆过滤器的位图,把访问过的元素的哈希函数组响应哈希值的比特位置1 func addWord(bitmap *BitMap, word string, hashFunc []func(string) int) { for i := 0; i < len(hashFunc); i++ { num := hashFunc[i](word) bitmap.Add(uint(num % bitmap.max)) } } // 查询第一不重复的词 // 先找出内存中队列的最早不重复词和硬盘中的最早不重复词,再比较可能哪边更早 // 存在则返回词,不存在则返回空 func FindFirstNonRepetitiveWord(hashFunc []func(string) int) (string, bool) { word := "" // 当前内存中的最早不重复词 if dueue != nil { word = dueue[0] } largeFile, err := os.Open("spare.txt") defer largeFile.Close() if err != nil { panic(err) } // 遍历硬盘 rd := bufio.NewReader(largeFile) for { tmpWord, err := rd.ReadString('\n') if err != nil { panic(err) } if len(tmpWord) == 0 { break } if hasWord(bitmap2, tmpWord, hashFunc) { continue } else { word = tmpWord // 找到硬盘中最早不重复词,则终止循环 break } } // 返回结果 if word != "" { return word, true } else { return "", false } }
true
7d100b2d754264527de7b493c2d945a64048d935
Go
sujiny-tech/preparing-for-coding-test
/programmers/level1/SortIntegers_DescendingOrder.go
UTF-8
923
3.140625
3
[]
no_license
[]
no_license
package main import ( "fmt" "math" "strconv" ) func solution(n int64) int64 { str_n := strconv.Itoa(int(n)) l_str_n := len(str_n) //자릿수 num := int64(math.Pow(10, float64(l_str_n-1))) arr := make([]int64, l_str_n) i := 0 for num >= 1 { //자릿수에 해당하는 수(0~9) 배열에 넣기 arr[i] = n / num n = n - (num * arr[i]) num = num / 10 i++ } fmt.Println(arr) temp := int64(0) for i := 0; i < l_str_n; i++ { //내림차순 Sort for j := i + 1; j < l_str_n; j++ { if arr[j] > arr[i] { temp = arr[i] arr[i] = arr[j] arr[j] = temp } } } fmt.Println(arr) i = 0 answer := int64(0) num = int64(math.Pow(10, float64(l_str_n-1))) for i < l_str_n { //정수로 바꾸기 answer = answer + (arr[i] * num) i++ num = num / 10 } return answer } func main() { first := solution(118372) fmt.Println(first) }
true
9945a3140443ab72523b4d591342dc1efc166bcf
Go
go-courier/expression
/error.go
UTF-8
455
2.703125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package expression func NewInvalidExpression(msg string) *InvalidExpression { return &InvalidExpression{msg: msg} } type InvalidExpression struct { msg string } func (e *InvalidExpression) Error() string { return "invalid expression: " + e.msg } func NewRuntimeError(msg string) *RuntimeError { return &RuntimeError{msg: msg} } type RuntimeError struct { msg string } func (e *RuntimeError) Error() string { return "runtime error: " + e.msg }
true
2d24a5137eca8cfffa313455abf570fbb41ed733
Go
ramailh/test-skill
/fetch/util/transformator/transformator_test.go
UTF-8
1,461
3.1875
3
[]
no_license
[]
no_license
package transformator_test import ( "testing" "github.com/ramailh/backend/fetch/util/transformator" ) func TestInterfacesToInts(t *testing.T) { testCases := []struct { desc string input []interface{} output []int }{ { desc: "test 1", input: []interface{}{1, 2, 3, 4, 5}, output: []int{1, 2, 3, 4, 5}, }, { desc: "test 2", input: []interface{}{nil}, output: []int{}, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { ints := transformator.NewTransformator().FromInterfaces(tC.input).ToInts() for i := 0; i < len(ints); i++ { if ints[i] != tC.output[i] { t.Error("error: output not matched") } } t.Logf("success: %v", ints) }) } } func TestStringsToInts(t *testing.T) { testCases := []struct { desc string input []interface{} output []int }{ { desc: "test 1", input: []interface{}{"1", "2", "3", "4", "5"}, output: []int{1, 2, 3, 4, 5}, }, { desc: "test 2", input: []interface{}{nil}, output: []int{}, }, { desc: "test 3", input: []interface{}{"1", "2", " 3"}, output: []int{1, 2}, }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) { ints := transformator.NewTransformator().FromStrings(tC.input).ToInts() for i := 0; i < len(ints); i++ { if ints[i] != tC.output[i] { t.Error("error: output not matched") } } t.Logf("success: %v", ints) }) } }
true
b09618539c5949852691c984d48a14f39d490b62
Go
lzake/mymove
/pkg/handlers/errors.go
UTF-8
3,880
2.625
3
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
package handlers import ( "encoding/json" "net/http" "strings" "github.com/go-openapi/runtime" "github.com/go-openapi/runtime/middleware" "github.com/gobuffalo/validate" "github.com/pkg/errors" "go.uber.org/zap" "github.com/transcom/mymove/pkg/models" uploaderpkg "github.com/transcom/mymove/pkg/uploader" ) // ValidationErrorsResponse is a middleware.Responder for a set of validation errors type ValidationErrorsResponse struct { Errors map[string]string `json:"errors,omitempty"` } func newValidationErrorsResponse(errors map[string]string) *ValidationErrorsResponse { return &ValidationErrorsResponse{Errors: errors} } // WriteResponse to the client func (v *ValidationErrorsResponse) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(http.StatusBadRequest) json.NewEncoder(rw).Encode(v) } // ErrResponse collect errors and error codes type ErrResponse struct { Code int Err error } type clientMessage struct { Message string `json:"message"` } // ErrResponse creates ErrResponse with default headers values func newErrResponse(code int, err error) *ErrResponse { return &ErrResponse{Code: code, Err: err} } // WriteResponse to the client func (o *ErrResponse) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(o.Code) json.NewEncoder(rw).Encode(clientMessage{o.Err.Error()}) } // ResponseForError logs an error and returns the expected error type func ResponseForError(logger *zap.Logger, err error) middleware.Responder { // AddCallerSkip(1) prevents log statements from listing this file and func as the caller skipLogger := logger.WithOptions(zap.AddCallerSkip(1)) switch errors.Cause(err) { case models.ErrFetchNotFound: skipLogger.Debug("not found", zap.Error(err)) return newErrResponse(http.StatusNotFound, err) case models.ErrFetchForbidden: skipLogger.Debug("forbidden", zap.Error(err)) return newErrResponse(http.StatusForbidden, err) case models.ErrUserUnauthorized: skipLogger.Debug("unauthorized", zap.Error(err)) return newErrResponse(http.StatusUnauthorized, err) case uploaderpkg.ErrZeroLengthFile: skipLogger.Debug("uploaded zero length file", zap.Error(err)) return newErrResponse(http.StatusBadRequest, err) case models.ErrInvalidPatchGate: skipLogger.Debug("invalid patch gate", zap.Error(err)) return newErrResponse(http.StatusBadRequest, err) case models.ErrInvalidTransition: skipLogger.Debug("invalid transition", zap.Error(err)) return newErrResponse(http.StatusBadRequest, err) default: skipLogger.Error("unexpected error", zap.Error(err)) return newErrResponse(http.StatusInternalServerError, err) } } // ResponseForVErrors checks for validation errors func ResponseForVErrors(logger *zap.Logger, verrs *validate.Errors, err error) middleware.Responder { skipLogger := logger.WithOptions(zap.AddCallerSkip(1)) if verrs.HasAny() { skipLogger.Error("Encountered validation error", zap.Any("Validation errors", verrs.String())) errors := make(map[string]string) for _, key := range verrs.Keys() { errors[key] = strings.Join(verrs.Get(key), " ") } return newValidationErrorsResponse(errors) } return ResponseForError(skipLogger, err) } // ResponseForCustomErrors checks for custom errors and returns a custom response body message func ResponseForCustomErrors(logger *zap.Logger, err error, httpStatus int) middleware.Responder { skipLogger := logger.WithOptions(zap.AddCallerSkip(1)) skipLogger.Error("Encountered error", zap.Error(err)) return newErrResponse(httpStatus, err) } // ResponseForConflictErrors checks for conflict errors func ResponseForConflictErrors(logger *zap.Logger, err error) middleware.Responder { skipLogger := logger.WithOptions(zap.AddCallerSkip(1)) skipLogger.Error("Encountered conflict error", zap.Error(err)) return newErrResponse(http.StatusConflict, err) }
true
3fe3338b3edb775b74ee6996de54d5ed3112a3e1
Go
sarisia/deepclone
/cmd/deepclone/main.go
UTF-8
1,598
2.640625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "context" "flag" "log" "net/http" _ "net/http/pprof" "os" "os/signal" "time" "github.com/sarisia/deepclone" ) func main() { depth := flag.Int("depth", 1, "fetch depth") conns := flag.Int("conn", 16, "max concurrent connections") dir := flag.String("dir", "content", "directory to save contents") debug := flag.Bool("debug", false, "enable pprof debug endpoint") flag.Parse() url := flag.Arg(0) if url == "" { log.Println("No URL is provided.") return } if *debug { go debugRoutine() } start := time.Now() deepclone.SetLoggerFlags() // this will fuck the app and it is golang's bug // https://github.com/golang/go/issues/34941 // so comment out this in 1.13 or lower deepclone.SetMaxConnsPerHost(*conns) deepclone.SetDirectory(*dir) log.Println("Starting...") log.Printf("Max concurrent connections: %d\n", *conns) log.Printf("Fetch depth: %d\n", *depth) sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt, os.Kill) ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan struct{}) go deepclone.Perform(ctx, url, *depth, done) // 虚無じゃん // https://qiita.com/cia_rana/items/a2c3e1609bd25a5c5596 // https://golang.org/ref/spec#Break_statements Finish: for { select { case <-sig: log.Printf("Interrupted...") cancel() case <-done: log.Println("Done") break Finish } } log.Printf("Finish: %s\n", time.Since(start)) } func debugRoutine() { log.Println("pprof debug endpoint: localhost:6611") log.Println(http.ListenAndServe("localhost:6611", nil)) }
true
891fff53ffa7d23c086503a7ba7c4030c9ec8a74
Go
chengzheng007/algorithm_exercise
/leetcode/650.2-Keys-Keyboard.go
UTF-8
851
3.53125
4
[]
no_license
[]
no_license
// 不同于以往通过加减实现的动态规划,这里需要乘除法来计算 // 位置,因为粘贴操作是倍数增加的。我们使用一个一维数组dp, // 其中位置i表示延展到长度i的最少操作次数。对于每个位置 // j,如果j可以被i整除,那么长度i就可以由长度j操作得到,其 // 操作次数等价于把一个长度为1的A延展到长度为i/j。因此我们 // 可以得到递推公式dp[i] = dp[j] + dp[i/j] func minSteps(n int) int { if n <= 1 { return 0 } dp := make([]int, n+1) h := int(math.Sqrt(float64(n))) for i := 2; i <= n; i++ { dp[i] = i for j := 2; j <= h; j++ { if i%j == 0 { // i能整除j, dp[i] = dp[j]+dp[i/j] break } } } return dp[n] }
true
8c48e60a1f0c43237f5227161d82da88d6d2df27
Go
bruntonspall/adventofcode
/2019/day12/main.go
UTF-8
3,282
3.125
3
[]
no_license
[]
no_license
package main import ( "fmt" "regexp" "strconv" "strings" "github.com/bruntonspall/adventofcode/pkg" ) // A Coord3D represents a coordinate in 3 dimensions type Coord3D struct { X, Y, Z int } type Moon struct { Pos Coord3D Vel Coord3D } func (c Coord3D) String() string { return fmt.Sprintf("<x=%d, y=%d, z=%d>", c.X, c.Y, c.Z) } func (c Moon) String() string { return fmt.Sprintf("Pos=%v, Vel=%v", c.Pos, c.Vel) } func (c Coord3D) Add(v Coord3D) (r Coord3D) { return Coord3D{c.X + v.X, c.Y + v.Y, c.Z + v.Z} } func (c Coord3D) Gravity(t Coord3D) (v Coord3D) { if t.X > c.X { v.X = 1 } if t.X < c.X { v.X = -1 } if t.Y > c.Y { v.Y = 1 } if t.Y < c.Y { v.Y = -1 } if t.Z > c.Z { v.Z = 1 } if t.Z < c.Z { v.Z = -1 } return } var r = regexp.MustCompile(`(-?\d+)`) func Parse(in string) []Moon { moons := make([]Moon, 4) for i, line := range strings.Split(in, "\n") { moon := Coord3D{} items := strings.Split(line, ",") moon.X, _ = strconv.Atoi(strings.Trim(items[0], "<> xyz=")) moon.Y, _ = strconv.Atoi(strings.Trim(items[1], "<> xyz=")) moon.Z, _ = strconv.Atoi(strings.Trim(items[2], "<> xyz=")) moons[i] = Moon{moon, Coord3D{}} } return moons } func PrintMoons(moons []Moon) { for _, moon := range moons { fmt.Println(moon) } } func Step(moons []Moon) []Moon { for i := range moons { for j := range moons { if i != j { moons[i].Vel = moons[i].Vel.Add(moons[i].Pos.Gravity(moons[j].Pos)) } } } for i := range moons { moons[i].Pos = moons[i].Pos.Add(moons[i].Vel) } return moons } func TotalEnergy(moons []Moon) int { total := 0 for _, moon := range moons { pot := pkg.Abs(moon.Pos.X) + pkg.Abs(moon.Pos.Y) + pkg.Abs(moon.Pos.Z) kin := pkg.Abs(moon.Vel.X) + pkg.Abs(moon.Vel.Y) + pkg.Abs(moon.Vel.Z) total += pot * kin } return total } // GCD returns the greatest common divisor between a and b func GCD(a, b int) int { for b != 0 { a, b = b, a%b } return a } // LCM returns the lowest common multiple of a and b func LCM(a, b int) int { return a * b / GCD(a, b) } func findPeriod(moons []Moon) int { period := Coord3D{} steps := 0 for { moons = Step(moons) steps++ if period.X == 0 { if moons[0].Vel.X == 0 && moons[1].Vel.X == 0 && moons[2].Vel.X == 0 && moons[3].Vel.X == 0 { period.X = steps } } if period.Y == 0 { if moons[0].Vel.Y == 0 && moons[1].Vel.Y == 0 && moons[2].Vel.Y == 0 && moons[3].Vel.Y == 0 { period.Y = steps } } if period.Z == 0 { if moons[0].Vel.Z == 0 && moons[1].Vel.Z == 0 && moons[2].Vel.Z == 0 && moons[3].Vel.Z == 0 { period.Z = steps } } if period.X > 0 && period.Y > 0 && period.Z > 0 { return LCM(LCM(period.X, period.Y), period.Z) } } } // returns part1 and part2 func run(input string) (part1 string, part2 string) { moons := Parse(input) println("After 0 steps") PrintMoons(moons) for i := 0; i < 1000; i++ { moons = Step(moons) } println("After 1000 steps") PrintMoons(moons) println("Total energy: ", TotalEnergy(moons)) // Parse input and return output part1 = fmt.Sprintf("%d", TotalEnergy(moons)) // Parse input and return output moons = Parse(input) part2 = fmt.Sprintf("%d", findPeriod(moons)*2) return } func main() { pkg.Execute(run, nil, puzzle, true) }
true
f2d48ea92281b78eec95eeb732a7ca00061b3c34
Go
poommin2543/SA-63
/backend/controllers/medicalequipment_controller.go
UTF-8
6,028
2.953125
3
[]
no_license
[]
no_license
package controllers import ( "context" "fmt" "strconv" "github.com/gin-gonic/gin" "github.com/poommin2543/app/ent" "github.com/poommin2543/app/ent/medicalequipment" ) // MedicalequipmentController defines the struct for the medicalequipment controller type MedicalequipmentController struct { client *ent.Client router gin.IRouter } // CreateMedicalequipment handles POST requests for adding medicalequipment entities // @Summary Create medicalequipment // @Description Create medicalequipment // @ID create-medicalequipment // @Accept json // @Produce json // @Param medicalequipment body ent.MedicalEquipment true "Medicalequipment entity" // @Success 200 {object} ent.MedicalEquipment // @Failure 400 {object} gin.H // @Failure 500 {object} gin.H // @Router /medicalequipments [post] func (ctl *MedicalequipmentController) CreateMedicalequipment(c *gin.Context) { obj := ent.MedicalEquipment{} if err := c.ShouldBind(&obj); err != nil { c.JSON(400, gin.H{ "error": "medicalequipment binding failed", }) return } u, err := ctl.client.MedicalEquipment. Create(). SetName(obj.Name). Save(context.Background()) if err != nil { c.JSON(400, gin.H{ "error": "saving failed", }) return } c.JSON(200, u) } // GetMedicalequipment handles GET requests to retrieve a medicalequipment entity // @Summary Get a medicalequipment entity by ID // @Description get medicalequipment by ID // @ID get-medicalequipment // @Produce json // @Param id path int true "Medicalequipment ID" // @Success 200 {object} ent.MedicalEquipment // @Failure 400 {object} gin.H // @Failure 404 {object} gin.H // @Failure 500 {object} gin.H // @Router /medicalequipments/{id} [get] func (ctl *MedicalequipmentController) GetMedicalequipment(c *gin.Context) { id, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { c.JSON(400, gin.H{ "error": err.Error(), }) return } u, err := ctl.client.MedicalEquipment. Query(). Where(medicalequipment.IDEQ(int(id))). Only(context.Background()) if err != nil { c.JSON(404, gin.H{ "error": err.Error(), }) return } c.JSON(200, u) } // ListMedicalequipment handles request to get a list of medicalequipment entities // @Summary List medicalequipment entities // @Description list medicalequipment entities // @ID list-medicalequipment // @Produce json // @Param limit query int false "Limit" // @Param offset query int false "Offset" // @Success 200 {array} ent.MedicalEquipment // @Failure 400 {object} gin.H // @Failure 500 {object} gin.H // @Router /medicalequipments [get] func (ctl *MedicalequipmentController) ListMedicalequipment(c *gin.Context) { limitQuery := c.Query("limit") limit := 10 if limitQuery != "" { limit64, err := strconv.ParseInt(limitQuery, 10, 64) if err == nil { limit = int(limit64) } } offsetQuery := c.Query("offset") offset := 0 if offsetQuery != "" { offset64, err := strconv.ParseInt(offsetQuery, 10, 64) if err == nil { offset = int(offset64) } } medicalequipments, err := ctl.client.MedicalEquipment. Query(). Limit(limit). Offset(offset). All(context.Background()) if err != nil { c.JSON(400, gin.H{"error": err.Error()}) return } c.JSON(200, medicalequipments) } // DeleteMedicalequipment handles DELETE requests to delete a medicalequipment entity // @Summary Delete a medicalequipment entity by ID // @Description get medicalequipment by ID // @ID delete-medicalequipment // @Produce json // @Param id path int true "Medicalequipment ID" // @Success 200 {object} gin.H // @Failure 400 {object} gin.H // @Failure 404 {object} gin.H // @Failure 500 {object} gin.H // @Router /medicalequipments/{id} [delete] func (ctl *MedicalequipmentController) DeleteMedicalequipment(c *gin.Context) { id, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { c.JSON(400, gin.H{ "error": err.Error(), }) return } err = ctl.client.MedicalEquipment. DeleteOneID(int(id)). Exec(context.Background()) if err != nil { c.JSON(404, gin.H{ "error": err.Error(), }) return } c.JSON(200, gin.H{"result": fmt.Sprintf("ok deleted %v", id)}) } // UpdateMedicalequipment handles PUT requests to update a medicalequipment entity // @Summary Update a medicalequipment entity by ID // @Description update medicalequipment by ID // @ID update-medicalequipment // @Accept json // @Produce json // @Param id path int true "Medicalequipment ID" // @Param medicalequipment body ent.MedicalEquipment true "Medicalequipment entity" // @Success 200 {object} ent.MedicalEquipment // @Failure 400 {object} gin.H // @Failure 500 {object} gin.H // @Router /medicalequipments/{id} [put] func (ctl *MedicalequipmentController) UpdateMedicalequipment(c *gin.Context) { id, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { c.JSON(400, gin.H{ "error": err.Error(), }) return } obj := ent.MedicalEquipment{} if err := c.ShouldBind(&obj); err != nil { c.JSON(400, gin.H{ "error": "medicalequipment binding failed", }) return } obj.ID = int(id) u, err := ctl.client.MedicalEquipment. UpdateOne(&obj). Save(context.Background()) if err != nil { c.JSON(400, gin.H{"error": "update failed"}) return } c.JSON(200, u) } // NewMedicalequipmentController creates and registers handles for the medicalequipment controller func NewMedicalequipmentController(router gin.IRouter, client *ent.Client) *MedicalequipmentController { uc := &MedicalequipmentController{ client: client, router: router, } uc.register() return uc } // InitMedicalequipmentController registers routes to the main engine func (ctl *MedicalequipmentController) register() { medicalequipments := ctl.router.Group("/medicalequipments") medicalequipments.GET("", ctl.ListMedicalequipment) // CRUD medicalequipments.POST("", ctl.CreateMedicalequipment) medicalequipments.GET(":id", ctl.GetMedicalequipment) medicalequipments.PUT(":id", ctl.UpdateMedicalequipment) medicalequipments.DELETE(":id", ctl.DeleteMedicalequipment) }
true
ea42a08ca812afa00469737f88bff374d577df65
Go
mkobaly/devop
/jira/jira.go
UTF-8
6,495
2.796875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package jira import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "strings" "github.com/mkobaly/devop/config" ) //ApiError represents a set of error(s) that the rest api threw type ApiError struct { ErrorMessages []string `json:"errorMessages"` Errors interface{} `json:"errors"` } func (e ApiError) String() string { return strings.Join(e.ErrorMessages, " ") } type BaseFields struct { Id string `json:"id"` Self string `json:"self"` } type IssueLink struct { BaseFields Type map[string]string `json:"type"` InwardIssue Issue `json:"inwardIssue"` OutwardIssue Issue `json:"outwardIssue"` } type Issue struct { BaseFields Key string `json:"key"` Fields IssueFields `json:fields"` } type IssueFields struct { Summary string `json:"summary"` Progress IssueFieldProgress `json:"progress"` IssueType IssueType `json:"issuetype"` ResolutionDate interface{} `json:"resolutiondate"` Timespent interface{} `json:"timespent"` Creator IssueFieldCreator `json:"creator"` Created string `json:"created"` Updated string `json:"updated"` Labels []string `json:"labels"` Assignee IssueFieldCreator `json:"assignee"` Description interface{} `json:"description"` IssueLinks []IssueLink `json:"issueLinks"` Status IssueStatus `json:"status"` } type IssueFieldProgress struct { Progress int `json:"progress"` Total int `json:"total"` } type IssueFieldCreator struct { Self string `json:"self"` Name string `json:"name"` EmailAddress string `json:"emailAddress"` AvatarUrls map[string]string `json:"avatarUrls"` DisplayName string `json:"displayName"` Active bool `json:"active"` } type IssueType struct { BaseFields Description string `json:"description"` IconUrl string `json:"iconURL"` Name string `json:"name"` Subtask bool `json:"subtask"` } type IssueStatus struct { BaseFields Name string `json:"name"` } //New will create a new instance of Jira Rest API func New(credentials config.UserCredential) *RestAPI { return &RestAPI{credentials: credentials} //var api = new(RestAPI) //api.credentials = credentials //return api } // RestAPI wraps some basic rest calls to work with Jira type RestAPI struct { credentials config.UserCredential } // GetJiraRelease returns Epic information func (api *RestAPI) GetRelease(epicID string) ([]ReleaseItem, error) { results := []ReleaseItem{} issue, err := api.getIssue(epicID) if err != nil { return results, err } scanner := bufio.NewScanner(strings.NewReader(issue.Fields.Description.(string))) for scanner.Scan() { line := strings.ToLower(scanner.Text()) if strings.Contains(line, "/app#/projects") { parts := strings.Split(line, "/") results = append(results, ReleaseItem{Project: parts[5], Version: parts[7]}) } } return results, nil } func (api *RestAPI) CreateEpicNew(project string, summary string, projectItems []ProjectItem) (*Issue, error) { desc := convertToDescription(projectItems) i := issue{summary: summary, description: desc, project: project1{key: project}, issuetype: issuetype{name: "epic"}} b, _ := json.Marshal(i) issue, err := api.createIssue(bytes.NewReader(b)) return issue, err } //CreateEpic will create a new release epic in Jira func (api *RestAPI) CreateEpic(project string, summary string, releaseItems []ReleaseItem) (*Issue, error) { i := issue{summary: summary, project: project1{key: project}, issuetype: issuetype{name: "epic"}} b, _ := json.Marshal(i) issue, err := api.createIssue(bytes.NewReader(b)) return issue, err } func convertToDescription(pi []ProjectItem) string { desc := "..." for _, r := range pi { desc += fmt.Sprintf("%s|%s\r\n", r.Project, r.Branch) } return desc } func (api *RestAPI) DeleteIssue(issue *Issue) error { url := fmt.Sprintf("%s/issue/%s", api.credentials.URL, issue.Key) code, body := api.execRequest("DELETE", url, nil) if code != http.StatusNoContent { return handleJiraError(body) } return nil } func (api *RestAPI) createIssue(params io.Reader) (*Issue, error) { url := fmt.Sprintf("%s/issue", api.credentials.URL) code, body := api.execRequest("POST", url, params) if code == http.StatusCreated { response := make(map[string]string) err := json.Unmarshal(body, &response) if err != nil { return nil, err } return api.getIssue(response["key"]) } return nil, handleJiraError(body) } func (api *RestAPI) getIssue(issueKey string) (*Issue, error) { url := fmt.Sprintf("%s/issue/%s", api.credentials.URL, issueKey) code, body := api.execRequest("GET", url, nil) if code == http.StatusOK { var issue Issue err := json.Unmarshal(body, &issue) if err != nil { return nil, err } return &issue, nil } return nil, handleJiraError(body) } // ReleaseItem is a line item in the Jira Release (Epic) that should be deployed type ReleaseItem struct { Project string Version string } // ProjectItem represents a project and git branch type ProjectItem struct { Project string Branch string } func (api *RestAPI) execRequest(requestType, requestUrl string, data io.Reader) (int, []byte) { client := &http.Client{} req, err := http.NewRequest(requestType, requestUrl, data) if err != nil { panic(err) } req.Header.Add("Content-Type", "application/json") req.SetBasicAuth(api.credentials.Username, api.credentials.Password) resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } return resp.StatusCode, body } func handleJiraError(body []byte) error { errorAnswer := ApiError{} err := json.Unmarshal(body, &errorAnswer) if err != nil { return err } return errors.New(errorAnswer.String()) } type project1 struct { key string } type issuetype struct { name string } type issue struct { summary string description string project project1 issuetype issuetype } /* { "fields": { "project": { "key": "TEST" }, "summary": "REST ye merry gentlemen.", "description": "Creating of an issue using project keys and issue type names using the REST API", "issuetype": { "name": "Bug" } } } */
true
bc441a6073330ce452b98f8112ad212b7ab61075
Go
hieuphq/go-backend-example
/pkg/app/app.go
UTF-8
2,557
2.625
3
[]
no_license
[]
no_license
package app import ( "context" "fmt" "log" "net/http" "os" "os/signal" "strings" "github.com/dwarvesf/gerr" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/hieuphq/backend-example/pkg/config" "github.com/hieuphq/backend-example/pkg/handler" "github.com/hieuphq/backend-example/pkg/middleware" "github.com/hieuphq/backend-example/pkg/validator" "github.com/hieuphq/backend-example/translation" ) // App api app instance type App struct { cfg config.Config l gerr.Log th translation.Helper } // LoadApp load config and init app func LoadApp() *App { cls := config.DefaultConfigLoaders() cfg := config.LoadConfig(cls) l := gerr.NewSimpleLog() th := translation.NewTranslatorHelper() return &App{ cfg: cfg, l: l, th: th, } } // Run api app func (a App) Run() { router := a.setupRouter() quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) gerr.SetCleanPathFunc(func(path string) string { projName := "go-backend-example/" startIdx := strings.Index(path, projName) if startIdx >= 0 { path = path[startIdx+len(projName):] } return path }) srv := &http.Server{ Addr: fmt.Sprintf(":%s", a.cfg.Port), Handler: router, } go func() { // service connections a.l.Info("listening on ", a.cfg.Port) if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } quit <- os.Interrupt }() select { case <-quit: a.l.Info("Shutdown Server ...") ctx, cancel := context.WithTimeout(context.Background(), a.cfg.GetShutdownTimeout()) defer cancel() if err := srv.Shutdown(ctx); err != nil { a.l.Error("Server Shutdown:", err) } a.l.Info("Server exiting") } } func (a App) setupRouter() *gin.Engine { r := gin.New() binding.Validator = validator.NewStructValidator(a.th) r.Use(middleware.NewLogDataMiddleware(a.cfg.ServiceName, a.cfg.Env)) r.Use(cors.New( cors.Config{ AllowOrigins: a.cfg.GetCORS(), AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"}, AllowHeaders: []string{"Origin", "Host", "Content-Type", "Content-Length", "Accept-Encoding", "Accept-Language", "Accept", "X-CSRF-Token", "Authorization", "X-Requested-With", "X-Access-Token"}, ExposeHeaders: []string{"MeAllowMethodsntent-Length"}, AllowCredentials: true, }, )) h := handler.NewHandler(a.cfg, a.l, a.th) // handlers r.GET("/healthz", h.Healthz) r.POST("/signup", h.Signup) r.POST("/orders", h.CreateOrder) return r }
true
b420046c856479f713695dc7eb173572fb8dee45
Go
creack/talks
/2015-02-22.raytracer.gophercon.india/rt/calc.go
UTF-8
448
2.984375
3
[]
no_license
[]
no_license
func (s *Scene) calc(x, y int, eye objects.Point, objs []objects.Object) color.Color { var ( k float64 = -1 col color.Color = color.Black v = objects.Vector{ X: float64(1000 - eye.X), Y: float64(s.Width/2 - x - eye.Y), Z: float64(s.Height/2 - y - eye.Z), } ) for _, obj := range objs { if tmp := obj.Intersect(v, eye); tmp > 0 && (k == -1 || tmp < k) { k = tmp col = obj.Color() } } return col }
true
c80c7db09348b206da58c2a92cded20a30335618
Go
rockstardevs/goofx
/util.go
UTF-8
3,016
3.0625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package goofx import ( "bytes" "encoding/xml" "unicode/utf8" "github.com/golang/glog" ) //revive:disable:exported var ( // XML Escape sequences. // from https://golang.org/src/encoding/xml/xml.go:1840 escQuot = []byte("&#34;") // shorter than "&quot;" escApos = []byte("&#39;") // shorter than "&apos;" escAmp = []byte("&amp;") escLt = []byte("&lt;") escGt = []byte("&gt;") escTab = []byte("&#x9;") escNl = []byte("&#xA;") escCr = []byte("&#xD;") escFffd = []byte("\uFFFD") // Unicode replacement character ) // Decide whether the given rune is in the XML Character Range, per // the Char production of http://www.xml.com/axml/testaxml.htm, // Section 2.2 Characters. // Lifted from https://golang.org/src/encoding/xml/xml.go:1102 func isInCharacterRange(r rune) (inrange bool) { return r == 0x09 || r == 0x0A || r == 0x0D || r >= 0x20 && r <= 0xDF77 || r >= 0xE000 && r <= 0xFFFD || r >= 0x10000 && r <= 0x10FFFF } // escapeString returns properly escaped XML equivalent of the plain text data s. // based on https://golang.org/src/encoding/xml/xml.go:1907 func EscapeString(s string) string { var ( result bytes.Buffer esc []byte last = 0 ) for i := 0; i < len(s); { r, width := utf8.DecodeRuneInString(s[i:]) i += width switch r { case '"': esc = escQuot case '\'': esc = escApos case '&': esc = escAmp case '<': esc = escLt case '>': esc = escGt case '\t': esc = escTab case '\n': esc = escNl case '\r': esc = escCr default: if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { esc = escFffd break } continue } result.WriteString(s[last : i-width]) result.Write(esc) last = i } result.WriteString(s[last:]) return result.String() } // writeStartTag writes the given start element to the given buffer. // based on https://golang.org/src/encoding/xml/marshal.go:678 func writeStartTag(e *xml.StartElement, buff *bytes.Buffer) { glog.V(3).Infof("pushed: %s", e.Name.Local) buff.WriteByte('<') buff.WriteString(e.Name.Local) buff.WriteByte('>') } // writeEndTag writes the closing tag for the given end element to the given buffer. // based on https://golang.org/src/encoding/xml/marshal.go:717 func writeEndTag(name xml.Name, buff *bytes.Buffer) { glog.V(3).Infof("popped: %s", name.Local) buff.Write([]byte("</")) buff.WriteString(name.Local) buff.WriteByte('>') } // writeElement writes the starting and closing tags and data for the given elements // to the given buffer. func writeElement(startTag *xml.StartElement, data string, buff *bytes.Buffer) { writeStartTag(startTag, buff) buff.WriteString(data) writeEndTag(startTag.Name, buff) } // writeElementFromName writes the starting and closing tags and data for the given elements // to the given buffer. func writeElementFromName(name xml.Name, data string, buff *bytes.Buffer) { startTag := xml.StartElement{Name: name} writeStartTag(&startTag, buff) buff.WriteString(data) writeEndTag(name, buff) }
true
5c60ca6f77e1d62e46de35bb0825acb546ff0983
Go
shyinyong/netgame
/src/test/robot.go
UTF-8
3,438
2.53125
3
[]
no_license
[]
no_license
package main import ( "base/gnet" "base/log" "command" "fmt" "github.com/golang/protobuf/proto" "time" ) const ( ROBOT_LOGIN = 1 ROBOT_GATEWAY = 2 ) type Robot struct { gnet.TCPClient loginip string loginport int account string password string session string //1:login,2:gateway status uint32 msgHandler gnet.MessageHandler msgQueue gnet.MessageQueue chClosed chan bool inittm int64 } func NewRobot(ip string, port int, account string, password string) *Robot { robot := &Robot{ loginip: ip, loginport: port, account: account, password: password, chClosed: make(chan bool, 1), inittm: time.Now().Unix(), } robot.init() return robot } func (robot *Robot) init() { robot.Derived = robot robot.msgHandler.Reg(&command.RetUserVerify{}, robot.onRetUserVerify) robot.msgHandler.Reg(&command.RetUserLogin{}, robot.onRetUserLogin) robot.msgHandler.Reg(&command.RetGatewayLogin{}, robot.onRetGatewayLogin) robot.msgHandler.Reg(&command.TestBroadcastAll{}, robot.onTestBroadcastAll) } func (robot *Robot) Run() { robot.status = ROBOT_LOGIN ret := robot.Connect(robot.loginip, robot.loginport) if !ret { log.Println("机器人", robot.account, "连接登陆服务器失败") return } robot.inittm = time.Now().Unix() } func (robot *Robot) OnConnected() { log.Println("connected", robot.status) if robot.status == ROBOT_LOGIN { snd := new(command.ReqUserVerify) robot.SendCmd(snd) log.Println("请求登录服验证") } else if robot.status == ROBOT_GATEWAY { snd := new(command.ReqGatewayLogin) snd.Session = robot.session robot.SendCmd(snd) log.Println("请求网关验证") } } func (robot *Robot) MsgParse(msg *command.Message) bool { robot.msgQueue.Cache(msg) return true } func (robot *Robot) Do() { robot.msgQueue.Do(robot.msgHandler.Process) } func (robot *Robot) onRetUserVerify(cmd proto.Message) { snd := new(command.ReqUserLogin) snd.Loginstr = fmt.Sprint("account=", robot.account, "&password=", robot.password) robot.SendCmd(snd) } func (robot *Robot) onRetUserLogin(cmd proto.Message) { msg := cmd.(*command.RetUserLogin) if msg.Retcode != 0 { log.Println("机器人", robot.account, "登陆失败,错误码", msg.Retcode) return } log.Println("机器人登陆成功,session=", msg.Session) robot.session = msg.Session robot.Terminate() robot.Join() robot.status = ROBOT_GATEWAY ret := robot.Connect(msg.Ip, int(msg.Port)) if !ret { log.Println("机器人", robot.account, "登陆网关服务器失败", msg.Ip, ":", msg.Port) return } } func (robot *Robot) onRetGatewayLogin(cmd proto.Message) { log.Println("网关验证成功") go func() { for { snd := new(command.TestBroadcastAll) snd.Str = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111" robot.SendCmd(snd) time.Sleep(100 * time.Millisecond) flag := false select { case flag = <-robot.chClosed: log.Println("机器人准备退出") break default: break } if flag { break } } }() } func (robot *Robot) Close() { robot.chClosed <- true robot.Terminate() robot.Join() robot.msgQueue.Final() } func (robot *Robot) GetInitSec() uint32 { return uint32(time.Now().Unix() - robot.inittm) } func (robot *Robot) onTestBroadcastAll(cmd proto.Message) { //msg := cmd.(*command.TestBroadcastAll) //log.Println("recv:", msg.Str) }
true
efe1bea9d4b9faf73cd724203244b0ff3b3fde0b
Go
furkanyilmazx/ttany-chat-service
/utils/paginator/utils.go
UTF-8
1,089
3.28125
3
[]
no_license
[]
no_license
package paginator import ( "fmt" "reflect" "strings" "time" ) type fieldType string const ( fieldString fieldType = "STRING" fieldTime fieldType = "TIME" ) func convert(field interface{}) (result string) { switch field.(type) { case time.Time: result = fmt.Sprintf("%s?%s", field.(time.Time).UTC().Format(time.RFC3339Nano), fieldTime) default: result = fmt.Sprintf("%v?%s", field, fieldString) } return } func deconvert(field string) (result interface{}) { fieldTypeSepIndex := strings.LastIndex(field, "?") fieldType := fieldType(field[fieldTypeSepIndex+1:]) field = field[:fieldTypeSepIndex] switch fieldType { case fieldTime: t, err := time.Parse(time.RFC3339Nano, field) if err != nil { t = time.Now().UTC() } result = t default: result = field } return } func flip(order order) order { if order == ASC { return DESC } return ASC } func reverse(v reflect.Value) reflect.Value { result := reflect.MakeSlice(v.Type(), 0, v.Cap()) for i := v.Len() - 1; i >= 0; i-- { result = reflect.Append(result, v.Index(i)) } return result }
true
de4ff524b2f1ef7599c236ff1d8ff5cede5827e6
Go
diananr/cai-project
/back/dataset.go
UTF-8
1,144
3.171875
3
[]
no_license
[]
no_license
package main import ( "encoding/csv" "fmt" "net/http" "strconv" "strings" ) func readCSV(url string) ([][]string, error) { response, err := http.Get(url) if err != nil { fmt.Println("Error getting URL => ", err.Error()) return nil, err } defer response.Body.Close() reader := csv.NewReader(response.Body) reader.Comma = ';' data, err := reader.ReadAll() if err != nil { fmt.Println("Error while reading the file => ", err.Error()) return nil, err } return data, nil } func getDataset() (dataset [][]float64){ urlDataSet := "https://github.com/diananr/cai-project/raw/master/dataset/casos_cai_2019.csv" data, err := readCSV(urlDataSet) if err != nil { fmt.Println("Error => ", err.Error()) panic(err) } datasetDataCustom := [][]float64{} for idx, row := range data { if idx == 0 { continue } rowFloat := strings.Split(row[0], ",") elementRow := []float64{} for _, element := range rowFloat { valueFloat, _ := strconv.ParseFloat(element, 64) elementRow = append(elementRow, valueFloat) } datasetDataCustom = append(datasetDataCustom, elementRow) } return datasetDataCustom; }
true
c4c8448d75bcdb8daf1a2c1341d72acd0f300b04
Go
rain825/membershipSite
/main.go
UTF-8
4,160
2.640625
3
[]
no_license
[]
no_license
package main import ( "fmt" "github.com/boj/redistore" "github.com/gorilla/sessions" "github.com/labstack/echo-contrib/session" "net/http" "github.com/flosch/pongo2" "github.com/jmoiron/sqlx" "github.com/labstack/echo" "golang.org/x/crypto/bcrypt" "log" ) var ( db DB templateSignup = pongo2.Must(pongo2.FromFile("template/signup.html")) templatelogin = pongo2.Must(pongo2.FromFile("template/login.html")) templateIndex = pongo2.Must(pongo2.FromFile("template/index.html")) ) type DB struct { *sqlx.DB } // Handler func handlerIndex(c echo.Context) error { sess, err := session.Get("session", c) if err != nil { log.Printf("session error:%v\n", err) } body, err := templateIndex.Execute( pongo2.Context{ "userID": sess.Values["userID"], }, ) if err != nil { log.Printf("pongo2 error:%v\n", err) return c.String(http.StatusInternalServerError, err.Error()) } return c.HTML(http.StatusOK, body) } func handlerGetSingUp(c echo.Context) error { body, err := templateSignup.Execute( pongo2.Context{}, ) if err != nil { c.String(http.StatusInternalServerError, err.Error()) } return c.HTML(http.StatusOK, body) } func handlerPostSignUp(c echo.Context) error { userID := c.FormValue("userID") userName := c.FormValue("userName") password, err := bcrypt.GenerateFromPassword([]byte(c.FormValue("password")), bcrypt.DefaultCost) if err != nil { log.Printf("password hash error:%v\n", err) } IDNumber, err := db.InsertUser(userID, userName, string(password)) if err != nil { log.Printf("insert error:%v\n", err) } fmt.Printf("insert number %d\n", IDNumber) db.FetchUsers() return c.String(http.StatusOK, "Hello, World!") } func handlerGetLogin(c echo.Context) error { body, err := templatelogin.Execute( pongo2.Context{}, ) if err != nil { c.String(http.StatusInternalServerError, err.Error()) } return c.HTML(http.StatusOK, body) } func handlerPostLogin(c echo.Context) error { userID := c.FormValue("userID") password := c.FormValue("password") authResult := authentication(userID, password) if authResult { sess, err := session.Get("session", c) if err != nil { log.Printf("session get error:%v\n", err) } sess.Options = &sessions.Options{ Path: "/", MaxAge: 86400 * 7, HttpOnly: true, } sess.Values["userID"] = userID if err := sess.Save(c.Request(), c.Response()); err != nil { log.Printf("session save error:%v\n", err) } return c.Redirect(http.StatusFound, "/") } else { body, err := templatelogin.Execute( pongo2.Context{ "flash": "ログイン失敗", "userID": userID, }, ) if err != nil { c.String(http.StatusInternalServerError, err.Error()) } return c.HTML(http.StatusUnauthorized, body) } } func handlerLogout(c echo.Context) error { sess, err := session.Get("session", c) if err != nil { log.Printf("session error:%v\n", err) } sess.Options = &sessions.Options{ MaxAge: -1, Path: "/", } sess.Save(c.Request(), c.Response()) return c.String(http.StatusOK, "Hello, World!") } func authentication(userID, password string) bool { user, err := db.FetchUserByID(userID) if err != nil { log.Printf("userInfo fetch error:%v\n", err) } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err == nil { return true } else { log.Printf("authenticattion error:%v\n", err) return false } } func main() { //DB接続 sqlxdb, err := sqlx.Open("mysql", fmt.Sprintf( "%s:%s@tcp(%s:%s)/%s", "local_user", "local_password", "localhost", "3306", "site", )) if err != nil { log.Fatalf("DB Connection Error: %v", err) return } db = DB{sqlxdb} store, err := redistore.NewRediStore(10, "tcp", ":6379", "", []byte("secret-key")) if err != nil { panic(err) } defer store.Close() // Echo instance e := echo.New() e.Use(session.Middleware(store)) // Routes e.GET("/", handlerIndex) e.GET("/signup", handlerGetSingUp) e.POST("/signup", handlerPostSignUp) e.GET("/login", handlerGetLogin) e.POST("/login", handlerPostLogin) e.DELETE("/logout", handlerLogout) // Start server e.Logger.Fatal(e.Start(":1323")) }
true
c785c12cca1f735470c38233b01b68ceae7e3771
Go
chrisport/SoundcloudToTrackID
/src/webserver.go
UTF-8
9,641
2.53125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "net/http" "log" "os/exec" "strings" "regexp" "strconv" "math" "html/template" simplejson "github.com/bitly/go-simplejson" "github.com/chrisport/slotprovider" "sync" "encoding/json" "os" "io/ioutil" "time" ) //TODO proper project setup, modular separation var ( //TODO use file templates bootstrap = `<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> body {margin: 1em;}</style>` inProgressMessage = "<html><head>" + bootstrap + "<meta http-equiv=\"refresh\" content=\"2;\"></head><body>recognition in progress... you will be redirected automatically</body></html>" resultPage = `<html><head>` + bootstrap + `</head><body> {{.ErrorMessage}}<h1>{{if .Artist}}{{.Artist}} - {{.TrackName}}{{end}}<h1> <button type="submit" class="btn btn-primary" onClick="window.history.go(-1); return false;">Search more</button> </body></html>` hourRegex = regexp.MustCompile("([0-9]+)h") minuteRegex = regexp.MustCompile("([0-9]+)m") secondRegex = regexp.MustCompile("([0-9]+)s") cleanUrlRegex = regexp.MustCompile("(.*)\\?") notRecognisedMessage = "Track could not be recognised." ) func main() { loadCacheFromDisc() go func() { for { time.Sleep(20 * time.Second) saveCacheToDisc() } }() Serve() } type Result struct { ErrorMessage string `json:"error,omitempty"` Artist string `json:"artist,omitempty"` TrackName string `json:"trackName,omitempty"` RawBody string `json:"rawBody,omitempty"` } func Serve() { fs := http.FileServer(http.Dir("frontend")) http.Handle("/", fs) http.HandleFunc("/stats", func(rw http.ResponseWriter, req *http.Request) { dump, err := dumpCache() if err != nil { rw.Write([]byte(err.Error())) } rw.Write(dump) }) throttledRecogniser := newThrottledRecogniser() http.HandleFunc("/api/recognise", func(rw http.ResponseWriter, req *http.Request) { q := req.URL.Query() songUrl := q["url"][0] songUrl = cleanUrl(songUrl) ts := q["t"][0] result := throttledRecogniser(songUrl, ts) if result.RawBody != "" { rw.Write([]byte(result.RawBody)) return } t := template.New("some template") // Create a template. //t2, err := t.ParseFiles("./frontend/result_page.html") // Parse template file. t2, err := t.Parse(resultPage) // Parse template file. if err != nil { panic(err) } t2.Execute(rw, *result) }) log.Fatal(http.ListenAndServe(":3000", nil)) } func newThrottledRecogniser() func(songUrl string, ts string) *Result { recognitionSP := slotprovider.New(5) return func(songUrl, ts string) *Result { timeInSeconds, err := extractTimeInSeconds(ts) if err != nil { return &Result{ErrorMessage:err.Error()} } timeInSeconds = floorToInterval(timeInSeconds, 30) fullUrl := songUrl + "#t=" + strconv.Itoa(timeInSeconds) + "s" initialized, res := getFromCache(fullUrl) if res != nil { log.Printf("Responding to %v with cached result", fullUrl) return res } else if initialized { // this item is processing currently log.Printf("Responding to %v with 'in progress'", fullUrl) return &Result{RawBody:inProgressMessage} } //else start recognition isSlotAcquired, releaseSlot := recognitionSP.AcquireSlot() if !isSlotAcquired { log.Printf("Responding to %v with 'no free slots'", fullUrl) return &Result{ErrorMessage:"Request limit reached. We are not able to recognize more songs at the moment. Please try later."} } reserveCache(fullUrl) go func() { defer releaseSlot() log.Printf("Start recognition of %v", fullUrl) result := RecogniseSong(songUrl, timeInSeconds) res := parseResult(result) putResultToCache(fullUrl, res) }() log.Printf("Responding to %v with 'in progress' and start recognition", fullUrl) return &Result{RawBody:inProgressMessage} } } func floorToInterval(time int, intervall int) int { fx := float32(time) / float32(intervall) f := time / intervall if fx - float32(f) < 0.5 { return f * intervall } else { return (f + 1) * intervall } } func parseResult(result string) *Result { sj, err := simplejson.NewJson([]byte(result)) if err != nil { return &Result{ErrorMessage:"Error occurred"} } noResult, err := (*sj).GetPath("status", "msg").String() if noResult == "No result" { return &Result{ErrorMessage:notRecognisedMessage} } artist, err := (*sj).GetPath("metadata", "music").GetIndex(0).Get("artists").GetIndex(0).Get("name").String() if err != nil { return &Result{ErrorMessage:"Error occurred"} } trackName, err := (*sj).GetPath("metadata", "music").GetIndex(0).Get("title").String() if err != nil { return &Result{ErrorMessage:"Error occurred"} } else { return &Result{Artist:artist, TrackName:trackName} } } func RecogniseSong(songUrl string, timeInSeconds int) (string) { filePath, err := downloadSong(songUrl) if err != nil { return "Error while downloading: " + err.Error() } result, err := sendSongToACR(filePath, timeInSeconds) if err != nil { return "Error while recognizing: " + err.Error() } return result } func downloadSong(songUrl string) (string, error) { var fileName string var err error if strings.Contains(songUrl, "youtube") { fileName, err = executeAndGetLastLine("./download_youtube.sh", songUrl) if err != nil { return "", err } } else if strings.Contains(songUrl, "soundcloud") { fileName, err = executeAndGetLastLine("./download_soundcloud.sh", songUrl) if err != nil { return "", err } } log.Println("Downloaded song to file: ", fileName, songUrl) return fileName, nil } func sendSongToACR(filePath string, timeInSeconds int) (string, error) { return executeAndGetLastLine("./recognise.sh", filePath, strconv.Itoa(timeInSeconds)) } func executeAndGetLastLine(script string, opts... string) (string, error) { out, err := exec.Command(script, opts...).Output() if err != nil { log.Printf("[ERROR] Script %v failed with %v\n", script, err) return "", err } log.Printf("[SUCCESS] Script %v finished\n", script) return getLastLine(string(out)), nil } // ### HELPER #### func getLastLine(input string) string { lines := strings.Split(string(input), "\n") res := "unknown error occurred" for i := len(lines) - 1; i >= 0; i-- { if lines[i] != "" { res = lines[i] break; } } return res } func extractTimeInSeconds(timestamp string) (int, error) { if timestamp == "" { return 0, nil } else if strings.Contains(timestamp, "s") || strings.Contains(timestamp, "h") || strings.Contains(timestamp, "m") { return extractFromHMSFormat(timestamp) } else { return extractFromCOLONFormat(timestamp) } } func extractFromCOLONFormat(timestamp string) (int, error) { p := strings.Split(timestamp, ":") factor := int(math.Pow(float64(60), float64(len(p) - 1))) total := 0 for i := 0; i < len(p); i++ { c, err := strconv.Atoi(p[i]) if err != nil { return 0, err } total += c * factor factor = factor / 60 } return total, nil } func extractFromHMSFormat(timestamp string) (int, error) { t := 0 match := hourRegex.FindStringSubmatch(timestamp) if len(match) > 0 { hrs, err := strconv.Atoi(match[1]) if err != nil { return 0, err } t += hrs * 1200 } match = minuteRegex.FindStringSubmatch(timestamp) if len(match) > 0 { min, err := strconv.Atoi(match[1]) if err != nil { return 0, err } t += min * 60 } match = secondRegex.FindStringSubmatch(timestamp) if len(match) > 0 { sec, err := strconv.Atoi(match[1]) if err != nil { return 0, err } t += sec } return t, nil } func cleanUrl(url string) string { if strings.Contains(url, "soundcloud") && strings.Contains(url, "?") { url = cleanUrlRegex.FindStringSubmatch(url)[0] url = url[:len(url) - 1] } return url } // ############ Cache ############ var ( cache = make(map[string]*Result) cacheMux = sync.Mutex{} InitialResult = &Result{ErrorMessage:"Processing"} ) func reserveCache(id string) { cacheMux.Lock() defer cacheMux.Unlock() cache[id] = InitialResult } func putResultToCache(id string, result *Result) { cacheMux.Lock() defer cacheMux.Unlock() if cache[id] == nil { log.Printf("Warning: Result for %v has been stored in cache without prior reservation\n", id) } cache[id] = result } func dumpCache() ([]byte, error) { cacheMux.Lock() defer cacheMux.Unlock() return json.Marshal(cache) } const cacheDumpFilePath = "cachedump.json" func loadCacheFromDisc() { if content, err := ioutil.ReadFile(cacheDumpFilePath); err == nil { var savedCache map[string]*Result err := json.Unmarshal(content, &savedCache) if err != nil { log.Println(err) return } keysToDelete := make([]string, 0) for k, v := range savedCache { if v.ErrorMessage != "" && v.ErrorMessage != notRecognisedMessage { keysToDelete = append(keysToDelete, k) } } for _, k := range keysToDelete { delete(savedCache, k) } cacheMux.Lock() defer cacheMux.Unlock() cache = savedCache } else if !os.IsNotExist(err) { log.Println("Could not load dump", err) } } func saveCacheToDisc() { log.Println("Saving result dump to disk") var f *os.File var err error f, err = os.OpenFile(cacheDumpFilePath, os.O_CREATE | os.O_RDWR | os.O_TRUNC, 0666) defer f.Close() bytes, err := dumpCache() if err != nil { log.Println(err) return } f.Write(bytes) } func getFromCache(id string) (initialized bool, result *Result) { cacheMux.Lock() defer cacheMux.Unlock() existing := cache[id] if existing == nil { return false, nil } if existing == InitialResult { return true, nil } return true, existing }
true
a34a69f3f28181f15382e8778e45df94172a0a20
Go
TheFlies/ofriends
/internal/app/visit/visit.go
UTF-8
3,320
3
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package visit import ( "context" "fmt" "github.com/TheFlies/ofriends/internal/app/types" "github.com/TheFlies/ofriends/internal/pkg/glog" validation "github.com/go-ozzo/ozzo-validation" ) // Repository is an interface of a visit repository type Repository interface { FindByID(ctx context.Context, id string) (*types.Visit, error) FindAll(ctx context.Context) ([]types.Visit, error) FindByCustomerID(ctx context.Context, customerId string) ([]types.Visit, error) Create(ctx context.Context, visit types.Visit) (string, error) Update(ctx context.Context, visit types.Visit) error Delete(ctx context.Context, id string) error FindInCommingVisit(ctx context.Context, dayTime int64) ([]types.Visit, error) FindVisitsByDay(ctx context.Context, startTime, endTime int64) ([]types.Visit, error) } type ActVisitAssocService interface { DeleteByVisitID(ctx context.Context, visitID string) error } type CusVisitAssocService interface { DeleteByVisitID(ctx context.Context, visitID string) error } // Service is an visit service type Service struct { repo Repository assocCusService CusVisitAssocService assocActService ActVisitAssocService logger glog.Logger } // NewService return a new visit service func NewService(r Repository, assocCusService CusVisitAssocService, assocActService ActVisitAssocService, l glog.Logger) *Service { return &Service{ repo: r, assocCusService: assocCusService, assocActService: assocActService, logger: l, } } // Get return given visit by his/her id func (s *Service) Get(ctx context.Context, id string) (*types.Visit, error) { return s.repo.FindByID(ctx, id) } // Get all visits from database by customer ID func (s *Service) GetByCustomerID(ctx context.Context, customerId string) ([]types.Visit, error) { return s.repo.FindByCustomerID(ctx, customerId) } // Get All return all visits from database func (s *Service) GetAll(ctx context.Context) ([]types.Visit, error) { return s.repo.FindAll(ctx) } // Create a visit func (s *Service) Create(ctx context.Context, visit types.Visit) (string, error) { if err := validation.ValidateStruct(&visit, validation.Field(&visit.Lab, validation.Required), validation.Field(&visit.ArrivedTime, validation.Required), validation.Field(&visit.DepartureTime, validation.Required), ); err != nil { return "", err } // not empty return s.repo.Create(ctx, visit) } // Update a visit func (s *Service) Update(ctx context.Context, visit types.Visit) error { if err := validation.ValidateStruct(&visit, validation.Field(&visit.ID, validation.Required), validation.Field(&visit.Lab, validation.Required), validation.Field(&visit.ArrivedTime, validation.Required), validation.Field(&visit.DepartureTime, validation.Required), ); err != nil { return err } // not empty return s.repo.Update(ctx, visit) } // Delete a visit func (s *Service) Delete(ctx context.Context, id string) error { if err := s.assocActService.DeleteByVisitID(ctx, id); err != nil && err.Error() != "not found" { fmt.Println(err) fmt.Println(err.Error()) return err } if err := s.assocCusService.DeleteByVisitID(ctx, id); err != nil && err.Error() != "not found" { fmt.Println(err) return err } if err := s.repo.Delete(ctx, id); err != nil { return err } return nil }
true
d5022b7e715e562c5efe6a338a8183f32f8ccd51
Go
Tsuyoshi-Iwanaga/learning_go
/003/06_struct.go
UTF-8
382
3.75
4
[]
no_license
[]
no_license
package main import "fmt" // var mydata struct { // Name string // Data []int // } type Mydata struct { Name string Data []int } func main() { // mydata.Name = "Taro" // mydata.Data = []int{10, 20, 30} // fmt.Println(mydata) taro := Mydata{"Taro", []int{10, 20, 30}} hanako := Mydata{Name: "Hanako", Data: []int{90, 80, 70}} fmt.Println(taro) fmt.Println(hanako) }
true
629eb5b6f97fe410473ce41355a81e851287a9d4
Go
komkom/jsonc
/jsonc/filter.go
UTF-8
15,166
3.140625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package jsonc import ( "errors" "fmt" "io" "unicode" "unicode/utf8" ) type TokenType int type State interface { Type() TokenType Next(r rune, f *Filter) error } var ErrDontAdvance = fmt.Errorf(`do-not-advance`) const ( Root TokenType = iota // 0 Object // 1 Key // 2 KeyNoQuote // 3 Value // 4 ValueNoQuote // 5 ValueMultiline // 6 Array // 7 Comment // 8 CommentMultiLine // 9 ) type Filter struct { ring *Ring outMinSize int stack []State rootState *RootState done bool err error format bool newlineCount int space string outbuf []byte lastOut rune } func NewFilter(ring *Ring, outMinSize int, format bool, space string) *Filter { return &Filter{ ring: ring, outMinSize: outMinSize, rootState: &RootState{}, format: format, space: space, lastOut: utf8.RuneError, } } func (f *Filter) Clear() { f.rootState.init = false f.outbuf = nil f.stack = nil f.done = false f.err = nil f.lastOut = utf8.RuneError } func (f *Filter) Done() bool { return f.done } func (f *Filter) Err() error { return f.err } type RootState struct { init bool } func (r *RootState) Type() TokenType { return Root } func (r *RootState) Next(ru rune, f *Filter) error { if f.format { if ru == '\n' { f.pushOut(ru) } } // check if comments need to be dispatched dispatch, err := dispatchComment(f, nil) if err != nil { return err } if dispatch { return ErrDontAdvance } if !r.init { switch ru { case '{': r.init = true f.pushOut(ru) f.pushState(&ObjectState{}) return nil case '[': r.init = true f.pushOut(ru) f.pushState(&ArrayState{}) return nil case '"': r.init = true f.pushOut(ru) f.pushState(&ValueState{}) return nil case '`': r.init = true if f.format { f.pushOut(ru) } else { f.pushOut('"') } f.pushState(&ValueMultilineState{}) return nil } } if !unicode.IsSpace(ru) { return Errorf("invalid first character: %v", -1, string(ru)) } return nil } type KeyState struct { escaped bool } func (o *KeyState) Type() TokenType { return Key } func (k *KeyState) Next(ru rune, f *Filter) error { if !k.escaped && ru == '"' { f.pushOut(ru) f.popState() return nil } k.escaped = false if ru == '\\' { k.escaped = true } f.pushOut(ru) return nil } type ValueState struct { escaped bool } func (v *ValueState) Type() TokenType { return Value } func (v *ValueState) Next(ru rune, f *Filter) error { if !v.escaped && ru == '\n' { return fmt.Errorf(`line break in string value`) } if !v.escaped && ru == '"' { f.pushOut(ru) f.popState() return nil } v.escaped = false if ru == '\\' { v.escaped = true } f.pushOut(ru) return nil } type KeyNoQuoteState struct { notFirst bool } func (o *KeyNoQuoteState) Type() TokenType { return KeyNoQuote } func (k *KeyNoQuoteState) Next(ru rune, f *Filter) error { if !k.notFirst { if !unicode.IsLetter(ru) && !unicode.IsDigit(ru) { return Errorf("invalid key", f.ring.Position()) } } if !f.format { if !k.notFirst { f.pushOut('"') } } k.notFirst = true if ru == ':' || ru == '/' || unicode.IsSpace(ru) { if !f.format { f.pushOut('"') } f.popState() return ErrDontAdvance } if !unicode.IsLetter(ru) && !unicode.IsDigit(ru) { return Errorf("invalid key", f.ring.Position()) } f.pushOut(ru) return nil } type ValueNoQuoteState struct { cval []rune } func (o *ValueNoQuoteState) Type() TokenType { return ValueNoQuote } func (v *ValueNoQuoteState) Next(ru rune, f *Filter) error { renderValue := func() error { f.popState() if len(v.cval) == 0 { return Errorf("empty no quote state", f.ring.Position()) } // check if quotes are not needed s := string(v.cval) if IsNumber(s) || s == `true` || s == `false` || s == `null` { f.pushRunes(v.cval) return ErrDontAdvance } if !unicode.IsLetter(([]rune(s))[0]) { return Errorf("invalid identifier", f.ring.Position()) } if f.format { f.pushRunes(v.cval) return ErrDontAdvance } // quote the value f.pushOut('"') f.pushRunes(v.cval) f.pushOut('"') return ErrDontAdvance } if unicode.IsSpace(ru) || ru == ',' || ru == '}' || ru == ']' || ru == '/' { return renderValue() } if !unicode.IsLetter(ru) && !unicode.IsDigit(ru) && ru != '.' && ru != '+' { return Errorf("invalid identifier", f.ring.Position()) } if ru == '\\' { return Errorf("invalid identifier", f.ring.Position()) } v.cval = append(v.cval, ru) return nil } var ( multilineEscapes = []struct { code rune replace rune }{ {code: '"', replace: '"'}, {code: '\n', replace: 'n'}, } ) func needsReplacement(r rune) (replace rune, ok bool) { for _, o := range multilineEscapes { if o.code == r { return o.replace, true } } return replace, false } type ValueMultilineState struct{} func (v *ValueMultilineState) Type() TokenType { return Value } func (v *ValueMultilineState) Next(ru rune, f *Filter) error { if f.format { if ru == '`' { f.pushOut(ru) f.popState() return nil } if ru == '\\' { return fmt.Errorf("character \\ found in multiline string") } f.pushOut(ru) return nil } if ru == '`' { f.pushOut('"') f.popState() return nil } if ru == '\\' { return fmt.Errorf("character \\ found in multiline string") } if rep, ok := needsReplacement(ru); ok { f.pushOut('\\') f.pushOut(rep) return nil } if unicode.IsSpace(ru) { f.pushOut(' ') return nil } f.pushOut(ru) return nil } type ObjInternalState = int const ( ObjIntNextAfterComma ObjInternalState = iota ObjIntNext ObjInternalKey ObjInternalDelimiter ObjInternalValue ) type ObjectState struct { internalState ObjInternalState lineBreaks int fromComment bool } func (o *ObjectState) Type() TokenType { return Object } func (o *ObjectState) pop(f *Filter) error { if f.format { f.pushOutMult(o.lineBreaks, 2, '\n') if o.lineBreaks > 0 { f.pushSpaces(f.indent() - 1) } o.lineBreaks = 0 } f.pushOut('}') f.popState() return nil } func (o *ObjectState) Next(ru rune, f *Filter) error { if ru == '\n' { o.lineBreaks++ return nil } if unicode.IsSpace(ru) { return nil } // check if comments need to be dispatched dispatch, err := dispatchComment(f, func() error { if f.format { o.fromComment = true f.pushOutMult(o.lineBreaks, 2, '\n') if o.lineBreaks > 0 { f.lastOut = utf8.RuneError } o.lineBreaks = 0 } return nil }) if err != nil { return err } if dispatch { return ErrDontAdvance } switch o.internalState { case ObjIntNext: if ru == '}' { return o.pop(f) } if !f.format { f.pushOut(',') } o.internalState = ObjIntNextAfterComma return ErrDontAdvance case ObjIntNextAfterComma: if ru == '}' { return o.pop(f) } if f.format { f.pushOutMult(o.lineBreaks, 2, '\n') if o.lineBreaks > 0 || o.fromComment { f.pushSpaces(f.indent()) o.fromComment = false } o.lineBreaks = 0 } o.internalState = ObjInternalKey if ru == '"' { f.pushOut(ru) f.pushState(&KeyState{}) return nil } f.pushState(&KeyNoQuoteState{}) return ErrDontAdvance case ObjInternalKey: if ru == ':' { f.pushOut(ru) if f.format { f.pushOut(' ') } o.internalState = ObjInternalDelimiter return nil } return Errorf("error parsing object rune: %v", f.ring.Position(), string(ru)) case ObjInternalDelimiter: o.internalState = ObjInternalValue switch ru { case '[': f.pushOut(ru) f.pushState(&ArrayState{}) return nil case '{': f.pushOut(ru) f.pushState(&ObjectState{}) return nil case '"': f.pushOut(ru) f.pushState(&ValueState{}) return nil case '`': if f.format { f.pushOut(ru) } else { f.pushOut('"') } f.pushState(&ValueMultilineState{}) return nil default: f.pushState(&ValueNoQuoteState{}) return ErrDontAdvance } case ObjInternalValue: if ru == '}' { return o.pop(f) } if ru == ',' { if f.format { f.pushOut(',') } o.internalState = ObjIntNext return nil } if f.format { if o.lineBreaks == 0 && !o.fromComment { f.pushOut(' ') } o.internalState = ObjIntNextAfterComma } else { o.internalState = ObjIntNext } return ErrDontAdvance default: return Errorf("invalid internal object state: %v", f.ring.Position(), string(ru)) } } type ArrayInternalState = int const ( ArrayIntStart ObjInternalState = iota ArrayIntValue ArrayIntAfterValue ) type ArrayState struct { init bool internalState ArrayInternalState lineBreaks int spaceOrControls int fromComment bool } func (ArrayState) Type() TokenType { return Array } func (a *ArrayState) Next(ru rune, f *Filter) error { if ru == '\n' { a.lineBreaks++ } if unicode.IsSpace(ru) { a.spaceOrControls++ return nil } // check if comments need to be dispatched dispatch, err := dispatchComment(f, func() error { if f.format { f.pushOutMult(a.lineBreaks, 2, '\n') if a.lineBreaks > 0 { f.lastOut = utf8.RuneError } a.fromComment = true a.lineBreaks = 0 } return nil }) if err != nil { return err } if dispatch { return ErrDontAdvance } switch a.internalState { case ArrayIntAfterValue: spaceOrControls := a.spaceOrControls a.spaceOrControls = 0 switch ru { case ']': a.internalState = ArrayIntValue return ErrDontAdvance case ',': a.internalState = ArrayIntValue if f.format { f.pushOut(',') } return nil } if spaceOrControls > 0 { if f.format && (a.lineBreaks == 0 && !a.fromComment) { f.pushOut(' ') } a.internalState = ArrayIntValue return ErrDontAdvance } return Errorf("invalid character after value", f.ring.Position()) case ArrayIntStart, ArrayIntValue: if ru == ']' { if f.format { f.pushOutMult(a.lineBreaks, 2, '\n') if a.lineBreaks > 0 || a.fromComment { a.fromComment = false f.pushSpaces(f.indent() - 1) } a.lineBreaks = 0 } f.popState() f.pushOut(ru) return nil } if a.internalState != ArrayIntStart && !f.format { f.pushOut(',') } if f.format { f.pushOutMult(a.lineBreaks, 2, '\n') if a.lineBreaks > 0 || a.fromComment { a.fromComment = false f.pushSpaces(f.indent()) } a.lineBreaks = 0 } a.internalState = ArrayIntAfterValue switch ru { case '[': f.pushOut(ru) f.pushState(&ArrayState{}) return nil case '{': f.pushOut(ru) f.pushState(&ObjectState{}) return nil case '"': f.pushOut(ru) f.pushState(&ValueState{}) return nil case '`': if f.format { f.pushOut(ru) } else { f.pushOut('"') } f.pushState(&ValueMultilineState{}) return nil default: f.pushState(&ValueNoQuoteState{}) return ErrDontAdvance } default: return Errorf("invalid internal array state: %v", f.ring.Position(), string(ru)) } } func dispatchComment(f *Filter, postHook func() error) (shouldDispatch bool, err error) { ru := f.ring.Peek() if ru == '/' { err = f.ring.Advance() if err != nil { return } ru = f.ring.Peek() if ru == '/' { if postHook != nil { err = postHook() if err != nil { return } } shouldDispatch = true err = f.ring.Advance() if f.format { f.pushSpace() f.pushRunes([]rune("//")) } f.pushState(&CommentState{}) return } if ru == '*' { if postHook != nil { postHook() } shouldDispatch = true if f.format { f.pushSpace() f.pushRunes([]rune("/*")) } err = f.ring.Advance() f.pushState(&CommentMultiLineState{}) return } err = f.ring.Pop() return } return } type CommentState struct{} func (c *CommentState) Type() TokenType { return Comment } func (*CommentState) Next(ru rune, f *Filter) error { if ru == '\n' { f.popState() if f.format { f.pushOut('\n') } return nil } if f.format { f.pushOut(ru) } err := f.ring.Advance() if err != nil { if errors.Is(err, io.EOF) { f.popState() } return err } return ErrDontAdvance } type CommentMultiLineState struct { escaped bool } func (c *CommentMultiLineState) Type() TokenType { return CommentMultiLine } func (c *CommentMultiLineState) Next(ru rune, f *Filter) error { if !c.escaped && ru == '*' { err := f.ring.Advance() if err != nil { return err } ru = f.ring.Peek() if ru == '/' { if f.format { f.pushOut('*') f.pushOut('/') } f.popState() return nil } f.ring.Pop() } c.escaped = false if ru == '\\' { c.escaped = true } if f.format { f.pushOut(ru) } return nil } func (f *Filter) Read(p []byte) (n int, err error) { if f.err != nil { return 0, f.err } n = f.outMinSize if n > len(p) { n = len(p) } for n > len(f.outbuf) { err = f.fill() if err != nil { break } } f.err = err if len(f.outbuf) < n { n = len(f.outbuf) } for i := 0; i < n; i++ { p[i] = f.outbuf[i] } f.outbuf = f.outbuf[n:] if errors.Is(err, io.EOF) && f.peekState().Type() == Root { f.done = true } return n, err } func (f *Filter) fill() error { state := f.peekState() for f.outMinSize > len(f.outbuf) { ru := f.ring.Peek() if ru != '\n' { // let only '\n' new line pass from the set of control characters if unicode.IsControl(ru) { err := f.ring.Advance() if err != nil { return err } continue } // transform all spaces to single spaces if unicode.IsSpace(ru) { ru = ' ' } } err := state.Next(ru, f) if err != nil && !errors.Is(err, ErrDontAdvance) { return err } if !errors.Is(err, ErrDontAdvance) { err = f.ring.Advance() if err != nil { return err } } state = f.peekState() } return nil } func (f *Filter) peekState() State { if len(f.stack) > 0 { return f.stack[len(f.stack)-1] } return f.rootState } func (f *Filter) pushState(s State) { f.stack = append(f.stack, s) } func (f *Filter) popState() { if len(f.stack) == 0 { return } f.stack = f.stack[:len(f.stack)-1] } func (f *Filter) indent() int { var indent int for _, s := range f.stack { if s.Type() == Object || s.Type() == Array { indent++ } } return indent } func (f *Filter) pushSpace() { if f.lastOut != ' ' && f.lastOut != utf8.RuneError { f.pushOut(' ') } } func (f *Filter) pushSpaces(c int) { for i := 0; i < c; i++ { f.pushOut(' ') } } func (f *Filter) pushOut(r rune) { f.lastOut = r f.outbuf = append(f.outbuf, byte(r)) } func (f *Filter) pushRunes(runes []rune) { if len(runes) > 0 { f.lastOut = runes[len(runes)-1] } f.outbuf = append(f.outbuf, []byte(string(runes))...) } func (f *Filter) pushOutMult(t int, max int, r rune) { if t > max { t = max } for i := 0; i < t; i++ { f.lastOut = r f.pushOut(r) } }
true
d2771d9cadd85362c0f419f7abeaa9fa51e8d477
Go
kapustkin/envdir
/internal/commands_test.go
UTF-8
1,174
2.75
3
[]
no_license
[]
no_license
package internal import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetEnviroment1(t *testing.T) { res, err := getEnviroment("../test/1") assert.Nil(t, err) assert.Equal(t, res, []string{"A_ENV=123", "B_VAR=another_val"}) } func TestGetEnviroment2(t *testing.T) { res, err := getEnviroment("../test/2") assert.NotNil(t, err) assert.Equal(t, res, []string{}) } func TestGetEnvParametr1(t *testing.T) { res, err := getEnvParametr("../test/1/A_ENV.txt") assert.Nil(t, err) assert.Equal(t, res, "A_ENV=123") } func TestGetEnvParametr2(t *testing.T) { res, err := getEnvParametr("../test/1/NO_EXIST.txt") assert.NotNil(t, err) assert.Equal(t, res, "") } func TestFileNameWithoutExtension(t *testing.T) { res := fileNameWithoutExtension("../test/1/A_ENV.txt") assert.Equal(t, res, "A_ENV") } func TestGetInputValues1(t *testing.T) { env, path, err := getInputValues([]string{"1233", "321"}) assert.Equal(t, env, "1233") assert.Equal(t, path, "321") assert.Nil(t, err) } func TestGetInputValues2(t *testing.T) { env, path, err := getInputValues([]string{}) assert.Equal(t, env, "") assert.Equal(t, path, "") assert.NotNil(t, err) }
true
60ecc914bdcbd94584f7f95d1eda95c1b8515d33
Go
icemanblues/advent-of-code
/2018/day08/day08.go
UTF-8
1,705
3.546875
4
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func readInput(filename string) []string { file, err := os.Open(filename) if err != nil { fmt.Printf("something bad with file: %v\n", err) return nil } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines } func main() { fmt.Println("Day 08: Memory Maneuver") // part1() part2() } type Node struct { numChild int numMetaData int metadata []int children []*Node } func part1() { fmt.Println("Part 1") line := readInput("input08.txt")[0] tokens := strings.Split(line, " ") _, _, sum := buildNode(tokens, 0) fmt.Println(sum) } func buildNode(l []string, i int) (*Node, int, int) { sum := 0 numChild, _ := strconv.Atoi(l[i]) numMetaData, _ := strconv.Atoi(l[i+1]) n := &Node{numChild, numMetaData, nil, nil} k := i + 2 for kid := 0; kid < numChild; kid++ { child, j, jmd := buildNode(l, k) n.children = append(n.children, child) k = j sum += jmd } for m := 0; m < numMetaData; m++ { md, _ := strconv.Atoi(l[k]) sum += md n.metadata = append(n.metadata, md) k++ } // fmt.Println(n) return n, k, sum } func part2() { fmt.Println("Part 2") line := readInput("input08.txt")[0] tokens := strings.Split(line, " ") root, _, _ := buildNode(tokens, 0) fmt.Println(value(*root)) } func value(n Node) int { if n.numChild == 0 { sum := 0 for _, md := range n.metadata { sum += md } return sum } v := 0 for _, md := range n.metadata { if md == 0 { continue } if md >= len(n.children)+1 { continue } v += value(*n.children[md-1]) } return v }
true
8ca67c54a13c1bd99d914ee9de02a2b9c090f794
Go
john6938/tenseIdentifierGo
/learningData.go
UTF-8
18,303
3.234375
3
[]
no_license
[]
no_license
package main // Learning data // TODO: Implement loading from csv files var ( EXAMPLES_ARRAY = map[string]int{ "He goes to school every morning.": TENSE_PRESENT_SIMPLE, "She understands English.": TENSE_PRESENT_SIMPLE, "It mixes the sand and the water.": TENSE_PRESENT_SIMPLE, "He tries very hard.": TENSE_PRESENT_SIMPLE, "She enjoys playing the piano.": TENSE_PRESENT_SIMPLE, "I don’t live in London now.": TENSE_PRESENT_SIMPLE, "I don’t play the piano but I play the guitar.": TENSE_PRESENT_SIMPLE, "They don’t work at the weekend.": TENSE_PRESENT_SIMPLE, "John doesn’t live in Manchester.)": TENSE_PRESENT_SIMPLE, "Angela doesn’t drive to work.": TENSE_PRESENT_SIMPLE, "She goes by bus.": TENSE_PRESENT_SIMPLE, "I listen to the radio": TENSE_PRESENT_SIMPLE, "I have a radio": TENSE_PRESENT_SIMPLE, "She is crying.": TENSE_PRESENT_CONTINUOUS, "He is talking to his friend.": TENSE_PRESENT_CONTINUOUS, "The baby is sleeping in his crib.": TENSE_PRESENT_CONTINUOUS, "We are visiting the museum in the afternoon.": TENSE_PRESENT_CONTINUOUS, "He is not standing.": TENSE_PRESENT_CONTINUOUS, "Anthony is sitting in the chair.": TENSE_PRESENT_CONTINUOUS, "You are not watching the movie.": TENSE_PRESENT_CONTINUOUS, "Rose is reading a book.": TENSE_PRESENT_CONTINUOUS, "She is not going to the game tonight.": TENSE_PRESENT_CONTINUOUS, "He is meeting his friends after school.": TENSE_PRESENT_CONTINUOUS, "Are you visiting your cousin this weekend?": TENSE_PRESENT_CONTINUOUS, "I am not going to the meeting after work.": TENSE_PRESENT_CONTINUOUS, "Is John playing football today?": TENSE_PRESENT_CONTINUOUS, "Marc is making pizza now.": TENSE_PRESENT_CONTINUOUS, "They are eating lunch right now.": TENSE_PRESENT_CONTINUOUS, "Frances is talking on the phone at the moment.": TENSE_PRESENT_CONTINUOUS, "Is she laughing?": TENSE_PRESENT_CONTINUOUS, "Are they listening to the teacher?": TENSE_PRESENT_CONTINUOUS, "Is the baby drinking his bottle?": TENSE_PRESENT_CONTINUOUS, "Are you going?": TENSE_PRESENT_CONTINUOUS, "I have been to France.": TENSE_PRESENT_PERFECT_SIMPLE, "I have been to France three times.": TENSE_PRESENT_PERFECT_SIMPLE, "I have never been to France.": TENSE_PRESENT_PERFECT_SIMPLE, "I think I have seen that movie before.": TENSE_PRESENT_PERFECT_SIMPLE, "He has never traveled by train.": TENSE_PRESENT_PERFECT_SIMPLE, "Joan has studied two foreign languages.": TENSE_PRESENT_PERFECT_SIMPLE, "Have you ever met him?": TENSE_PRESENT_PERFECT_SIMPLE, "No, I have not met him.": TENSE_PRESENT_PERFECT_SIMPLE, "You have grown since the last time I saw you.": TENSE_PRESENT_PERFECT_SIMPLE, "The government has become more interested in arts education.": TENSE_PRESENT_PERFECT_SIMPLE, "Japanese has become one of the most popular courses at the university since the Asian studies program was established.": TENSE_PRESENT_PERFECT_SIMPLE, "My English has really improved since I moved to Australia.": TENSE_PRESENT_PERFECT_SIMPLE, "Man has walked on the Moon.": TENSE_PRESENT_PERFECT_SIMPLE, "Our son has learned how to read.": TENSE_PRESENT_PERFECT_SIMPLE, "Doctors have cured many deadly diseases.": TENSE_PRESENT_PERFECT_SIMPLE, "Scientists have split the atom.": TENSE_PRESENT_PERFECT_SIMPLE, "James has not finished his homework yet.": TENSE_PRESENT_PERFECT_SIMPLE, "Susan hasn't mastered Japanese, but she can communicate.": TENSE_PRESENT_PERFECT_SIMPLE, "They have been talking for the last hour.": TENSE_PRESENT_PERFECT_CONTINUOUS, "She has been working at that company for three years.": TENSE_PRESENT_PERFECT_CONTINUOUS, "What have you been doing for the last 30 minutes?": TENSE_PRESENT_PERFECT_CONTINUOUS, "James has been teaching at the university since June.": TENSE_PRESENT_PERFECT_CONTINUOUS, "We have been waiting here for over two hours!": TENSE_PRESENT_PERFECT_CONTINUOUS, "Why has Nancy not been taking her medicine for the last three days?": TENSE_PRESENT_PERFECT_CONTINUOUS, "Recently, I have been feeling really tired.": TENSE_PRESENT_PERFECT_CONTINUOUS, "She has been watching too much television lately.": TENSE_PRESENT_PERFECT_CONTINUOUS, "Mary has been feeling a little depressed.": TENSE_PRESENT_PERFECT_CONTINUOUS, "Lisa has not been practicing her English.": TENSE_PRESENT_PERFECT_CONTINUOUS, "You have only been waiting here for one hour.": TENSE_PRESENT_PERFECT_CONTINUOUS, "Have you only been waiting here for one hour?": TENSE_PRESENT_PERFECT_CONTINUOUS, "Recently, John has been doing the work.": TENSE_PRESENT_PERFECT_CONTINUOUS, "Recently, the work has been being done by John.": TENSE_PRESENT_PERFECT_CONTINUOUS, "What have you been doing?": TENSE_PRESENT_PERFECT_CONTINUOUS, "I didn't want to go to the dentist.": TENSE_PAST_SIMPLE, "She didn't have time.": TENSE_PAST_SIMPLE, "You didn't close the door.": TENSE_PAST_SIMPLE, "He didn't come to my party.": TENSE_PAST_SIMPLE, "They didn't study so they didn't pass the test.": TENSE_PAST_SIMPLE, "We didn't sleep well last night.": TENSE_PAST_SIMPLE, "Did she like the surprise?": TENSE_PAST_SIMPLE, "They went to the library.": TENSE_PAST_SIMPLE, "We didn't have any money.": TENSE_PAST_SIMPLE, "We didn't do our exercises this morning.": TENSE_PAST_SIMPLE, "Did you have a bicycle when you were young?": TENSE_PAST_SIMPLE, "Did you do much climbing in Switzerland?": TENSE_PAST_SIMPLE, "He didn't go to bed early last night.": TENSE_PAST_SIMPLE, "I had a radio": TENSE_PAST_SIMPLE, "I heard the radio": TENSE_PAST_SIMPLE, "I listened to the radio": TENSE_PAST_SIMPLE, "Did he come to your party last week?": TENSE_PAST_SIMPLE, "They went yesterday.": TENSE_PAST_SIMPLE, "The sun was shining every day that summer.": TENSE_PAST_CONTINUOUS, "As I spoke, the children were laughing at my cleverness.": TENSE_PAST_CONTINUOUS, "The audience was applauding until he fell off the stage.": TENSE_PAST_CONTINUOUS, "I was making dinner when she arrived.": TENSE_PAST_CONTINUOUS, "At 6 o’clock, I was eating dinner.": TENSE_PAST_CONTINUOUS, "She was talking constantly in class in those days.": TENSE_PAST_CONTINUOUS, "I was watching TV when she called.": TENSE_PAST_CONTINUOUS, "When the phone rang, she was writing a letter.": TENSE_PAST_CONTINUOUS, "While we were having the picnic, it started to rain.": TENSE_PAST_CONTINUOUS, "What were you doing when the earthquake started?": TENSE_PAST_CONTINUOUS, "I was listening to my iPod, so I didn't hear the fire alarm.": TENSE_PAST_CONTINUOUS, "You were not listening to me when I told you to turn the oven off.": TENSE_PAST_CONTINUOUS, "While John was sleeping last night, someone stole his car.": TENSE_PAST_CONTINUOUS, "The teacher asked if we had studied for the exam.": TENSE_PAST_PERFECT_SIMPLE, "The usher asked if we had purchased our tickets.": TENSE_PAST_PERFECT_SIMPLE, "My neighbor asked if we had seen her dog.": TENSE_PAST_PERFECT_SIMPLE, "The boss had said it would be a long meeting.": TENSE_PAST_PERFECT_SIMPLE, "We wished we had purchased the winning ticket": TENSE_PAST_PERFECT_SIMPLE, "I wished I had told the truth.": TENSE_PAST_PERFECT_SIMPLE, "She wished she had seen her friend.": TENSE_PAST_PERFECT_SIMPLE, "The boy wished he had asked another question.": TENSE_PAST_PERFECT_SIMPLE, "She had just left the scene when the ambulance arrived.": TENSE_PAST_PERFECT_SIMPLE, "The bus had just left when we got to the stop.": TENSE_PAST_PERFECT_SIMPLE, "I had never seen such a beautiful sunset before I went to the island.": TENSE_PAST_PERFECT_SIMPLE, "Before he did his homework, he had stayed after school for help.": TENSE_PAST_PERFECT_SIMPLE, "She had lived in California before moving to Texas.": TENSE_PAST_PERFECT_SIMPLE, "We had just called home when my mom texted us about returning the car.": TENSE_PAST_PERFECT_SIMPLE, "He had been drinking milk out the carton when Mom walked into the kitchen.": TENSE_PAST_PERFECT_CONTINUOUS, "I had been working at the company for five years when I got the promotion.": TENSE_PAST_PERFECT_CONTINUOUS, "Martha had been walking three miles a day before she broke her leg.": TENSE_PAST_PERFECT_CONTINUOUS, "The program that was terminated had been working well since 1945.": TENSE_PAST_PERFECT_CONTINUOUS, "Cathy had been playing the piano for 35 years when she was finally asked to do a solo with the local orchestra.": TENSE_PAST_PERFECT_CONTINUOUS, "He had been throwing rocks at her window for five minutes before she finally came out on the balcony and said, “Hey, Romeo.”": TENSE_PAST_PERFECT_CONTINUOUS, "It will rain tomorrow.": TENSE_FUTURE_SIMPLE, "I'll pay for the tickets by credit card.": TENSE_FUTURE_SIMPLE, "I'll do the washing-up.": TENSE_FUTURE_SIMPLE, "He'll carry your bag for you.": TENSE_FUTURE_SIMPLE, "The baby won't eat his soup.": TENSE_FUTURE_SIMPLE, "I won't leave until I've seen the manager!": TENSE_FUTURE_SIMPLE, "Shall I open the window?": TENSE_FUTURE_SIMPLE, "Shall we go to the cinema tonight?": TENSE_FUTURE_SIMPLE, "What shall I tell the boss about this money?": TENSE_FUTURE_SIMPLE, "You will do exactly as I say.": TENSE_FUTURE_SIMPLE, "Will you come to the dance with me?": TENSE_FUTURE_SIMPLE, "Will you marry me?": TENSE_FUTURE_SIMPLE, " I will finish my report later today.": TENSE_FUTURE_SIMPLE, "The sun will rise at 6:03 am.": TENSE_FUTURE_SIMPLE, "I'll go to the market tomorrow.": TENSE_FUTURE_SIMPLE, "There will be another conference next month.": TENSE_FUTURE_SIMPLE, "I'll come to see you on Sunday.": TENSE_FUTURE_SIMPLE, "We'll be back on Friday afternoon.": TENSE_FUTURE_SIMPLE, "Tom will visit his parents next week.": TENSE_FUTURE_SIMPLE, "They will paint the fence blue.": TENSE_FUTURE_SIMPLE, "I will return in two hours.": TENSE_FUTURE_SIMPLE, "He will finish his homework in twenty minutes.": TENSE_FUTURE_SIMPLE, "Jane will turn 18 this year.": TENSE_FUTURE_SIMPLE, "Michael will be running a marathon this Saturday.": TENSE_FUTURE_CONTINUOUS, "Eric will be competing against Michael in the race.": TENSE_FUTURE_CONTINUOUS, "I will be watching Michael and Eric race.": TENSE_FUTURE_CONTINUOUS, "Robert will be reading various kinds of books.": TENSE_FUTURE_CONTINUOUS, "They will be playing football in that field.": TENSE_FUTURE_CONTINUOUS, "April will be having coffee in this coffee shop.": TENSE_FUTURE_CONTINUOUS, "Bob will be going to the library.": TENSE_FUTURE_CONTINUOUS, "We will be shopping in that market this Monday.": TENSE_FUTURE_CONTINUOUS, "We will be watching a movie in this Cineplex on next Friday.": TENSE_FUTURE_CONTINUOUS, "You will be shopping at that market tomorrow.": TENSE_FUTURE_CONTINUOUS, "I will be singing different kinds of songs, especially modern.": TENSE_FUTURE_CONTINUOUS, "I will be attending a program of my varsity on Friday.": TENSE_FUTURE_CONTINUOUS, "Jeff will be traveling around the world in March.": TENSE_FUTURE_CONTINUOUS, "They will be playing hockey in that field on Thursday.": TENSE_FUTURE_CONTINUOUS, "The poet will be writing a romantic poem for the program.": TENSE_FUTURE_CONTINUOUS, "The lyricist will be writing a realistic song for the film.": TENSE_FUTURE_CONTINUOUS, "Will you be going to the concert of realistic songs?": TENSE_FUTURE_CONTINUOUS, "I will not be attending the program because of my busy schedule.": TENSE_FUTURE_CONTINUOUS, "Robin will be joining us at the meeting.": TENSE_FUTURE_CONTINUOUS, "I will be helping him to do the task": TENSE_FUTURE_CONTINUOUS, "We will be going to enjoy the musical drama.": TENSE_FUTURE_CONTINUOUS, "I will be arranging all the necessary materials for the program.": TENSE_FUTURE_CONTINUOUS, "Jack will have finished his homework by the time his mother gets home.": TENSE_FUTURE_PERFECT_SIMPLE, "She will have gotten ready by the time they leave the house.": TENSE_FUTURE_PERFECT_SIMPLE, "Laura will have cleaned out the apartment before she gives back the key.": TENSE_FUTURE_PERFECT_SIMPLE, "By the time I get home, Zoe will have cooked dinner for both of us.": TENSE_FUTURE_PERFECT_SIMPLE, "The robbers will have taken all the money by the time anyone arrives.": TENSE_FUTURE_PERFECT_SIMPLE, "By the time he graduates, he will have completed five years of study.": TENSE_FUTURE_PERFECT_SIMPLE, "The snow will have stopped by April.": TENSE_FUTURE_PERFECT_SIMPLE, "We will have returned home by five o'clock.": TENSE_FUTURE_PERFECT_SIMPLE, "By tomorrow, their life will have changed completely.": TENSE_FUTURE_PERFECT_SIMPLE, "Her heel will have fully healed by the summer.": TENSE_FUTURE_PERFECT_SIMPLE, "By next month, you will have received your promotion.": TENSE_FUTURE_PERFECT_SIMPLE, "By the time he wakes up, we will have prepared lunch for everyone.": TENSE_FUTURE_PERFECT_SIMPLE, "In November, I will have been working at my company for three years.": TENSE_FUTURE_PERFECT_CONTINUOUS, "At five o’clock, I will have been waiting for thirty minutes.": TENSE_FUTURE_PERFECT_CONTINUOUS, "When I turn thirty, I will have been playing piano for twenty-one years.": TENSE_FUTURE_PERFECT_CONTINUOUS, } )
true
864c573bafead004dc9c13e82f925f1d62fa3236
Go
yskang/AlgorithmWithGo
/baekjoon/numberTriangleDynamicProgramming.go
UTF-8
1,025
3.25
3
[]
no_license
[]
no_license
// https://www.acmicpc.net/problem/1932 package baekjoon import ( "fmt" "bufio" "os" "strings" "strconv" ) func NumberTriangleDynamicPrograming() { triangle := make([][]int, 0) var n int fmt.Scanf("%d\n", &n) //for i := 0 ; i < n ; i++ { // triangle = append(triangle, []int{}) // for j := 0 ; j <= i ; j++ { // fmt.Scanf("%d", &m) // triangle[i] = append(triangle[i], m) // } //} inNums := make([]int, 0) scanner := bufio.NewScanner(os.Stdin) i := 0 for scanner.Scan() { inline := scanner.Text() inStrs := strings.Split(inline, " ") triangle = append(triangle, []int{}) for _, str := range inStrs { num, _ := strconv.Atoi(str) triangle[i] = append(triangle[i], num) } inNums = inNums[:0] i += 1 if i == n { break } } for i = n-2 ; i >= 0 ; i-- { for j := 0 ; j < i+1 ; j++ { triangle[i][j] = triangle[i][j] + max(triangle[i+1][j], triangle[i+1][j+1]) } } fmt.Println(triangle[0][0]) } func max(a int, b int) int { if a > b { return a } return b }
true
5136314c730c6cdb907d813c531d58a4d932fd38
Go
HDUerZhuBin/golang
/temp_repo/for2.go
UTF-8
142
3.125
3
[]
no_license
[]
no_license
package main import ( "fmt" ) func main(){ var i int = 5 for count:=i;count>0;count--{ fmt.Println("the current count is:",count) } }
true
bcb53096987025c76939cc6302fbdf7df1e88d29
Go
HarryAlvarado28/mini-servers-hackrry
/server-go.go
UTF-8
345
2.671875
3
[]
no_license
[]
no_license
package main import ( "net/http" "github.com/labstack/echo" ) func main() { const VAR_PORT = ":4321" // Cont. indicador del puerto e := echo.New() e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "Hola, Mundo!") }) e.Logger.Fatal(e.Start(VAR_PORT)) } // Ver más del framework Echo en https://echo.labstack.com.
true
fc987bb5885343f81a672c639ab9818e44019bdd
Go
openshift/cluster-kube-storage-version-migrator-operator
/pkg/operator/deploymentcontroller/deployment_test.go
UTF-8
1,771
2.796875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package deploymentcontroller import ( "testing" "github.com/google/go-cmp/cmp" operatorv1 "github.com/openshift/api/operator/v1" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" ) func Test_setOperandLogLevel(t *testing.T) { testCases := []struct { logLevel operatorv1.LogLevel command []string expected []string }{ { logLevel: operatorv1.Debug, command: []string{"arg0", "arg1", "arg2"}, expected: []string{"arg0", "arg1", "arg2", "--v=4"}, }, { logLevel: operatorv1.Trace, command: []string{"arg0", "--v=2", "arg2"}, expected: []string{"arg0", "--v=6", "arg2"}, }, { logLevel: operatorv1.TraceAll, command: []string{"arg0", "arg1", "--v=2"}, expected: []string{"arg0", "arg1", "--v=8"}, }, } for _, tc := range testCases { t.Run("", func(t *testing.T) { spec := &operatorv1.OperatorSpec{ LogLevel: tc.logLevel, } deployment := &appsv1.Deployment{ Spec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{ Containers: []corev1.Container{{ Name: "migrator", Command: tc.command, }}, }}}, } _ = setOperandLogLevel(spec, deployment) if !cmp.Equal(deployment.Spec.Template.Spec.Containers[0].Command, tc.expected) { t.Fatal(cmp.Diff(deployment.Spec.Template.Spec.Containers[0].Command, tc.expected)) } }) } t.Run("", func(t *testing.T) { spec := &operatorv1.OperatorSpec{LogLevel: operatorv1.Debug} deployment := &appsv1.Deployment{ Spec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{ Containers: []corev1.Container{{ Name: "not_migrator", }}, }}}, } if err := setOperandLogLevel(spec, deployment); err == nil { t.Fatal("expected error") } }) }
true
81074fa1f6c578848baf94f578766dba74eb2703
Go
CrowdPower/fund
/controllers/payment.go
UTF-8
3,818
2.828125
3
[]
no_license
[]
no_license
package controllers import ( "encoding/json" "fmt" "log" "net/http" "time" "github.com/gorilla/mux" "github.com/satori/go.uuid" "github.com/crowdpower/fund/models" "github.com/crowdpower/fund/storage" "github.com/crowdpower/fund/utils" ) const ( paymentPageSize = 20 ) type PaymentController interface { PostPayment(w http.ResponseWriter, r *http.Request) GetPayment(w http.ResponseWriter, r *http.Request) GetPayments(w http.ResponseWriter, r *http.Request) GetPaymentsSum(w http.ResponseWriter, r *http.Request) } type paymentController struct { db storage.DB } func NewPaymentController(db storage.DB) PaymentController { return &paymentController{db} } func (d *paymentController) PostPayment(w http.ResponseWriter, r *http.Request) { var payment models.Payment err := json.NewDecoder(r.Body).Decode(&payment) if err != nil { log.Printf("could not unmarshal PostPayment request body\n%v", err) utils.SendError(w, "Could not parse body as JSON", http.StatusBadRequest) return } if payment.Amount <= 0 { utils.SendError(w, "Payment amount must be greater than 0", http.StatusBadRequest) return } if payment.Url == "" { utils.SendError(w, "Payment url cannot be empty", http.StatusBadRequest) return } payment.Username = mux.Vars(r)["username"] payment.Id = uuid.NewV4().String() payment.Time = time.Now().Format(storage.TimeFormat) err = d.db.CreatePayment(&payment) if err != nil { if storage.IsInsufficientFunds(err) { utils.SendError(w, "Insufficient funds", http.StatusBadRequest) return } log.Printf("could not insert payment %v into database\n%v", payment, err) utils.SendError(w, "Error inserting payment into database", http.StatusInternalServerError) return } utils.SendSuccess(w, nil, http.StatusNoContent) } func (d *paymentController) GetPayment(w http.ResponseWriter, r *http.Request) { username := mux.Vars(r)["username"] id := r.URL.Query().Get("id") if id == "" { utils.SendError(w, "Parameter 'id' required", http.StatusBadRequest) return } payment, err := d.db.GetPayment(username, id) if storage.IsNotFound(err) { utils.SendError(w, fmt.Sprintf("Payment %v not found for user %v", id, username), http.StatusNotFound) return } else if err != nil { log.Printf("could not get payment %v for user %v from the database\n%v", id, username, err) utils.SendError(w, "Error getting payment from database", http.StatusInternalServerError) return } utils.SendSuccess(w, payment, http.StatusOK) } func (d *paymentController) GetPayments(w http.ResponseWriter, r *http.Request) { username := mux.Vars(r)["username"] args := &models.PaymentArgs{} err := utils.ParseArgs(r, args) if err != nil { utils.SendError(w, err.Error(), http.StatusBadRequest) return } if args.Count == 0 { args.Count = paymentPageSize } payments, err := d.db.GetPayments(username, args) if err != nil { log.Printf("could not get payments for user %v from the database\n%v", username, err) utils.SendError(w, "Error getting payments from database", http.StatusInternalServerError) return } utils.SendPage(w, r, payments, args.Offset+paymentPageSize, paymentPageSize, len(payments) == args.Count) } func (d *paymentController) GetPaymentsSum(w http.ResponseWriter, r *http.Request) { username := mux.Vars(r)["username"] args := &models.PaymentArgs{} err := utils.ParseArgs(r, args) if err != nil { utils.SendError(w, err.Error(), http.StatusBadRequest) return } sum, err := d.db.GetPaymentsSum(username, args) if err != nil { log.Printf("could not get payments sum for user %v from the database\n%v", username, err) utils.SendError(w, "Error getting payments sum from database", http.StatusInternalServerError) return } utils.SendSuccess(w, map[string]int{"sum": sum}, http.StatusOK) }
true
53230bdcd4c3afb836617796602e3c15ae31fedb
Go
kechako/gosw
/env/option.go
UTF-8
601
2.703125
3
[]
no_license
[]
no_license
package env import "path/filepath" type Option interface { apply(env *Env) } type optionFunc func(env *Env) func (f optionFunc) apply(env *Env) { f(env) } func WithEnvRoot(root string) Option { return optionFunc(func(env *Env) { env.envRoot = filepath.Clean(root) }) } func WithVersionLinkName(name string) Option { return optionFunc(func(env *Env) { env.verLinkName = name }) } func WithConfigDir(dir string) Option { return optionFunc(func(env *Env) { env.confDir = dir }) } func WithCacheDir(dir string) Option { return optionFunc(func(env *Env) { env.cacheDir = dir }) }
true
7cbe9814d4b012edbdad097dba7ddd3a6cf25944
Go
nettan20/hn
/hackernews/getpage.go
UTF-8
3,151
2.9375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package hackernews import ( "fmt" "html" "net/http" "regexp" "strconv" "strings" "time" "github.com/PuerkitoBio/goquery" ) //Get a new page by passing a url func (c *Client) RetrievePage(url string) (*Page, error) { //Trim leading slash if necessary if url[0] == '/' { url = url[1:] } //All urls must start with YC root (or test) urlForReq := fmt.Sprintf("%s/%s", c.RootUrl, url) req, err := http.NewRequest("GET", urlForReq, nil) if err != nil { return nil, fmt.Errorf("Error creating request for url %s: %v", url, err) } doc, err := c.doReq(req) if err != nil { return nil, fmt.Errorf("Error doing request:\n\t %v", err) } //Get all the trs with subtext for children then go back one (for the first row) rows := doc.Find(".subtext").ParentsFilteredUntil("tr", "tbody").Prev() p := NewPage(url) //Get the next url if nextUrl, found := doc.Find("td.title").Last().Find("a").Attr("href"); found { p.NextUrl = nextUrl } else { return nil, fmt.Errorf("Could not retreive next hackernews page. Time to go outside?") } //Make sure NextUrl doesn't start with forward slash for len(p.NextUrl) > 0 && p.NextUrl[0] == '/' { p.NextUrl = p.NextUrl[1:] } //Parse articles rows.Each(func(i int, row *goquery.Selection) { ar := Article{ Rank: len(p.Articles) + i, } title := row.Find(".title").Eq(1) link := title.Find("a").First() ar.Title = html.UnescapeString(link.Text()) if url, exists := link.Attr("href"); exists { ar.Url = url } //Rows are used in pairs currently row = row.Next() row.Find("span").Each(func(i int, s *goquery.Selection) { if karma, err := strconv.Atoi(strings.Split(s.Text(), " ")[0]); err == nil { ar.Karma = karma } if idSt, exists := s.Attr("id"); exists { if id, err := strconv.Atoi(strings.Split(idSt, "_")[1]); err == nil { ar.Id = id } } }) sub := row.Find("td.subtext") t := html.UnescapeString(sub.Text()) //We can ignore the error safely here ar.Created, _ = parseCreated(t) //Get the username ar.User = html.UnescapeString(sub.Find("a").First().Text()) //Get number of comments comStr := strings.Split(sub.Find("a").Last().Text(), " ")[0] if comNum, err := strconv.Atoi(comStr); err == nil { ar.NumComments = comNum } p.Articles = append(p.Articles, &ar) }) return p, nil } //Parse out from a string the create time var timeName = map[string]time.Duration{ "second": time.Second, "minute": time.Minute, "hour": time.Hour, "day": 24 * time.Hour, } var agoRegexp = regexp.MustCompile(`((?:\w*\W){2})(?:ago)`) func parseCreated(s string) (time.Time, error) { agoStr := agoRegexp.FindStringSubmatch(s) if len(agoStr) < 2 { return time.Time{}, fmt.Errorf(`No "ago" string found in string %s`, s) } words := strings.Split(agoStr[1], " ") if count, err := strconv.Atoi(words[0]); err == nil { durText := words[1] if durText[len(durText)-1] == 's' { durText = durText[:len(durText)-1] } dur := timeName[durText] diff := -int64(count) * int64(dur) return time.Now().Add(time.Duration(diff)).Round(dur), nil } else { return time.Time{}, err } }
true
46a576474d73dd0642da79d493acbe26ab6f0273
Go
sublimeye/100-days-of-code
/thegobook/xkcd.go
UTF-8
5,063
2.953125
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "errors" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "strconv" "strings" "time" ) const FIRST = 1 const LAST = 1930 // 1930 const CONCURRENCY = 10 const CACHE_DIR = "xkcd-cache" const CACHE_FILE = "xkcd-index.json" type result struct { index int res *Xkcd err error } type Xkcd struct { SafeTitle string `json:"safe_title"` Title string `json:"title"` Transcript string `json:"transcript"` Alt string `json:"alt"` Img string `json:"img"` Url string } // Collection of xkcd stories type Collection struct { Items []*Xkcd `json:"items"` } func initIndex(fetch bool) Collection { if fetch { return buildIndex() } bIndex, err := readAndParseIndexFile() var index Collection if err == nil { if jerr := json.Unmarshal(bIndex, &index); jerr != nil { fmt.Println("Unable to parse index file. Building index from scratch") return buildIndex() } fmt.Println("Using index file") return index } else { fmt.Println("Error parsing index file", err) return buildIndex() } } func buildIndex() Collection { var urls []string var collection Collection start := time.Now() fmt.Println("fetching xkcd.com") for i := 1; i <= LAST; i++ { urls = append(urls, "https://xkcd.com/"+strconv.Itoa(i)+"/info.0.json") } results := fetchAll(urls, CONCURRENCY) for _, result := range results { if result.res != nil { collection.Items = append(collection.Items, result.res) } } saveAsJson(collection, CACHE_DIR) fmt.Printf("Fetched %d items in %.2fs\n", len(collection.Items), time.Since(start).Seconds()) return collection } func saveAsJson(data Collection, dir string) { if _, err := os.Stat(dir); err != nil { if os.IsNotExist(err) { os.Mkdir(dir, 0755) } else { log.Println(err) } } path := fmt.Sprint(dir, "/", CACHE_FILE) os.Remove(path) //fmt.Println(data) b, err := json.Marshal(data) if err != nil { log.Println(err) } //fmt.Println(b) ioutil.WriteFile(path, b, 0644) } func fetchAll(urls []string, concurrency int) []result { // buffered channel that will block at the concurrency limit semaphoreChan := make(chan struct{}, concurrency) // unbuffered channel -> will not block and collect http request results resultsChan := make(chan *result) defer func() { close(semaphoreChan) close(resultsChan) }() for i, url := range urls { // start a go routine with the index go func(i int, url string) { // this sends an empty struct into the semaphoreChan which // is basically saying add one to the limit, but when the // limit has been reached block until there is room semaphoreChan <- struct{}{} // send the request and put the response in a result struct // along with the index so we can sort them later along with // any error that might have happened res, err := http.Get(url) var item result var myresult Xkcd if res.StatusCode != 200 { fmt.Println("Bad status code", res.StatusCode, url) item = result{i, nil, err} } else if jsonErr := json.NewDecoder(res.Body).Decode(&myresult); jsonErr != nil { // res.Body.Close() // fmt.Println(jsonErr) // panic("JSON decoder unhandled error") item = result{i, nil, jsonErr} } else { myresult.Url = url item = result{i, &myresult, err} } res.Body.Close() // now we can send the result struct through the resultsChan resultsChan <- &item // once we're done it's we read from the semaphoreChan which // has the effect of removing one from the limit and allowing // another goroutine to start <-semaphoreChan }(i, url) } var results []result // start listening to resultsChan, once arrived append it to the result slice for { result := <-resultsChan results = append(results, *result) // stop when reached expected amount of urls if len(results) == len(urls) { break } } // we can sort here // sort.Slice() return results } func check(e error) { if e != nil { panic(e) } } // Reads index from file into memory func readAndParseIndexFile() ([]byte, error) { const indexFilePath = CACHE_DIR + "/" + CACHE_FILE bIndex, err := ioutil.ReadFile(indexFilePath) if err != nil { fmt.Println("Index file was not found") return nil, err } if bIndex != nil { return bIndex, nil } return nil, errors.New("file is empty") } func searchIndex(text string, collection Collection) { var foundIndexes []int fmt.Printf("Searching for %q\n", text) for i, item := range collection.Items { if strings.Contains(item.Transcript, text) || strings.Contains(item.Title, text) { foundIndexes = append(foundIndexes, i) // 0 url title text fmt.Printf("%4.4d %.20s %.20s %.20s\n", i, item.Url, item.Title, item.Transcript) } } if len(foundIndexes) == 0 { fmt.Printf("No items found") } } func runXkcd() { text := flag.String("text", "", "text to search in xkcd index") fetch := flag.Bool("fetch", false, "force fetching index") flag.Parse() index := initIndex(*fetch) searchIndex(*text, index) }
true
cb0d6fd246d2ef74488a0e54e3abc28546de3a64
Go
akure/demo_exchange_api
/lib/redis/redis.go
UTF-8
3,108
2.5625
3
[]
no_license
[]
no_license
package redis /* * Copyright © 2006-2019 Around25 SRL <[email protected]> * * Licensed under the Around25 Exchange License Agreement (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.around25.com/licenses/EXCHANGE_LICENSE * * 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. * * @author Cosmin Harangus <[email protected]> * @copyright 2006-2019 Around25 SRL <[email protected]> * @license EXCHANGE_LICENSE */ import ( "crypto/tls" "crypto/x509" "fmt" "time" radix "github.com/mediocregopher/radix/v3" ) // Config godoc type Config struct { Host string Username string Password string Port int SSLEnabled bool `mapstructure:"ssl_enabled"` CACert string `mapstructure:"cacert"` PoolSize int } // Client connection to redis server type Client struct { Config Config Pool *radix.Pool } // NewClient creates a new client func NewClient(config Config) *Client { return &Client{Config: config} } // Connect to a redis server func (client *Client) Connect() error { size := client.Config.PoolSize connFunc := func(network, addr string) (radix.Conn, error) { opts := []radix.DialOpt{} if client.Config.Password != "" { opts = append(opts, radix.DialAuthPass(client.Config.Password)) } if client.Config.SSLEnabled { if client.Config.CACert != "" { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM([]byte(client.Config.CACert)) if !ok { panic("failed to parse root certificate") } tlsConfig := &tls.Config{RootCAs: roots} opts = append(opts, radix.DialUseTLS(tlsConfig)) } else { tlsConfig := &tls.Config{InsecureSkipVerify: true} opts = append(opts, radix.DialUseTLS(tlsConfig)) } } return radix.Dial(network, addr, opts...) } defaultPoolOpts := []radix.PoolOpt{ radix.PoolConnFunc(connFunc), radix.PoolOnEmptyCreateAfter(1 * time.Second), radix.PoolRefillInterval(1 * time.Second), radix.PoolOnFullBuffer((size/3)+1, 1*time.Second), radix.PoolPingInterval(5 * time.Second / time.Duration(size+1)), radix.PoolPipelineConcurrency(size), // NOTE if 150us is changed the benchmarks need to be updated too radix.PoolPipelineWindow(150*time.Microsecond, 0), } pool, err := radix.NewPool("tcp", fmt.Sprintf("%s:%d", client.Config.Host, client.Config.Port), client.Config.PoolSize, defaultPoolOpts...) if err != nil { return err } client.Pool = pool return nil } // Disconnect -- close the connection to the redis instance func (client *Client) Disconnect() error { return client.Pool.Close() } // Exec processes a command on the redis server with the given arguments func (client *Client) Exec(val interface{}, command, key string, args ...interface{}) error { return client.Pool.Do(radix.FlatCmd(val, command, key, args...)) }
true
5ed29cf052395347f06b4bb95b52ac5cbe2383b9
Go
ethanfrogers/springo-config
/pkg/parser_test.go
UTF-8
2,679
3.234375
3
[]
no_license
[]
no_license
package pkg import ( "testing" ) var baseCase = ` foo: bar: foobar foo1: bar1: ${foo.bar} ` var baseResult = ` foo: bar: foobar foo1: bar1: foobar ` var withEnvironmentVariablesCase = ` foo: bar: ${TEST_CASE:tacobell} ` var withEnvironmentVariablesResult = ` foo: bar: HELLOWORLD ` var selfReferentalWithDefaultBase = ` services: taco: bell foo: bar: ${services.test:false} ` var selfReferentalWithDefaultResult = ` services: taco: bell foo: bar: false ` var environmentVariableWithUrlBase = ` foo: bar: ${TEST_ME:http://test.io} ` var environmentVariableWithUrlResult = ` foo: bar: http://test.io ` var onlyEnvironmentVariableBase = ` foo: bar: ${TEST_CASE} ` var onlyEnvionmentVariableResult = ` foo: bar: HELLOWORLD ` var recursiveBase = ` foo: bar: ${car.dar} car: dar: ${mar.lar} mar: lar: test ` var recursiveResult = ` foo: bar: test car: dar: test mar: lar: test ` var withContextBase = ` foo: bar: ${fizz.buzz} ` var withContextResult = ` foo: bar: fizzbuzz ` func TestParseAndEvaluateYAML(t *testing.T) { cases := []struct { test string expected string withFunc []WithFunc name string context map[string]interface{} }{ { test: baseCase, expected: baseResult, name: "base case", }, { name: "case with environment variables", test: withEnvironmentVariablesCase, expected: withEnvironmentVariablesResult, withFunc: []WithFunc{func() (string, interface{}) { return "Env", map[string]string{"TEST_CASE": "HELLOWORLD"} }}, }, { name: "self referential with default", test: selfReferentalWithDefaultBase, expected: selfReferentalWithDefaultResult, }, { name: "environment variable with url default", test: environmentVariableWithUrlBase, expected: environmentVariableWithUrlResult, }, { name: "only environment variable", test: onlyEnvironmentVariableBase, expected: onlyEnvionmentVariableResult, withFunc: []WithFunc{func() (string, interface{}) { return "Env", map[string]string{"TEST_CASE": "HELLOWORLD"} }}, }, { name: "recursive", test: recursiveBase, expected: recursiveResult, }, { name: "with context", test: withContextBase, expected: withContextResult, context: map[string]interface{}{"fizz": map[string]string{"buzz": "fizzbuzz"}}, }, } for _, c := range cases { r, err := ParseAndEvaluateYAML([]byte(c.test), c.context, c.withFunc...) if err != nil { t.Fatalf("case: %s, err: %s", c.name, err.Error()) } if string(r) != c.expected { t.Fatalf("expected: %s\ngot: %s\n", c.expected, r) } } }
true
9d6cd25c7150d79e51cbff818fa08e09ccb9069e
Go
isabst/zhihu
/utils/utils.go
UTF-8
2,799
2.890625
3
[]
no_license
[]
no_license
package utils import ( "crypto/md5" "fmt" "io" "regexp" "time" "github.com/gitobhub/zhihu/config" ) type Err struct { Message string Code int } func (err *Err) Error() string { return err.Message } const ( ErrAccountNotFound = 100000 + iota ErrIncorrectPassword ErrDuplicatedEmail ErrBadFullnameFormat ErrBadEmailFormat ErrBadPasswordFormat ) func ValidateFullname(fullname string) *Err { reg := regexp.MustCompile(`^[\p{Han}\w]+([\p{Han}\w\s.-]*)$`) println(fullname) if !reg.MatchString(fullname) { err := &Err{ Message: "名字中含有特殊字符", Code: ErrBadFullnameFormat, } return err } return nil } func ValidateUsername(username string) *Err { reg := regexp.MustCompile(`^[a-zA-Z0-9]+@(\w+).(\w{2,5})$`) //Email if !reg.MatchString(username) { err := &Err{ Message: "请输入正确的邮箱", Code: ErrBadEmailFormat, } return err } return nil } func ValidatePassword(password string) *Err { reg := regexp.MustCompile(`^(\w+[\w[:graph:]]*){6,}$`) if !reg.MatchString(password) { err := &Err{ Message: "密码格式不正确", Code: ErrBadPasswordFormat, } return err } return nil } func FormatUnixTime(dt int64) string { var res string now := time.Now() datetime := time.Unix(dt, 0) year, month, day := datetime.Date() nowYear, nowMonth, nowDay := now.Date() ydaYear, ydaMonth, ydaDay := time.Unix((now.Unix() - 86400), 0).Date() //yesterday if nowYear == year && nowMonth == month && nowDay == day { res = datetime.Format("15:04") } else if ydaYear == year && ydaMonth == month && ydaDay == day { res = "昨天 " + datetime.Format("15:04") } else { res = datetime.Format("2006-01-02") } return res } const ( Minute = 60 Hour = 3600 Day = 86400 Month = 86400 * 30 Year = 86400 * 30 * 12 ) func FormatBeforeUnixTime(dt int64) string { var res string now := time.Now().Unix() diff := now - dt switch { case diff < Minute: res = "刚刚" case diff < Hour && diff >= Minute: res = fmt.Sprintf("%d分钟前", diff/Minute) case diff < Day && diff >= Hour: res = fmt.Sprintf("%d小时前", diff/Hour) case diff < Month && diff >= Day: res = fmt.Sprintf("%d天前", diff/Day) case diff < Year && diff >= Month: res = fmt.Sprintf("%d个月前", diff/Month) case diff >= Year: res = fmt.Sprintf("%d年前", diff/Year) } return res } func EncryptPassword(username, password string) string { h := md5.New() io.WriteString(h, password) pwdMD5 := fmt.Sprintf("%x", h.Sum(nil)) io.WriteString(h, config.Server.Salt) io.WriteString(h, username) io.WriteString(h, pwdMD5) return fmt.Sprintf("%x", h.Sum(nil)) } func URLToken(urlToken *string, urlTokenCode int) { if urlTokenCode != 0 { *urlToken = fmt.Sprintf("%s-%d", *urlToken, urlTokenCode) } }
true
bf73083cae0706cb80b91c9f85de80b4aefb8e11
Go
Dedalum/translate-klingon
/http/client.go
UTF-8
2,971
3.328125
3
[]
no_license
[]
no_license
package http import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "time" ) type ( // Client holds the http client to query webpages Client struct { apiURL string http.Client } // ClientConfig holds the configuration for the HTTP client ClientConfig struct { APIHost string `json:"api_host"` } ) const ( apiPath = "api/v1/rest" apiCharacterSearch = "character/search" apiCharacter = "character" ) // NewClient returns a pointer to a new client func NewClient(config *ClientConfig) *Client { return &Client{ fmt.Sprintf("http://%s/%s", config.APIHost, apiPath), http.Client{ Timeout: time.Second * 3, }, } } // GetCharacterUIDs queries the API for a given character name. It returns a // list of characters (e.g. "Uhura" returns 3 different UIDs). func (c *Client) GetCharacterUIDs(name string) ([]string, error) { var characters []string if name == "" { return characters, fmt.Errorf("character name is empty") } var dataStr = []byte(fmt.Sprintf("name=%s", name)) resp, err := c.Post(fmt.Sprintf("%s/%s", c.apiURL, apiCharacterSearch), "data", bytes.NewBuffer(dataStr)) if err != nil { return characters, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) uids, err := parseUIDs(body) if err != nil { return characters, err } return uids, nil } // parseUIDs returns the list of UIDs for a character given the JSON // response func parseUIDs(jsonData []byte) ([]string, error) { var uids []string type character struct { UID string `json:"uid"` } var data struct { Characters []character `json:"characters"` } if err := json.Unmarshal(jsonData, &data); err != nil { return uids, err } for _, character := range data.Characters { uids = append(uids, character.UID) } return uids, nil } // GetCharacterSpeciesList returns the species for a given UID func (c *Client) GetCharacterSpeciesList(characterUID string) ([]string, error) { var speciesList []string if characterUID == "" { return speciesList, fmt.Errorf("character UID is empty") } resp, err := c.Get( fmt.Sprintf("%s/%s?uid=%s", c.apiURL, apiCharacter, characterUID)) if err != nil { return speciesList, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) speciesList, err = parseSpeciesList(body) if err != nil { return speciesList, err } return speciesList, nil } // parseSpecies returns the list of species for a character given the JSON // response func parseSpeciesList(jsonData []byte) ([]string, error) { var speciesList []string type character struct { SpeciesList []struct { Name string `json:"name"` } `json:"characterSpecies"` } var data struct { Character character `json:"character"` } if err := json.Unmarshal(jsonData, &data); err != nil { return speciesList, err } for _, species := range data.Character.SpeciesList { speciesList = append(speciesList, species.Name) } return speciesList, nil }
true
b386298f7abc068b6f665822e9a5cbbb8641b680
Go
mrpoundsign/adventofcode_2019
/day10/step2/main_test.go
UTF-8
1,323
3.328125
3
[]
no_license
[]
no_license
package main import "testing" func Test_point_angleTo(t *testing.T) { type fields struct { X int Y int } type args struct { p2 point } tests := []struct { name string fields fields args args want float64 }{ { name: "5,5 to 5,-16", fields: fields{X: 5, Y: 5}, args: args{point{X: 5, Y: -16}}, want: 0, }, { name: "5,5 to 8,2", fields: fields{X: 5, Y: 5}, args: args{point{X: 8, Y: 2}}, want: 45, }, { name: "5,5 to 16,5", fields: fields{X: 5, Y: 5}, args: args{point{X: 16, Y: 5}}, want: 90, }, { name: "5,5 to 16,16", fields: fields{X: 5, Y: 5}, args: args{point{X: 16, Y: 16}}, want: 135, }, { name: "5,5 to 5,16", fields: fields{X: 5, Y: 5}, args: args{point{X: 5, Y: 16}}, want: 180, }, { name: "5,5 to -16,5", fields: fields{X: 5, Y: 5}, args: args{point{X: -16, Y: 5}}, want: 270, }, { name: "5,5 to 0,0", fields: fields{X: 5, Y: 5}, args: args{point{X: 0, Y: 0}}, want: 315, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := point{ X: tt.fields.X, Y: tt.fields.Y, } if got := p.angleTo(tt.args.p2); got != tt.want { t.Errorf("point.angleTo() = %v, want %v", got, tt.want) } }) } }
true
58998b32b51a9ed00b5d007f6099a287ba637903
Go
tpisani/clubinho-go
/examples/err.go
UTF-8
169
2.546875
3
[]
no_license
[]
no_license
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("missing.txt") if err != nil { fmt.Println(err) } fmt.Println("bytes:", b) }
true
28ea0a2d120879189a64e8ad654d15dc51b80561
Go
huydinhle/golang-learning
/HackerRank/Algorithms/warmup/4-a-very-big-sum/main.go
UTF-8
522
3.53125
4
[]
no_license
[]
no_license
package main import "fmt" func main() { slice, _ := readData() fmt.Println(Addition(slice)) } // Addition get the sum of all numers func Addition(nums []int) int { total := 0 for _, v := range nums { total += v } return total } func readData() ([]int, error) { var length int _, err := fmt.Scanf("%d", &length) if err != nil { return nil, err } data := make([]int, length) for i := range data { _, err := fmt.Scanf("%d", &data[i]) if err != nil { return nil, err } } return data, nil }
true
f3b5137ef218ed99196d3d25713fb3cf278b6dcb
Go
NeuralSpaz/watcher
/watcher.go
UTF-8
2,738
2.796875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "crypto/md5" "encoding/hex" "encoding/json" "flag" "fmt" "io" "log" "os" "path/filepath" ) func init() { log.SetOutput(os.Stdout) } var fileStore *FileStateStore func main() { dir := flag.String("dir", "/root/", "the directory you want to monitor") clean := flag.Bool("clean", false, "rebuild the database") // store := flag.String("store", "store", "the file to store file states") flag.Parse() fmt.Println("Adding Dirs to watch ", *dir) fileStore = NewFileStateStore("./filedb.json") if !*clean { scandir, err := filepath.Abs(*dir) if err != nil { log.Fatalln(err) } err = filepath.Walk(scandir, visit) if err != nil { log.Printf("filepath.Walk() returned %v\n", err) } } if *clean { close(fileStore.save) fmt.Println("Rehashing files") for key := range fileStore.files { hash, err := hash_file_md5(key) if err != nil { log.Printf("problem hashing file: %s\n", key) delete(fileStore.files, key) } if err == nil { info, serr := os.Stat(key) if serr != nil { log.Printf("problem getting stats on file: %s\n", key) delete(fileStore.files, key) } if serr == nil { var fs FileState fs.Hash = hash fs.LastModified = info.ModTime() fs.Path = key fileStore.files[key] = fs } } // if err != nil { // log.Printf("Error adding to clean db %s: %v\n", fs, err) // } } var err = os.Remove("./filedb.json") if err != nil { log.Fatalln("unable to delete filedb") } f, err := os.OpenFile("./filedb.json", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) // f, err := os.Open("./filedb.json") if err != nil { log.Fatalln("unable to write clean db file") } // b := bufio.NewWriter(f) e := json.NewEncoder(f) defer f.Close() // defer b.Flush() for key := range fileStore.files { err = e.Encode(fileStore.files[key]) if err != nil { log.Println("FileStateStore Save:", err) } } } } func visit(path string, f os.FileInfo, err error) error { if !f.IsDir() { hash, err := hash_file_md5(path) if err != nil { log.Printf("Hashing err %v of file %s", err, path) return err } var fs FileState fs.Hash = hash fs.LastModified = f.ModTime() fs.Path = path err = fileStore.Put(fs) if err != nil { return err } } return nil } func hash_file_md5(filePath string) (string, error) { var returnMD5String string file, err := os.Open(filePath) if err != nil { return returnMD5String, err } defer file.Close() hash := md5.New() if _, err := io.Copy(hash, file); err != nil { return returnMD5String, err } hashInBytes := hash.Sum(nil)[:16] returnMD5String = hex.EncodeToString(hashInBytes) return returnMD5String, nil }
true
ab910bccdd90608cf88ad7823aa7ef9158806bbc
Go
brongineers/pgcenter
/internal/view/view_test.go
UTF-8
6,244
2.609375
3
[]
no_license
[]
no_license
package view import ( "github.com/lesovsky/pgcenter/internal/query" "github.com/stretchr/testify/assert" "testing" ) func TestNew(t *testing.T) { v := New() assert.Equal(t, 18, len(v)) // 18 is the total number of views have to be returned } func TestViews_Configure(t *testing.T) { testcases := []struct { version int recovery string trackCommit string querylen int }{ // v13 matrix {version: 130000, recovery: "f", trackCommit: "on", querylen: 256}, {version: 130000, recovery: "f", trackCommit: "on", querylen: 0}, {version: 130000, recovery: "f", trackCommit: "off", querylen: 256}, {version: 130000, recovery: "f", trackCommit: "off", querylen: 0}, {version: 130000, recovery: "t", trackCommit: "on", querylen: 256}, {version: 130000, recovery: "t", trackCommit: "on", querylen: 0}, {version: 130000, recovery: "t", trackCommit: "off", querylen: 256}, {version: 130000, recovery: "t", trackCommit: "off", querylen: 0}, // v12 matrix {version: 120000, recovery: "f", trackCommit: "on", querylen: 256}, {version: 120000, recovery: "f", trackCommit: "on", querylen: 0}, {version: 120000, recovery: "f", trackCommit: "off", querylen: 256}, {version: 120000, recovery: "f", trackCommit: "off", querylen: 0}, {version: 120000, recovery: "t", trackCommit: "on", querylen: 256}, {version: 120000, recovery: "t", trackCommit: "on", querylen: 0}, {version: 120000, recovery: "t", trackCommit: "off", querylen: 256}, {version: 120000, recovery: "t", trackCommit: "off", querylen: 0}, // v11 matrix {version: 110000, recovery: "f", trackCommit: "on", querylen: 256}, {version: 110000, recovery: "f", trackCommit: "on", querylen: 0}, {version: 110000, recovery: "f", trackCommit: "off", querylen: 256}, {version: 110000, recovery: "f", trackCommit: "off", querylen: 0}, {version: 110000, recovery: "t", trackCommit: "on", querylen: 256}, {version: 110000, recovery: "t", trackCommit: "on", querylen: 0}, {version: 110000, recovery: "t", trackCommit: "off", querylen: 256}, {version: 110000, recovery: "t", trackCommit: "off", querylen: 0}, // v9.6 matrix {version: 90600, recovery: "f", trackCommit: "on", querylen: 256}, {version: 90600, recovery: "f", trackCommit: "on", querylen: 0}, {version: 90600, recovery: "f", trackCommit: "off", querylen: 256}, {version: 90600, recovery: "f", trackCommit: "off", querylen: 0}, {version: 90600, recovery: "t", trackCommit: "on", querylen: 256}, {version: 90600, recovery: "t", trackCommit: "on", querylen: 0}, {version: 90600, recovery: "t", trackCommit: "off", querylen: 256}, {version: 90600, recovery: "t", trackCommit: "off", querylen: 0}, // v9.5 matrix {version: 90500, recovery: "f", trackCommit: "on", querylen: 256}, {version: 90500, recovery: "f", trackCommit: "on", querylen: 0}, {version: 90500, recovery: "f", trackCommit: "off", querylen: 256}, {version: 90500, recovery: "f", trackCommit: "off", querylen: 0}, {version: 90500, recovery: "t", trackCommit: "on", querylen: 256}, {version: 90500, recovery: "t", trackCommit: "on", querylen: 0}, {version: 90500, recovery: "t", trackCommit: "off", querylen: 256}, {version: 90500, recovery: "t", trackCommit: "off", querylen: 0}, // v9.4 matrix {version: 90400, recovery: "f", trackCommit: "on", querylen: 256}, {version: 90400, recovery: "f", trackCommit: "on", querylen: 0}, {version: 90400, recovery: "f", trackCommit: "off", querylen: 256}, {version: 90400, recovery: "f", trackCommit: "off", querylen: 0}, {version: 90400, recovery: "t", trackCommit: "on", querylen: 256}, {version: 90400, recovery: "t", trackCommit: "on", querylen: 0}, {version: 90400, recovery: "t", trackCommit: "off", querylen: 256}, {version: 90400, recovery: "t", trackCommit: "off", querylen: 0}, } for _, tc := range testcases { views := New() opts := query.NewOptions(tc.version, tc.recovery, tc.trackCommit, tc.querylen, "public") err := views.Configure(opts) assert.NoError(t, err) switch tc.version { case 130000: if tc.trackCommit == "on" { assert.Equal(t, query.PgStatReplicationExtended, views["replication"].QueryTmpl) assert.Equal(t, 17, views["replication"].Ncols) } else { assert.Equal(t, query.PgStatReplicationDefault, views["replication"].QueryTmpl) } case 120000: if tc.trackCommit == "on" { assert.Equal(t, query.PgStatReplicationExtended, views["replication"].QueryTmpl) assert.Equal(t, 17, views["replication"].Ncols) } else { assert.Equal(t, query.PgStatReplicationDefault, views["replication"].QueryTmpl) } assert.Equal(t, query.PgStatStatementsTimingPG12, views["statements_timings"].QueryTmpl) case 110000: if tc.trackCommit == "on" { assert.Equal(t, query.PgStatReplicationExtended, views["replication"].QueryTmpl) assert.Equal(t, 17, views["replication"].Ncols) } else { assert.Equal(t, query.PgStatReplicationDefault, views["replication"].QueryTmpl) } assert.Equal(t, query.PgStatDatabasePG11, views["databases"].QueryTmpl) assert.Equal(t, 17, views["databases"].Ncols) assert.Equal(t, [2]int{1, 15}, views["databases"].DiffIntvl) case 90600: if tc.trackCommit == "on" { assert.Equal(t, query.PgStatReplication96Extended, views["replication"].QueryTmpl) assert.Equal(t, 14, views["replication"].Ncols) } else { assert.Equal(t, query.PgStatReplication96, views["replication"].QueryTmpl) assert.Equal(t, 12, views["replication"].Ncols) } assert.Equal(t, query.PgStatActivity96, views["activity"].QueryTmpl) assert.Equal(t, 13, views["activity"].Ncols) case 90500: assert.Equal(t, query.PgStatActivity95, views["activity"].QueryTmpl) assert.Equal(t, 12, views["activity"].Ncols) } for _, v := range views { assert.NotEqual(t, "", v.Query) } } } func TestView_VersionOK(t *testing.T) { testcases := []struct { version int total int }{ {version: 130000, total: 18}, {version: 120000, total: 15}, {version: 110000, total: 13}, {version: 100000, total: 13}, } for _, tc := range testcases { views := New() var total int for _, v := range views { if v.VersionOK(tc.version) { total++ } } assert.Equal(t, tc.total, total) } }
true
794a7cfe36b161bb4925ebac7cca541c20ea730b
Go
JasonSpeak/LearnGoWithTest
/BaseKnowledge/maps/Dictionary.go
UTF-8
605
3.6875
4
[]
no_license
[]
no_license
package maps import "errors" var ( ErrNotFound = errors.New("could not find the word you were looking for") ErrWordExists = errors.New("cannot add word because it already exists") ) type Dictionary map[string]string func (dictionary Dictionary) Search(key string) (string, error) { definition, ok := dictionary[key] if !ok { return "", ErrNotFound } return definition, nil } func (d Dictionary) Add(key, value string) error { _, isExist := d.Search(key) switch isExist { case ErrNotFound: d[key] = value case nil: return ErrWordExists default: return isExist } return nil }
true
9f8be2bdcde3740fd06dce8dc51e08414944616b
Go
shouliang/Development
/Go/go_inaction/src/chapter6/listing07/listing07.go
UTF-8
1,172
4.15625
4
[]
no_license
[]
no_license
// 展示如何创建goroutine以及调度器的行为 package main import ( "fmt" "runtime" "sync" ) func main() { // 分配2个逻辑处理器给调度器使用 // 2个逻辑处理器,goroutine是真正的同时运行,而不是CPU时间片切换 runtime.GOMAXPROCS(2) // wg 用来等待程序完成 // 计数加2,表示要等待2个goroutine // WaitGroup是一个计数信号量,值大于0,Wait()方法就会阻塞 var wg sync.WaitGroup wg.Add(2) fmt.Println("Start Goroutines") // go关键字后声明一个匿名函数来运行一个goroutine go func() { // Schedule the call to Done to tell main we are done defer wg.Done() for count := 0; count < 3; count++ { for char := 'a'; char < 'a'+26; char++ { fmt.Printf("%c", char) } } }() go func() { defer wg.Done() // Dispaly the alphebet three times for count := 0; count < 3; count++ { for char := 'A'; char < 'A'+26; char++ { fmt.Printf("%c", char) } } }() // 等待goroutines结束 // 各个goroutine是并发执行的,而不是按照代码编写的顺序 fmt.Println("Waiting to Finish") wg.Wait() fmt.Printf("\nTerminating Program") }
true
32be905c17e55a9d8ec8b85419bd909d91f4e310
Go
konatu/study_tour_of_go
/struct/field_access.go
UTF-8
119
3.140625
3
[]
no_license
[]
no_license
package main import( "fmt" ) type st struct{ x int y int } func main(){ v := st{55, 18} fmt.Println(v.x) }
true
9715668ff9f96d3f467f1b1e49e9f104c0875da6
Go
footprint-it-solutions/kube-annotate
/annotator/mutator_test.go
UTF-8
1,098
2.75
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package annotator import ( "testing" "github.com/stretchr/testify/assert" ) func TestCreatePatchFromAnnotations(t *testing.T) { podAnnotations := map[string]string{ "hello": "world", } rulesAnnotations := map[string]string{ "log": "enabled", } patch := createPatchFromAnnotations(podAnnotations, rulesAnnotations) assert.Equal(t, "replace", patch.Op) assert.Equal(t, "/metadata/annotations", patch.Path) assert.IsType(t, podAnnotations, patch.Value) valuesAsMap := patch.Value.(map[string]string) assert.Len(t, valuesAsMap, 2) assert.Equal(t, "world", valuesAsMap["hello"]) assert.Equal(t, "enabled", valuesAsMap["log"]) } func TestCreatePatchFromNilAnnotations(t *testing.T) { rulesAnnotations := map[string]string{ "log": "enabled", } patch := createPatchFromAnnotations(nil, rulesAnnotations) assert.Equal(t, "add", patch.Op) assert.Equal(t, "/metadata/annotations", patch.Path) assert.IsType(t, make(map[string]string), patch.Value) valuesAsMap := patch.Value.(map[string]string) assert.Len(t, valuesAsMap, 1) assert.Equal(t, "enabled", valuesAsMap["log"]) }
true
99e76736862f0856b0b2aada93f189ee1bd7ab9a
Go
philkry/drivers
/tplink/hs1xx_hal.go
UTF-8
1,084
2.578125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package tplink import ( "encoding/json" "fmt" "github.com/reef-pi/hal" "github.com/reef-pi/rpi/i2c" ) type HS1xxPlugConfig struct { Address string `json:"address"` } var meta = hal.Metadata{ Name: "tplink-hs1xx", Description: "Supports tplink hs1xx series smart plugs", Capabilities: []hal.Capability{ hal.Output, }, } func HALAdapter(c []byte, _ i2c.Bus) (hal.Driver, error) { var conf HS1xxPlugConfig if err := json.Unmarshal(c, &conf); err != nil { return nil, err } return NewHS1xxPlug(conf.Address), nil } func (p *HS1xxPlug) Metadata() hal.Metadata { return meta } func (p *HS1xxPlug) Name() string { return meta.Name } func (p *HS1xxPlug) OutputPins() []hal.OutputPin { return []hal.OutputPin{p} } func (p *HS1xxPlug) OutputPin(i int) (hal.OutputPin, error) { if i != 0 { return nil, fmt.Errorf("invalid pin: %d", i) } return p, nil } func (p *HS1xxPlug) Write(state bool) error { if state { return p.On() } return p.Off() } func (p *HS1xxPlug) LastState() bool { return p.state } func (p *HS1xxPlug) Close() error { return nil }
true
def8d3abbb3204daeef2f5cac9cf095aba2ec9dc
Go
Myavuz34/GoExamples
/JSON/main.go
UTF-8
2,186
3.4375
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "fmt" "os" ) type Name struct { Family string Personel string } type Email struct { ID int Kind string Address string } type Interest struct { ID int Name string } type Person struct { ID int FirstName string LastName string UserName string Gender string Name Name Email []Email Interest []Interest } func GetPerson(p *Person) string { return p.FirstName + " " + p.LastName } func GetPersonEmailAddress(p *Person, i int) string { return p.Email[i].Address } func GetPersonEmail(p *Person, i int) Email { return p.Email[i] } func WriteMessage(msg string) { fmt.Println(msg) } func WriteStarLine() { fmt.Println("*************************") } func CheckError(err error) { if err != nil { fmt.Println("Fata Error: ", err.Error()) os.Exit(1) } } func SaveJSON(fileName string, key interface{}) { outFile, err := os.Create(fileName) CheckError(err) encoder := json.NewEncoder(outFile) err = encoder.Encode(key) CheckError(err) outFile.Close() } func main() { person := Person{ ID: 10, FirstName: "Mustafa", LastName: "Yavuz", UserName: "Myavuz", Gender: "E", Name: Name{Family: "bididibid", Personel: "Mustafa"}, Email: []Email{ Email{ID: 1, Kind: "Work", Address: "[email protected]"}, Email{ID: 2, Kind: "Home", Address: "[email protected]"}, }, Interest: []Interest{ Interest{ID: 1, Name: "Go"}, Interest{ID: 2, Name: "C#"}, Interest{ID: 3, Name: "Python"}, }, } WriteMessage("Reading Operation Started") WriteMessage("Personel Fullname") WriteStarLine() res := GetPerson(&person) WriteMessage(res) WriteStarLine() WriteMessage("\n") WriteMessage("Personel Emil With Index") WriteStarLine() resEmail := GetPersonEmailAddress(&person, 1) WriteMessage(resEmail) WriteStarLine() WriteMessage("\n") WriteMessage("Personel Email Object winth Index") WriteStarLine() resEmail2 := GetPersonEmail(&person, 0) fmt.Println(resEmail2) WriteStarLine() WriteMessage("Reading Operation Ended") WriteMessage("\n") WriteMessage("Writing Operation Started") SaveJSON("person.json", person) WriteMessage("Writing Operation Ended") }
true
84a9d3c53a848f361a93707cbcc2b7e6c61423e0
Go
CristoferNava/cardinal
/db/removeTweet.go
UTF-8
598
2.796875
3
[]
no_license
[]
no_license
package db import ( "context" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) // RemoveTweet removes a tweet given an tweetID and a userID func RemoveTweet(tweetID, userID string) error { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() db := MongoConnection.Database("cardinal") tweetsCollection := db.Collection("tweets") objID, _ := primitive.ObjectIDFromHex(tweetID) condition := bson.M{ "_id": objID, "userID": userID, } _, err := tweetsCollection.DeleteOne(ctx, condition) return err }
true
72340b645f48f7dc9259e6845482f8bd02c5cce5
Go
chebrolus/golearn
/stringutil/palindrome_test.go
UTF-8
1,010
3.40625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package stringutil import ( "math/rand" "testing" ) func TestIsPalindrome(t *testing.T) { // test data with expected result var tests = []struct { s string isPalindrome bool }{ {"", false}, {"m", true}, {"ace", false}, {"ana", true}, {"anna", true}, {"aloha", false}, {"alola", true}, {"civic", true}, {"toyota", false}, {"not a palindrome", false}, } // for each entry in test data apply function and compare with expected result for _, c := range tests { got := isPalindrome(c.s) if got != c.isPalindrome { // fail if the result doesn't match expected t.Errorf("isPalindrome(%v) == %v, want %v", c.s, got, c.isPalindrome) } } } func BenchmarkIsPalindrome(b *testing.B) { // input array ip := []string{"", "civic", "a", "aloha", "ahoha", "palindrome", "verylongstringforpalindrometest", "aaaaabbbbcccddeddcccbbbbaaaaa"} for i := 1; i < b.N; i++ { // random input selection from the given input array isPalindrome(ip[rand.Intn(len(ip))]) } }
true
3bfb325a91c6f1d57b623439d39a468bf5fe4f00
Go
liampulles/cabiria
/cmd/cabiria-generate/core/video.go
UTF-8
4,565
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package core import ( "fmt" "runtime" "sync" "github.com/liampulles/cabiria/pkg/array" "github.com/liampulles/cabiria/pkg/image" "github.com/liampulles/cabiria/pkg/intertitle" cabiriaMath "github.com/liampulles/cabiria/pkg/math" "github.com/liampulles/cabiria/pkg/video" "github.com/jinzhu/copier" ) // VideoConfiguration provides configuration options necessary to extract video information type VideoConfiguration interface { VideoPath() string FrameOutputDirectory() string PredictorPath() string SmoothingClosingThreshold() uint SmoothingOpeningThreshold() uint } // VideoInformation provides relevant information about the video (including // the intertitles) type VideoInformation struct { VideoFPS float64 VideoWidth int VideoHeight int IntertitleRanges []intertitle.Range } // ExtractVideoInformation reads relevant information from the input video func ExtractVideoInformation(config VideoConfiguration) (VideoInformation, error) { fmt.Print("Extracting video information") // Extract frames to configured dir framePaths, err := video.ExtractFrames(config.VideoPath(), config.FrameOutputDirectory()) if err != nil { return VideoInformation{}, err } printProgressDot() // Predict intertitle frames predictions, err := predictIntertitles(framePaths, config.PredictorPath()) if err != nil { return VideoInformation{}, err } printProgressDot() // Smooth intertitle frames smoothIntertitles(predictions, config.SmoothingClosingThreshold(), config.SmoothingOpeningThreshold()) printProgressDot() // Get some basic video info basicInfo, err := video.GetBasicInformation(config.VideoPath()) if err != nil { return VideoInformation{}, err } printProgressDot() // Extract intertitle timings interRanges, err := intertitle.MapRanges(predictions, basicInfo.FPS, framePaths) if err != nil { return VideoInformation{}, err } printDone() return VideoInformation{ VideoFPS: basicInfo.FPS, VideoHeight: basicInfo.Height, VideoWidth: basicInfo.Width, IntertitleRanges: interRanges, }, nil } func predictIntertitles(framePaths []string, predictorPath string) ([]bool, error) { predictor, err := intertitle.Load(predictorPath) if err != nil { return nil, err } // Split into workers _, workerCount := cabiriaMath.MinMaxInt(1, runtime.NumCPU()/2) var wg sync.WaitGroup framePathsDivided := divideStringArray(framePaths, workerCount) predictionsDivided := setupPredictionsArrays(len(framePaths), workerCount) errors := make([]error, workerCount) for i := 0; i < workerCount; i++ { wg.Add(1) // Setup vars var predictorCopy intertitle.Predictor copier.Copy(&predictorCopy, &predictor) go predictIntertitlesWorker(&predictorCopy, framePathsDivided[i], predictionsDivided[i], errors[i], &wg) } wg.Wait() // Check for errors for _, err := range errors { if err != nil { return nil, err } } // Construct predictions array var predictions []bool for _, elem := range predictionsDivided { predictions = append(predictions, elem...) } return predictions, nil } func predictIntertitlesWorker(predictor *intertitle.Predictor, framePaths []string, predictions []bool, err error, wg *sync.WaitGroup) { defer wg.Done() for i, path := range framePaths { // if i%3 == 0 { // fmt.Printf("Processing: %f%%\n", float64(i*100)/float64(len(framePaths))) // } img, potentialErr := image.GetPNG(path) if potentialErr != nil { err = potentialErr return } prediction, potentialErr := predictor.PredictSingle(img) if potentialErr != nil { err = potentialErr return } predictions[i] = prediction } printProgressDot() } func smoothIntertitles(intertitles []bool, closingThreshold, openingThreshold uint) { array.CloseBoolArray(intertitles, closingThreshold) array.OpenBoolArray(intertitles, openingThreshold) } func divideStringArray(many []string, parts int) [][]string { var divided [][]string chunkSize := (len(many) + parts - 1) / parts for i := 0; i < len(many); i += chunkSize { end := i + chunkSize if end > len(many) { end = len(many) } divided = append(divided, many[i:end]) } return divided } func setupPredictionsArrays(total int, parts int) [][]bool { var divided [][]bool chunkSize := (total + parts - 1) / parts for i := 0; i < total; i += chunkSize { end := i + chunkSize if end > total { end = total } divided = append(divided, make([]bool, end-i)) } return divided } func printProgressDot() { fmt.Print(".") } func printDone() { fmt.Print("DONE\n") }
true
2ebcba280650d26bbb2e5f6cf79970dafeea7c1c
Go
dhruv-bansal/golang-exploration
/basic/datatypes/main.go
UTF-8
671
4.28125
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "fmt" func main() { // explicit declaration var i int i = 32 // explicit initialization fmt.Println(i) // explicit declaration and initialization var f float32 = 3.14 fmt.Println(f) // implicit declaration with initialization title := "go data types" fmt.Println("Title", title) // implicit declaration of Boolean b := false fmt.Println("Boolean", b) // complex data type is built in GO c := complex(3, 4) fmt.Println("Complex Variable", c) // multi assignment in the go // two variables in the left and two functions in the right real, img := real(c), imag(c) fmt.Println("Real number and imaginary number", real, img) }
true
077aa6b7fc2a4582ed32c9af42c72fbb056f84d8
Go
code-mv/logreporter-go-core
/utils/utils.go
UTF-8
424
3.578125
4
[]
no_license
[]
no_license
package utils // ItemInSlice is a utility function that returns true // if list contains the interface a func ItemInSlice(a interface{}, list []interface{}) bool { for _, b := range list { if b == a { return true } } return false } // AddAll adds all map entries from a source map to a target map func AddAll(source map[string]string, target map[string]string) { for k, v := range source { target[k] = v } }
true
97cb15ce143531c1e5f57428dc58ac94bd3b6bb6
Go
BitonicNL/btcd
/txscript/sigcache.go
UTF-8
4,109
2.765625
3
[ "ISC" ]
permissive
[ "ISC" ]
permissive
// Copyright (c) 2015 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package txscript import ( "bytes" "crypto/rand" "sync" "github.com/btcsuite/btcd/btcec" "github.com/btcsuite/btcd/wire" ) // sigInfo represents an entry in the SigCache. Entries in the sigcache are a // 3-tuple: (sigHash, sig, pubKey). type sigInfo struct { sigHash wire.ShaHash sig string pubKey string } // SigCache implements an ECDSA signature verification cache with a randomized // entry eviction policy. Only valid signatures will be added to the cache. The // benefits of SigCache are two fold. Firstly, usage of SigCache mitigates a DoS // attack wherein an attack causes a victim's client to hang due to worst-case // behavior triggered while processing attacker crafted invalid transactions. A // detailed description of the mitigated DoS attack can be found here: // https://bitslog.wordpress.com/2013/01/23/fixed-bitcoin-vulnerability-explanation-why-the-signature-cache-is-a-dos-protection/. // Secondly, usage of the SigCache introduces a signature verification // optimization which speeds up the validation of transactions within a block, // if they've already been seen and verified within the mempool. type SigCache struct { sync.RWMutex validSigs map[sigInfo]struct{} maxEntries uint } // NewSigCache creates and initializes a new instance of SigCache. Its sole // parameter 'maxEntries' represents the maximum number of entries allowed to // exist in the SigCache at any particular moment. Random entries are evicted // to make room for new entries that would cause the number of entries in the // cache to exceed the max. func NewSigCache(maxEntries uint) *SigCache { return &SigCache{validSigs: make(map[sigInfo]struct{}), maxEntries: maxEntries} } // Exists returns true if an existing entry of 'sig' over 'sigHash' for public // key 'pubKey' is found within the SigCache. Otherwise, false is returned. // // NOTE: This function is safe for concurrent access. Readers won't be blocked // unless there exists a writer, adding an entry to the SigCache. func (s *SigCache) Exists(sigHash wire.ShaHash, sig *btcec.Signature, pubKey *btcec.PublicKey) bool { info := sigInfo{sigHash, string(sig.Serialize()), string(pubKey.SerializeCompressed())} s.RLock() _, ok := s.validSigs[info] s.RUnlock() return ok } // Add adds an entry for a signature over 'sigHash' under public key 'pubKey' // to the signature cache. In the event that the SigCache is 'full', an // existing entry is randomly chosen to be evicted in order to make space for // the new entry. // // NOTE: This function is safe for concurrent access. Writers will block // simultaneous readers until function execution has concluded. func (s *SigCache) Add(sigHash wire.ShaHash, sig *btcec.Signature, pubKey *btcec.PublicKey) { s.Lock() defer s.Unlock() if s.maxEntries <= 0 { return } // If adding this new entry will put us over the max number of allowed // entries, then evict an entry. if uint(len(s.validSigs)+1) > s.maxEntries { // Generate a cryptographically random hash. randHashBytes := make([]byte, wire.HashSize) _, err := rand.Read(randHashBytes) if err != nil { // Failure to read a random hash results in the proposed // entry not being added to the cache since we are // unable to evict any existing entries. return } // Try to find the first entry that is greater than the random // hash. Use the first entry (which is already pseudo random due // to Go's range statement over maps) as a fall back if none of // the hashes in the rejected transactions pool are larger than // the random hash. var foundEntry sigInfo for sigEntry := range s.validSigs { if foundEntry.sig == "" { foundEntry = sigEntry } if bytes.Compare(sigEntry.sigHash.Bytes(), randHashBytes) > 0 { foundEntry = sigEntry break } } delete(s.validSigs, foundEntry) } info := sigInfo{sigHash, string(sig.Serialize()), string(pubKey.SerializeCompressed())} s.validSigs[info] = struct{}{} }
true
99deb9dd1a9abd3994470325066b096f1a218005
Go
nju04zq/pegasus
/src/pegasus/cfgagent/meta.go
UTF-8
1,146
2.71875
3
[]
no_license
[]
no_license
package main import ( "net/http" "pegasus/log" "pegasus/server" "pegasus/util" "sync" ) type meta struct { mutex sync.Mutex masterAddr string } var cfgmeta = meta{} func registerMaster(addr string) (err error) { log.Info("Handle register master request as %s", addr) cfgmeta.mutex.Lock() defer func() { cfgmeta.mutex.Unlock() if err == nil { log.Info("Register master as %s", addr) } }() // TODO comment out for test convenience //if cfgmeta.masterAddr != "" { // err = fmt.Errorf("Master already registered as %s", cfgmeta.masterAddr) // return //} cfgmeta.masterAddr = addr return } func getMasterAddr() (addr string) { cfgmeta.mutex.Lock() defer func() { cfgmeta.mutex.Unlock() log.Info("Get master addr as %s", addr) }() addr = cfgmeta.masterAddr return } func getMasterAddrHandler(w http.ResponseWriter, r *http.Request) { server.FmtResp(w, nil, getMasterAddr()) } func postMasterHandler(w http.ResponseWriter, r *http.Request) { addr, err := util.HttpReadRequestTextBody(r) if err != nil { server.FmtResp(w, err, "") return } err = registerMaster(addr) server.FmtResp(w, err, "") }
true
60b67d7b715ad6a42d1831db6d9a7aaf2618b73d
Go
fr34k8/hmgo
/internal/hm/thermal/weatherevent.go
UTF-8
1,924
2.78125
3
[]
permissive
[]
permissive
package thermal import ( "bytes" "fmt" "html/template" "github.com/prometheus/client_golang/prometheus" ) var ( weatherEventTemperature = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: prometheusNamespace, Name: "WeatherEventTemperature", Help: "Temperature in degC", }, []string{"address", "name"}) weatherEventHumidity = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: prometheusNamespace, Name: "WeatherEventHumidity", Help: "Humidity in percentage points", }, []string{"address", "name"}) ) func init() { prometheus.MustRegister(weatherEventTemperature) prometheus.MustRegister(weatherEventHumidity) } type WeatherEvent struct { Temperature float64 // in degC Humidity uint64 // in percentage points } var weTmpl = template.Must(template.New("weatherevent").Parse(` <strong>Weather:</strong><br> Temperature: {{ .Temperature }} ℃<br> Humidity: {{ .Humidity }}%<br> `)) func (we *WeatherEvent) HTML() template.HTML { var buf bytes.Buffer if err := weTmpl.Execute(&buf, we); err != nil { return template.HTML(template.HTMLEscapeString(err.Error())) } return template.HTML(buf.String()) } func (tc *ThermalControl) DecodeWeatherEvent(payload []byte) (*WeatherEvent, error) { // c.f. <frame id="WEATHER_EVENT"> in rftypes/tc.xml if got, want := len(payload), 3; got != want { return nil, fmt.Errorf("unexpected payload size: got %d, want %d", got, want) } we := &WeatherEvent{ Temperature: float64((int16(payload[0])<<8|int16(payload[1]))&0x3FFF) / 10, Humidity: uint64(payload[2]), } weatherEventTemperature.With(prometheus.Labels{"name": tc.Name(), "address": tc.AddrHex()}).Set(we.Temperature) weatherEventHumidity.With(prometheus.Labels{"name": tc.Name(), "address": tc.AddrHex()}).Set(float64(we.Humidity)) tc.latestMu.Lock() defer tc.latestMu.Unlock() tc.latestWeatherEvent = we return we, nil }
true
7962f1bd173205e2eac0ec53ddffd06b6b36e59a
Go
tmacbg/ask-gamblers-go-api
/platform/data/data.go
UTF-8
1,968
3.265625
3
[]
no_license
[]
no_license
package data import ( "database/sql" "fmt" ) type Feed struct { DB *sql.DB } type Item struct { Name string `json:"name"` } func (feed *Feed) GetCountries() []Item { items := []Item{} rows, _ := feed.DB.Query("SELECT name from countries") var country string for rows.Next() { rows.Scan(&country) item := Item{ Name: country, } items = append(items, item) } return items } func (feed *Feed) GetCasinos() []Item { allCasinos := []Item{} rows, _ := feed.DB.Query("Select DISTINCT(name) from websites") var casino string for rows.Next() { rows.Scan(&casino) casinoItem := Item{ Name: casino, } allCasinos = append(allCasinos, casinoItem) } return allCasinos } func (feed *Feed) Get(query string) []Item { items := []Item{} stm, _ := feed.DB.Prepare(`SELECT DISTINCT(w.name) from websites as w JOIN websites_countries as w_c on w_c.website_id = w.id JOIN countries as c on w_c.country_id = c.id where c.name = ? `) rows, _ := stm.Query(query) var website string for rows.Next() { rows.Scan(&website) item := Item{ Name: website, } items = append(items, item) } return items } func (feed *Feed) GetBlockedCountries(query string) []Item { items := []Item{} stm, _ := feed.DB.Prepare(`SELECT DISTINCT(lower(c.code) ) as code from websites as w JOIN websites_countries as w_c on w_c.website_id = w.id JOIN countries as c on w_c.country_id = c.id where w.name like ?`) queryString := fmt.Sprintf("%s%%", query) fmt.Print(queryString) rows, err := stm.Query(queryString) if err != nil { fmt.Print(err) } var countryCode string for rows.Next() { rows.Scan(&countryCode) item := Item{ Name: countryCode, } items = append(items, item) } return items } func NewConnection(db *sql.DB) *Feed { stm, _ := db.Prepare("CREATE TABLE IF NOT EXISTS countries ( id integer PRIMARY KEY, name text);") stm.Exec() return &Feed{ DB: db, } }
true
2fae87e56dea5cb05ef926970ca3a5b671fb9483
Go
mazzegi/wasa
/example/todomvc/app/app.go
UTF-8
1,213
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package app import ( "github.com/mazzegi/wasa" "github.com/mazzegi/wasa/example/todomvc/backend" "github.com/mazzegi/wasa/wlog" ) type App struct { root *wasa.Elt doc *wasa.Document backend *backend.Backend header *Header main *Main footer *Footer } func New(be *backend.Backend) (*App, error) { doc, err := wasa.NewDocument("WASA / TodoMVC") if err != nil { return nil, err } a := &App{ root: wasa.NewElt("section", wasa.Class("todoapp")), doc: doc, backend: be, } a.backend.Subscribe(func() { a.render() }) api := doc.GetGlobal("wasaenv", "api").String() wlog.Infof("api=(%s)", api) loc := doc.Location() wlog.Infof("loc=(%s)", loc) a.setupUI() a.render() return a, nil } func (a *App) Run() { wlog.Infof("app: run ...") a.doc.Run(a.root) wlog.Infof("app: run ... done") } func (a *App) setupUI() { a.header = NewHeader(a.doc, a.backend) a.main = NewMain(a.doc, a.backend) a.footer = NewFooter(a.doc, a.backend) a.root.Append(a.header.Elt(), a.main.Elt(), a.footer.Elt()) } func (a *App) render() { wlog.Infof("app: render ...") a.header.render() a.main.render() a.footer.render() a.root.Invalidate() wlog.Infof("app: render ... done") }
true
1022351d34fb8428d01d3ac6bfdd324837a2fa6f
Go
logic-building/functional-go
/internal/template/dropwhile.go
UTF-8
1,008
3.21875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package template // DropWhile is template to generate function(DropWhhile) for user defined data type func DropWhile() string { return ` func DropWhile<CONDITIONAL_TYPE>(f func(<TYPE>) bool, list []<TYPE>) []<TYPE> { if f == nil { return []<TYPE>{} } var newList []<TYPE> for i, v := range list { if !f(v) { listLen := len(list) newList = make([]<TYPE>, listLen-i) j := 0 for i < listLen { newList[j] = list[i] i++ j++ } return newList } } return newList } ` } // DropWhilePtr is template to generate function(DropWhhile) for user defined data type func DropWhilePtr() string { return ` func DropWhile<CONDITIONAL_TYPE>Ptr(f func(*<TYPE>) bool, list []*<TYPE>) []*<TYPE> { if f == nil { return []*<TYPE>{} } var newList []*<TYPE> for i, v := range list { if !f(v) { listLen := len(list) newList = make([]*<TYPE>, listLen-i) j := 0 for i < listLen { newList[j] = list[i] i++ j++ } return newList } } return newList } ` }
true
fc7190015e88744246fa4802c5f4eb65c2ba385b
Go
robertpknight/knightlygo
/GolangToddMcLeod/Exercises/ninja_level6/exercise9/Exercise9.go
UTF-8
580
4.0625
4
[]
no_license
[]
no_license
package exercise9 import ( "fmt" "strings" ) // Exercise9 ... code for ninja level 6 exercise 9 func Exercise9() { fmt.Println("\nExercise 9:") g := greeting("Rob") fmt.Println(g) fmt.Println("Using shout function to shout a word returning func:") fmt.Println(shout(greeting, "Rob")) fmt.Println(shout(swear, "Rob")) } func greeting(person string) string { return "Hello, " + person } func swear(person string) string { return "Screw you, " + person } func shout(words func(string) string, person string) string { w := words(person) return strings.ToUpper(w) }
true
6a616845d430bb0727f5229947f998016579080e
Go
Melenium2/inhumanCocain
/auth/logic/grpc_transport_test.go
UTF-8
2,063
2.59375
3
[]
no_license
[]
no_license
package auth import ( "context" "testing" "github.com/BurntSushi/toml" "github.com/go-kit/kit/log" pbs "github.com/inhumanLightBackend/auth/pb" "github.com/stretchr/testify/assert" ) var ( newConfig = func() (*Config, error) { var configPath string = "_config.toml" config := NewConfig() _, err := toml.DecodeFile(configPath, config) if err != nil { return nil, err } return config, nil } ) func TestGRPCGenerateShouldReturnNewTokenFromGivenRequest(t *testing.T) { config, err := newConfig() assert.NoError(t, err) ep := NewEndpoints(NewService(config)) tr := NewGRPCServer(ep, log.NewNopLogger()) req := &pbs.GenerateRequest{ UserId: 1, Role: "admin", } r, err := tr.Generate(context.Background(), req) assert.NoError(t, err) assert.NotEmpty(t, r.Token) } func TestGRPCGenerateShouldReturnNewTokenFromEmptyRequest(t *testing.T) { config, err := newConfig() assert.NoError(t, err) ep := NewEndpoints(NewService(config)) tr := NewGRPCServer(ep, log.NewNopLogger()) req := &pbs.GenerateRequest{} r, err := tr.Generate(context.Background(), req) assert.NoError(t, err) assert.NotEmpty(t, r.Token) } func TestGRPCValidateShouldReturnClaimsFromGivenToken(t *testing.T) { config, err := newConfig() assert.NoError(t, err) ep := NewEndpoints(NewService(config)) tr := NewGRPCServer(ep, log.NewNopLogger()) req := &pbs.GenerateRequest{ UserId: 1, Role: "admin", } r, err := tr.Generate(context.Background(), req) assert.NoError(t, err) token := r.Token claims, err := tr.Validate(context.Background(), &pbs.ValidateRequest{Token: token}) assert.NoError(t, err) assert.Equal(t, claims.UserId, int32(1)) assert.Equal(t, claims.Role, "admin") } func TestGRPCValidateShouldReturnErrorFromEmptyRequest(t *testing.T) { config, err := newConfig() assert.NoError(t, err) ep := NewEndpoints(NewService(config)) tr := NewGRPCServer(ep, log.NewNopLogger()) claims, err := tr.Validate(context.Background(), &pbs.ValidateRequest{}) assert.NoError(t, err) assert.Equal(t, "Empty token", claims.Err) }
true
f3a90607b9e9bb8365a7cd5e8f1aedfd2ff5e6ea
Go
mbrt/gmailctl
/cmd/gmailctl-config-migrate/v1alpha1/config_test.go
UTF-8
1,146
2.796875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package v1alpha1 import ( "bytes" "testing" "github.com/stretchr/testify/assert" "gopkg.in/yaml.v3" ) func TestParse(t *testing.T) { yml := []byte(` version: v1alpha1 author: name: MB email: [email protected] rules: - filters: list: - [email protected] actions: labels: - MyList archive: true `) var res Config dec := yaml.NewDecoder(bytes.NewBuffer(yml)) dec.KnownFields(true) assert.NoError(t, dec.Decode(&res)) filters := Filters{ CompositeFilters: CompositeFilters{ MatchFilters: MatchFilters{ List: []string{"[email protected]"}, }, }, } expected := Config{ Version: "v1alpha1", Author: Author{Name: "MB", Email: "[email protected]"}, Rules: []Rule{ { Filters: filters, Actions: Actions{ Labels: []string{"MyList"}, Archive: true, }, }, }, } assert.Equal(t, expected, res) } func TestParseUnknownField(t *testing.T) { yml := []byte(` version: v1alpha1 author: name: MB email: [email protected] rules: - filters: foobar: - [email protected] `) var res Config dec := yaml.NewDecoder(bytes.NewBuffer(yml)) dec.KnownFields(true) assert.NotNil(t, dec.Decode(&res)) }
true
f6eff0f106251d910ce56142342faf38295d24e8
Go
sp-mario-quesada/hpack
/type_test.go
UTF-8
1,084
2.703125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package hpack import ( assert "github.com/Jxck/assertion" "testing" ) func TestNewIndexedHeader(t *testing.T) { var index uint32 = 10 var frame *IndexedHeader frame = NewIndexedHeader(index) actual, expected := frame.Index, index assert.Equal(t, actual, expected) } func TestNewIndexedLiteral(t *testing.T) { var indexing Indexing = WITH var index uint32 = 10 var value string = "var" var frame *IndexedLiteral = NewIndexedLiteral(indexing, index, value) assert.Equal(t, frame.Indexing, indexing) assert.Equal(t, frame.Index, index) assert.Equal(t, frame.ValueLength, uint32(len(value))) assert.Equal(t, frame.ValueString, value) } func TestNewStringLiteral(t *testing.T) { var indexing Indexing = WITH var name string = "foo" var value string = "var" var frame *StringLiteral = NewStringLiteral(indexing, name, value) assert.Equal(t, frame.Indexing, indexing) assert.Equal(t, frame.NameLength, uint32(len(name))) assert.Equal(t, frame.NameString, name) assert.Equal(t, frame.ValueLength, uint32(len(value))) assert.Equal(t, frame.ValueString, value) }
true
c5cf8a84ef5c15c3b9b35535733dbbb1dccc59d8
Go
westonZhang/rank_util_api
/services/keyword_include_extractor_service/sogou_pc.go
UTF-8
1,131
2.5625
3
[]
no_license
[]
no_license
package keyword_include_extractor_service import ( "github.com/PuerkitoBio/goquery" "gitlab.fxt.cn/fxt/rank-util/structs/include_extractor" "regexp" "strings" ) func KeywordIncludeExtractorSogouPc(req *include_extractor.IncludeExtractorRequest) (*include_extractor.KeywordIncludeExtractorResponse, error) { includeExtractorResponse := &include_extractor.KeywordIncludeExtractorResponse{} re := regexp.MustCompile(`站内没有找到能和.*?匹配的内容。`) subMatch := re.FindStringSubmatch(req.Body) if len(subMatch) != 0 { return includeExtractorResponse, nil } dom, err := goquery.NewDocumentFromReader(strings.NewReader(req.Body)) if err != nil { return nil, err } dom.Find("div.results>div h3.pt a").EachWithBreak(func(i int, selection *goquery.Selection) bool { if i == 0 { selectionHtml, err := selection.Html() if err != nil { return false } re := regexp.MustCompile(`<em>.*?</em>`) subMatch := re.FindStringSubmatch(selectionHtml) if len(subMatch) != 0 { includeExtractorResponse.IsIncluded = true } } return false }) return includeExtractorResponse, nil }
true
bc1dacce9e1a51327c5901c73ed96251e2bf1ed5
Go
andywijaya260286/golangudemy
/013-exercise-ninja-level-2/exercise-2-1.go
UTF-8
144
3.171875
3
[]
no_license
[]
no_license
package main import ( "fmt" ) func main() { //Program to print number in decimal, binary, hex x := 10 fmt.Printf("%d,%b,%#x", x, x, x) }
true
6718c1eb9de41473759b904b55394caacf8958c9
Go
jonhadfield/gosn-v2
/component.go
UTF-8
7,599
2.609375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package gosn import ( "fmt" "time" ) func parseComponent(i DecryptedItem) Item { c := Component{} c.UUID = i.UUID c.ItemsKeyID = i.ItemsKeyID c.ContentType = i.ContentType c.Deleted = i.Deleted c.UpdatedAt = i.UpdatedAt c.UpdatedAtTimestamp = i.UpdatedAtTimestamp c.CreatedAtTimestamp = i.CreatedAtTimestamp c.CreatedAt = i.CreatedAt c.ContentSize = len(i.Content) var err error if !c.Deleted { var content Content content, err = processContentModel(i.ContentType, i.Content) if err != nil { panic(err) } c.Content = *content.(*ComponentContent) } var cAt, uAt time.Time cAt, err = parseSNTime(i.CreatedAt) if err != nil { panic(err) } c.CreatedAt = cAt.Format(timeLayout) uAt, err = parseSNTime(i.UpdatedAt) if err != nil { panic(err) } c.UpdatedAt = uAt.Format(timeLayout) return &c } type ComponentContent struct { Identifier string `json:"identifier"` LegacyURL string `json:"legacy_url"` HostedURL string `json:"hosted_url"` LocalURL string `json:"local_url"` URL string `json:"url"` ValidUntil string `json:"valid_until"` OfflineOnly bool `json:"offlineOnly"` Name string `json:"name"` Area string `json:"area"` PackageInfo interface{} `json:"package_info"` Permissions interface{} `json:"permissions"` Active interface{} `json:"active"` AutoUpdateDisabled string `json:"autoupdateDisabled"` ComponentData interface{} `json:"componentData"` DissociatedItemIds []string `json:"disassociatedItemIds"` AssociatedItemIds []string `json:"associatedItemIds"` ItemReferences ItemReferences `json:"references"` AppData AppDataContent `json:"appData"` } type Component struct { ItemCommon Content ComponentContent } func (c Component) IsDefault() bool { return false } func (i Items) Components() (c Components) { for _, x := range i { if x.GetContentType() == "SN|Component" { component := x.(*Component) c = append(c, *component) } } return c } func (c *Components) DeDupe() { var encountered []string var deDuped Components for _, i := range *c { if !stringInSlice(i.UUID, encountered, true) { deDuped = append(deDuped, i) } encountered = append(encountered, i.UUID) } *c = deDuped } // NewComponent returns an Item of type Component without content. func NewComponent() Component { now := time.Now().UTC().Format(timeLayout) var c Component c.ContentType = "SN|Component" c.CreatedAtTimestamp = time.Now().UTC().UnixMicro() c.CreatedAt = now c.UUID = GenUUID() return c } // NewComponentContent returns an empty Tag content instance. func NewComponentContent() *ComponentContent { c := &ComponentContent{} c.SetUpdateTime(time.Now().UTC()) return c } type Components []Component func (c Components) Validate() error { var updatedTime time.Time var err error for _, item := range c { // validate content if being added if !item.Deleted { updatedTime, err = item.Content.GetUpdateTime() if err != nil { return err } switch { case item.Content.Name == "": err = fmt.Errorf("failed to create \"%s\" due to missing title: \"%s\"", item.ContentType, item.UUID) case updatedTime.IsZero(): err = fmt.Errorf("failed to create \"%s\" due to missing content updated time: \"%s\"", item.ContentType, item.Content.GetTitle()) case item.CreatedAt == "": err = fmt.Errorf("failed to create \"%s\" due to missing created at date: \"%s\"", item.ContentType, item.Content.GetTitle()) } if err != nil { return err } } } return err } func (c Component) IsDeleted() bool { return c.Deleted } func (c *Component) SetDeleted(d bool) { c.Deleted = d } func (c Component) GetContent() Content { return &c.Content } func (c *Component) SetContent(cc Content) { c.Content = *cc.(*ComponentContent) } func (c Component) GetItemsKeyID() string { return c.ItemsKeyID } func (c Component) GetUUID() string { return c.UUID } func (c *Component) SetUUID(u string) { c.UUID = u } func (c Component) GetContentType() string { return c.ContentType } func (c Component) GetCreatedAt() string { return c.CreatedAt } func (c *Component) SetCreatedAt(ca string) { c.CreatedAt = ca } func (c Component) GetUpdatedAt() string { return c.UpdatedAt } func (c *Component) SetUpdatedAt(ca string) { c.UpdatedAt = ca } func (c Component) GetCreatedAtTimestamp() int64 { return c.CreatedAtTimestamp } func (c *Component) SetCreatedAtTimestamp(ca int64) { c.CreatedAtTimestamp = ca } func (c Component) GetUpdatedAtTimestamp() int64 { return c.UpdatedAtTimestamp } func (c *Component) SetUpdatedAtTimestamp(ca int64) { c.UpdatedAtTimestamp = ca } func (c *Component) SetContentType(ct string) { c.ContentType = ct } func (c Component) GetContentSize() int { return c.ContentSize } func (c *Component) SetContentSize(s int) { c.ContentSize = s } func (cc *ComponentContent) AssociateItems(newItems []string) { // add to associated item ids for _, newRef := range newItems { var existingFound bool var existingDFound bool for _, existingRef := range cc.AssociatedItemIds { if existingRef == newRef { existingFound = true } } for _, existingDRef := range cc.DissociatedItemIds { if existingDRef == newRef { existingDFound = true } } // add reference if it doesn't exist if !existingFound { cc.AssociatedItemIds = append(cc.AssociatedItemIds, newRef) } // remove reference (from disassociated) if it does exist in that list if existingDFound { cc.DissociatedItemIds = removeStringFromSlice(newRef, cc.DissociatedItemIds) } } } func (cc *ComponentContent) GetItemAssociations() []string { return cc.AssociatedItemIds } func (cc *ComponentContent) GetItemDisassociations() []string { return cc.DissociatedItemIds } func (cc *ComponentContent) DisassociateItems(itemsToRemove []string) { // remove from associated item ids for _, delRef := range itemsToRemove { var existingFound bool for _, existingRef := range cc.AssociatedItemIds { if existingRef == delRef { existingFound = true } } // remove reference (from disassociated) if it does exist in that list if existingFound { cc.AssociatedItemIds = removeStringFromSlice(delRef, cc.AssociatedItemIds) } } } func (cc *ComponentContent) GetUpdateTime() (time.Time, error) { if cc.AppData.OrgStandardNotesSN.ClientUpdatedAt == "" { return time.Time{}, fmt.Errorf("ClientUpdatedAt not set") } return time.Parse(timeLayout, cc.AppData.OrgStandardNotesSN.ClientUpdatedAt) } func (cc *ComponentContent) SetUpdateTime(uTime time.Time) { cc.AppData.OrgStandardNotesSN.ClientUpdatedAt = uTime.Format(timeLayout) } func (cc ComponentContent) GetTitle() string { return "" } func (cc *ComponentContent) GetName() string { return cc.Name } func (cc *ComponentContent) GetActive() bool { return cc.Active.(bool) } func (cc *ComponentContent) SetTitle(title string) { } func (cc *ComponentContent) GetAppData() AppDataContent { return cc.AppData } func (cc *ComponentContent) SetAppData(data AppDataContent) { cc.AppData = data } func (cc ComponentContent) References() ItemReferences { return cc.ItemReferences } func (cc *ComponentContent) UpsertReferences(input ItemReferences) { panic("implement me") } func (cc *ComponentContent) SetReferences(input ItemReferences) { cc.ItemReferences = input }
true
4d6b68da7f622b0a798c1fc38c51efe1b5158608
Go
jcdny/goeuler
/prob079_test.go
UTF-8
1,149
3.234375
3
[]
no_license
[]
no_license
package euler import ( "log" "testing" ) func prob079() int { // I did this one by hand // sort -u < keylog.txt gives: keys := []int{ 129, 160, 162, 168, 180, 289, 290, 316, 318, 319, 362, 368, 380, 389, 620, 629, 680, 689, 690, 710, 716, 718, 719, 720, 728, 729, 731, 736, 760, 762, 769, 790, 890} // Make a table per digit like so // before:D:after // 9876321 0 // 73 1 02689 // 7631 2 089 // 7 3 012689 // 731 6 289 // 7 0123689 // 76321 8 09 // 876321 9 0 // // from the above you can see 7 is the first digit removing 7 from // before all digits leaves 3 as the second digit and similiarly // removing 3 leaves 1 etc. // // once you have placed all the digits you end up with // 73162890. // // going back to the original keylog data you can see all the // triples are satisfied by this sequence and each digit occurs // once so it is a minimal length sequence. if false { log.Print(keys) } return 73162890 } func TestProb079(t *testing.T) { out := prob079() Validate(t, 79, out) } func BenchmarkProb079(b *testing.B) { for i := 0; i < b.N; i++ { prob079() } }
true
9badad4c8f3757872f4997b40767293e87ad19af
Go
logonmy/go-study
/main/cal/deque_test.go
UTF-8
3,020
3.75
4
[]
no_license
[]
no_license
package cal_test import ( "fmt" "testing" ) // 链表的一个节点 type ListNode struct { prev *ListNode // 前一个节点 next *ListNode // 后一个节点 value interface{} // 数据 } // 创建一个节点 func NewListNode(value interface{}) (listNode *ListNode) { listNode = &ListNode{ value: value, } return } // 当前节点的前一个节点 func (n *ListNode) Prev() (prev *ListNode) { prev = n.prev return } // 当前节点的前一个节点 func (n *ListNode) Next() (next *ListNode) { next = n.next return } // 获取节点的值 func (n *ListNode) GetValue() (value interface{}) { if n == nil { return } value = n.value return } // 链表 type List struct { head *ListNode // 表头节点 tail *ListNode // 表尾节点 len int // 链表的长度 } // 创建一个空链表 func NewList() (list *List) { list = &List{} return } // 返回链表头节点 func (l *List) Head() (head *ListNode) { head = l.head return } // 返回链表尾节点 func (l *List) Tail() (tail *ListNode) { tail = l.tail return } // 返回链表长度 func (l *List) Len() (len int) { len = l.len return } // 在链表的右边插入一个元素 func (l *List) RPush(value interface{}) { node := NewListNode(value) // 链表未空的时候 if l.Len() == 0 { l.head = node l.tail = node } else { tail := l.tail tail.next = node node.prev = tail l.tail = node } l.len = l.len + 1 return } // 从链表左边取出一个节点 func (l *List) LPop() (node *ListNode) { // 数据为空 if l.len == 0 { return } node = l.head if node.next == nil { // 链表未空 l.head = nil l.tail = nil } else { l.head = node.next } l.len = l.len - 1 return } // 从链表右边取出一个节点 func (l *List) RPop() (node *ListNode) { // 数据为空 if l.len == 0 { return } node = l.tail l.tail = node.prev //if node.next == nil { // // 链表未空 // l.head = nil // l.tail = nil //} else { // //} l.len = l.len - 1 return } func Test_deque(t *testing.T) { nums := []int{1, 3, -1, -3, 5, 3, 6, 7} fmt.Println(maxSlidingWindow(nums, 3)) } func maxSlidingWindow(nums []int, k int) []int { d := NewList() windowCnt := len(nums) - k + 1 result := make([]int, 0, windowCnt) for i := 0; i < windowCnt; i++ { for j := 0; j < k; j++ { if i == 0 && j == 0 { d.RPush(nums[i]) continue } max := nums[i+j] for t := i + j - 1; t >= i; t-- { if max > nums[t] { d.RPop() if t == i { d.RPush(i + j) } } else { d.RPush(t + 1) break } } } if d.Head().value.(int) < i { d.LPop() result = append(result, nums[d.LPop().value.(int)]) } else { result = append(result, nums[d.Head().value.(int)]) } } return result } //func maxSlidingWindow1(nums []int, k int) []int { // d:= NewList() // windowCnt := len(nums) - k + 1 // result := make([]int, 0, windowCnt) // for i := k; i < len(nums); i ++ { // // } // // // return result //}
true
0d698d26f06e7f6b1324ddb724e766a9e6fe5c4c
Go
offlinehacker/deployment-manager
/util/httpclient_test.go
UTF-8
3,840
2.96875
3
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package util import ( "bytes" "compress/gzip" "errors" "io" "net/http" "strings" "testing" "time" ) type mockSleeper struct { args []time.Duration } func (m *mockSleeper) Sleep(d time.Duration) { m.args = append(m.args, d) } type responseAndError struct { err error resp *http.Response } type testBody struct { closed bool body io.Reader } func (tb *testBody) Read(p []byte) (n int, err error) { return tb.body.Read(p) } func (tb *testBody) Close() error { tb.closed = true return nil } func createResponse(err error, code int, body string, shouldClose bool, headers map[string]string) responseAndError { httpBody := testBody{body: strings.NewReader(body), closed: !shouldClose} header := http.Header{} for k, v := range headers { header.Add(k, v) } httpResponse := &http.Response{ Body: &httpBody, ContentLength: int64(len(body)), StatusCode: code, Header: header, } return responseAndError{err: err, resp: httpResponse} } type mockDoer struct { resp []responseAndError t *testing.T url string headers map[string]string } func (doer *mockDoer) Do(req *http.Request) (res *http.Response, err error) { if req.URL.String() != doer.url { doer.t.Errorf("Expected url %s but got url %s", doer.url, req.URL.String()) } for k, v := range doer.headers { if req.Header.Get(k) != v { doer.t.Errorf("Expected header %s with value %s but found %s", k, v, req.Header.Get(k)) } } if len(doer.resp) == 0 { doer.t.Errorf("Do method was called more times than expected.") } res = doer.resp[0].resp err = doer.resp[0].err doer.resp = doer.resp[1:] return } func testClientDriver(md mockDoer, ms mockSleeper, expectedErr error, code int, result string, t *testing.T) { expectedCalls := len(md.resp) client := NewHTTPClient(uint(expectedCalls)-1, &md, &ms) r, c, e := client.Get(md.url) if expectedCalls-1 != len(ms.args) { t.Errorf("Expected %d calls to sleeper but found %d", expectedCalls-1, len(ms.args)) } if r != result { t.Errorf("Expected result %s but received %s", result, r) } if c != code { t.Errorf("Expected status code %d but received %d", code, c) } if e != expectedErr { t.Errorf("Expected error %s but received %s", expectedErr, e) } } func TestGzip(t *testing.T) { doer := mockDoer{} var b bytes.Buffer gz := gzip.NewWriter(&b) gz.Write([]byte("Test")) gz.Flush() gz.Close() result := b.String() doer.resp = []responseAndError{ createResponse(nil, 200, result, true, map[string]string{"Content-Encoding": "gzip"}), } sleeper := mockSleeper{} testClientDriver(doer, sleeper, nil, 200, "Test", t) } func TestRetry(t *testing.T) { doer := mockDoer{} doer.resp = []responseAndError{ createResponse(nil, 404, "", true, map[string]string{}), createResponse(nil, 200, "Test", true, map[string]string{}), } sleeper := mockSleeper{} testClientDriver(doer, sleeper, nil, 200, "Test", t) } func TestFail(t *testing.T) { doer := mockDoer{} err := errors.New("Error") doer.resp = []responseAndError{ createResponse(nil, 404, "", true, map[string]string{}), createResponse(err, 0, "", false, map[string]string{}), } sleeper := mockSleeper{} testClientDriver(doer, sleeper, err, 0, "", t) }
true
1d5d8ce568637b9c91cc58bff877995e2795bde4
Go
gophergala/echodb
/dbcore/hashtable.go
UTF-8
8,204
3.203125
3
[ "BSD-2-Clause", "MIT" ]
permissive
[ "BSD-2-Clause", "MIT" ]
permissive
/* Hash table file contains binary content; it implements a static hash table made of hash buckets and integer entries. Every bucket has a fixed number of entries. When a bucket becomes full, a new bucket is chained to it in order to store more entries. Every entry has an integer key and value. An entry key may have multiple values assigned to it, however the combination of entry key and value must be unique across the entire hash table. */ // Taken from tiedot hashtable implementation package dbcore import ( "encoding/binary" "fmt" "sync" ) const ( HT_FILE_GROWTH = 32 * 1048576 // Hash table file initial size & file growth ENTRY_SIZE = 1 + 10 + 10 // Hash entry size: validity (single byte), key (int 10 bytes), value (int 10 bytes) BUCKET_HEADER = 10 // Bucket header size: next chained bucket number (int 10 bytes) PER_BUCKET = 16 // Entries per bucket HASH_BITS = 16 // Number of hash key bits BUCKET_SIZE = BUCKET_HEADER + PER_BUCKET*ENTRY_SIZE // Size of a bucket INITIAL_BUCKETS = 65536 // Initial number of buckets == 2 ^ HASH_BITS ) // Hash table file is a binary file containing buckets of hash entries. type HashTable struct { *DataFile numBuckets int Lock *sync.RWMutex } // Smear the integer entry key and return the portion (first HASH_BITS bytes) used for allocating the entry. func HashKey(key int) int { /* tiedot should be compiled/run on x86-64 systems. If you decide to compile tiedot on 32-bit systems, the following integer-smear algorithm will cause compilation failure due to 32-bit interger overflow; therefore you must modify the algorithm. Do not remove the integer-smear process, and remember to run test cases to verify your mods. */ // ========== Integer-smear start ======= key = key ^ (key >> 4) key = (key ^ 0xdeadbeef) + (key << 5) key = key ^ (key >> 11) // ========== Integer-smear end ========= return key & ((1 << HASH_BITS) - 1) // Do not modify this line } // Open a hash table file. func OpenHashTable(path string) (ht *HashTable, err error) { ht = &HashTable{Lock: new(sync.RWMutex)} if ht.DataFile, err = OpenDataFile(path, HT_FILE_GROWTH); err != nil { return } ht.calculateNumBuckets() return } // Follow the longest bucket chain to calculate total number of buckets, hence the "used size" of hash table file. func (ht *HashTable) calculateNumBuckets() { ht.numBuckets = ht.Size / BUCKET_SIZE largestBucketNum := INITIAL_BUCKETS - 1 for i := 0; i < INITIAL_BUCKETS; i++ { lastBucket := ht.lastBucket(i) if lastBucket > largestBucketNum && lastBucket < ht.numBuckets { largestBucketNum = lastBucket } } ht.numBuckets = largestBucketNum + 1 usedSize := ht.numBuckets * BUCKET_SIZE if usedSize > ht.Size { ht.Used = ht.Size ht.EnsureSize(usedSize - ht.Used) } ht.Used = usedSize fmt.Printf("%s: calculated used size is %d", ht.Path, usedSize) } // Return number of the next chained bucket. func (ht *HashTable) nextBucket(bucket int) int { if bucket >= ht.numBuckets { return 0 } bucketAddr := bucket * BUCKET_SIZE nextUint, err := binary.Varint(ht.Buf[bucketAddr : bucketAddr+10]) next := int(nextUint) if next == 0 { return 0 } else if err < 0 || next <= bucket || next >= ht.numBuckets || next < INITIAL_BUCKETS { fmt.Errorf("Bad hash table - repair ASAP %s", ht.Path) return 0 } else { return next } } // Return number of the last bucket in chain. func (ht *HashTable) lastBucket(bucket int) int { for curr := bucket; ; { next := ht.nextBucket(curr) if next == 0 { return curr } curr = next } } // Create and chain a new bucket. func (ht *HashTable) growBucket(bucket int) { ht.EnsureSize(BUCKET_SIZE) lastBucketAddr := ht.lastBucket(bucket) * BUCKET_SIZE binary.PutVarint(ht.Buf[lastBucketAddr:lastBucketAddr+10], int64(ht.numBuckets)) ht.Used += BUCKET_SIZE ht.numBuckets++ } // Clear the entire hash table. func (ht *HashTable) Clear() (err error) { if err = ht.DataFile.Clear(); err != nil { return } ht.calculateNumBuckets() return } // Sync Hashtable mmap to file func (ht *HashTable) Sync() (err error) { if err = ht.DataFile.Sync(); err != nil { return } return nil } // Store the entry into a vacant (invalidated or empty) place in the appropriate bucket. func (ht *HashTable) Put(key, val int) { for bucket, entry := HashKey(key), 0; ; { entryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE if ht.Buf[entryAddr] != 1 { ht.Buf[entryAddr] = 1 binary.PutVarint(ht.Buf[entryAddr+1:entryAddr+11], int64(key)) binary.PutVarint(ht.Buf[entryAddr+11:entryAddr+21], int64(val)) return } if entry++; entry == PER_BUCKET { entry = 0 if bucket = ht.nextBucket(bucket); bucket == 0 { ht.growBucket(HashKey(key)) ht.Put(key, val) return } } } } // Look up values by key. func (ht *HashTable) Get(key, limit int) (vals []int) { if limit == 0 { vals = make([]int, 0, 10) } else { vals = make([]int, 0, limit) } for count, entry, bucket := 0, 0, HashKey(key); ; { entryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11]) entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21]) if ht.Buf[entryAddr] == 1 { if int(entryKey) == key { vals = append(vals, int(entryVal)) if count++; count == limit { return } } } else if entryKey == 0 && entryVal == 0 { return } if entry++; entry == PER_BUCKET { entry = 0 if bucket = ht.nextBucket(bucket); bucket == 0 { return } } } } // Flag an entry as invalid, so that Get will not return it later on. func (ht *HashTable) Remove(key, val int) { for entry, bucket := 0, HashKey(key); ; { entryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11]) entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21]) if ht.Buf[entryAddr] == 1 { if int(entryKey) == key && int(entryVal) == val { ht.Buf[entryAddr] = 0 return } } else if entryKey == 0 && entryVal == 0 { return } if entry++; entry == PER_BUCKET { entry = 0 if bucket = ht.nextBucket(bucket); bucket == 0 { return } } } } // Divide the entire hash table into roughly equally sized partitions, and return the start/end key range of the chosen partition. func GetPartitionRange(partNum, totalParts int) (start int, end int) { perPart := INITIAL_BUCKETS / totalParts leftOver := INITIAL_BUCKETS % totalParts start = partNum * perPart if leftOver > 0 { if partNum == 0 { end += 1 } else if partNum < leftOver { start += partNum end += 1 } else { start += leftOver } } end += start + perPart if partNum == totalParts-1 { end = INITIAL_BUCKETS } return } // Collect entries all the way from "head" bucket to the end of its chained buckets. func (ht *HashTable) collectEntries(head int) (keys, vals []int) { keys = make([]int, 0, PER_BUCKET) vals = make([]int, 0, PER_BUCKET) var entry, bucket int = 0, head for { entryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11]) entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21]) if ht.Buf[entryAddr] == 1 { keys = append(keys, int(entryKey)) vals = append(vals, int(entryVal)) } else if entryKey == 0 && entryVal == 0 { return } if entry++; entry == PER_BUCKET { entry = 0 if bucket = ht.nextBucket(bucket); bucket == 0 { return } } } } // Return all entries in the chosen partition. func (ht *HashTable) GetPartition(partNum, partSize int) (keys, vals []int) { rangeStart, rangeEnd := GetPartitionRange(partNum, partSize) prealloc := (rangeEnd - rangeStart) * PER_BUCKET keys = make([]int, 0, prealloc) vals = make([]int, 0, prealloc) for head := rangeStart; head < rangeEnd; head++ { k, v := ht.collectEntries(head) keys = append(keys, k...) vals = append(vals, v...) } return }
true
33103ea11a8f8a8d194ea755b7c745c91ba86d15
Go
patsoffice/aliasman
/internal/cmd/aliascmd/create.go
UTF-8
6,153
2.625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Copyright © 2020 Patrick Lawrence <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package aliascmd import ( "crypto/md5" "crypto/rand" "encoding/base64" "fmt" "strings" "github.com/patsoffice/aliasman/internal/alias" "github.com/patsoffice/aliasman/internal/cmd" "github.com/spf13/cobra" "github.com/spf13/viper" ) // aliasCreateCmd represents the create command var ( aliasCreateCmd = &cobra.Command{ Use: "create", Short: "Create an email alias", Run: aliasCreateRun, } aliasCreateFlags = struct { alias string domain string addresses []string description string randomAlias bool randomAliasLength int useBase64Encoding bool }{} ) func init() { aliasCmd := cmd.AliasCmd() aliasCmd.AddCommand(aliasCreateCmd) aliasCreateCmd.Flags().StringSliceVarP(&aliasCreateFlags.addresses, "email-address", "e", []string{}, "Address(es) for alias to send email to (fully qualified)") aliasCreateCmd.Flags().StringVarP(&aliasCreateFlags.domain, "domain", "d", "", "Domain to attach the alias to") aliasCreateCmd.Flags().StringVarP(&aliasCreateFlags.alias, "alias", "a", "", "Alias name (minus domain)") aliasCreateCmd.Flags().StringVarP(&aliasCreateFlags.description, "description", "D", "", "Description") aliasCreateCmd.Flags().BoolVarP(&aliasCreateFlags.randomAlias, "random-alias", "r", false, "Create a random alias") aliasCreateCmd.Flags().IntVarP(&aliasCreateFlags.randomAliasLength, "random-length", "l", 16, "Length of the randomly generated alias") aliasCreateCmd.Flags().BoolVarP(&aliasCreateFlags.useBase64Encoding, "use-base64", "b", false, "Use RFC 4648 encoding for the alias") aliasCreateCmd.Flags().SortFlags = false } type randReader interface { Read([]byte) (int, error) } type realRandReader struct{} func (r realRandReader) Read(b []byte) (int, error) { return rand.Read(b) } func randomAlias(r randReader, randomAliasLength int, useBase64Encoding bool) (string, error) { // Make a bas64 encoding set that only consists of a-z0-9 -- not an even distribution // but should not matter for our use case. Using lowercase letters since most email // systems don't distinguish between upper and lowercase latters. const encodeSet = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz01" b := make([]byte, 256) _, err := r.Read(b) if err != nil { return "", fmt.Errorf("generating random data") } var alias string if useBase64Encoding { fmt.Println("HERE") alias = base64.NewEncoding(encodeSet).WithPadding(base64.NoPadding).EncodeToString(b) alias = alias[:randomAliasLength] } else { alias = fmt.Sprintf("%x", md5.Sum(b)) alias = alias[:randomAliasLength] } return alias, nil } func aliasCreateRun(cobraCmd *cobra.Command, args []string) { // Validate inputs err := cmd.ValidateInputs(&aliasCreateFlags.domain, nil, &aliasCreateFlags.addresses) if err != nil { cmd.ErrorExit(err, cobraCmd) } if aliasCreateFlags.randomAliasLength > 32 { cmd.ErrorExit(fmt.Errorf("max random alias length of 32 bytes"), cobraCmd) } if !aliasCreateFlags.randomAlias && aliasCreateFlags.alias == "" { cmd.ErrorExit(fmt.Errorf("alias needed or specify generating a random alias"), cobraCmd) } // If --random-alias is set, we generate a random set of bytes to feed to // the encoding generators. if aliasCreateFlags.randomAlias && aliasCreateFlags.alias == "" { var err error aliasCreateFlags.alias, err = randomAlias(realRandReader{}, aliasCreateFlags.randomAliasLength, aliasCreateFlags.useBase64Encoding) if err != nil { cmd.ErrorExit(err, nil) } } sp, err := cmd.StorageProvider() if err != nil { cmd.ErrorExit(err, nil) } ep, err := cmd.EmailProvider() if err != nil { cmd.ErrorExit(err, nil) } a := alias.Alias{ Alias: aliasCreateFlags.alias, Domain: aliasCreateFlags.domain, EmailAddresses: aliasCreateFlags.addresses, Description: aliasCreateFlags.description, } readOnly := viper.GetBool("readonly") if readOnly { cmd.ErrorExit(fmt.Errorf("alias create requires %s to not be readonly", sp.Type()), nil) } if err := sp.Open(readOnly); err != nil { cmd.ErrorExit(fmt.Errorf("failure opening %s storage: %v", sp.Type(), err), nil) } // Check if the alias already exists alias, err := sp.Get(aliasCreateFlags.alias, aliasCreateFlags.domain) if err != nil { cmd.ErrorExit(err, nil) } if alias != nil { cmd.ErrorExit(fmt.Errorf("alias %s for domain %s already exists", aliasCreateFlags.alias, aliasCreateFlags.domain), nil) } err = ep.AliasCreate(aliasCreateFlags.alias, aliasCreateFlags.domain, aliasCreateFlags.addresses...) if err != nil { cmd.ErrorExit(err, nil) } fmt.Printf("Created alias %s that points to %s\n", fmt.Sprintf("%s@%s", aliasCreateFlags.alias, aliasCreateFlags.domain), strings.Join(aliasCreateFlags.addresses, ", ")) if err := sp.Put(a, true); err != nil { cmd.ErrorExit(fmt.Errorf("failure adding to %s storage: %v", sp.Type(), err), nil) } if err := sp.Close(); err != nil { cmd.ErrorExit(fmt.Errorf("failure closing %s storage: %v", sp.Type(), err), nil) } }
true
9274ac48db8cf83e841acba7da561735afcf2732
Go
zhaopeilin1/go-excercise
/practice/home-system/internal/model/item.go
UTF-8
1,809
2.875
3
[]
no_license
[]
no_license
package model import ( "github.com/jinzhu/gorm" ) type Item struct { *Model // 物品名称 Name string `json:"name"` // 状态 State string `json:"state"` Category string `json:"category"` //类目 CategoryId uint32 `json:"category_id"` HomeId uint32 `json:"home_id"` //计量单位 Unit string `json:"unit"` //消耗速度 ConsumptionSpeed float64 `json:"consumption_speed"` } func (model Item) TableName() string { return "item" } func (t Item) Count(db *gorm.DB) (int, error) { var count int if t.Name != "" { db = db.Where("name like '%?%'", t.Name) } if t.HomeId != 0 { db = db.Where("home_id=?", t.HomeId) } if t.CategoryId != 0 { db = db.Where("category_id=?", t.CategoryId) } if t.State != "" { db = db.Where("state = ?", t.State) } if err := db.Model(&t).Where("is_del = ?", 0).Count(&count).Error; err != nil { return 0, err } return count, nil } func (t Item) List(db *gorm.DB, pageOffset, pageSize int) ([]*Item, error) { var tags []*Item var err error if pageOffset >= 0 && pageSize > 0 { db = db.Offset(pageOffset).Limit(pageSize) } if t.Name != "" { db = db.Where("name like '%?%'", t.Name) } if t.HomeId != 0 { db = db.Where("home_id=?", t.HomeId) } if t.CategoryId != 0 { db = db.Where("category_id=?", t.CategoryId) } if t.State != "" { db = db.Where("state = ?", t.State) } if err = db.Where("is_del = ?", 0).Find(&tags).Error; err != nil { return nil, err } return tags, nil } func (t Item) Create(db *gorm.DB) error { return db.Create(&t).Error } func (t Item) Update(db *gorm.DB, values interface{}) error { return db.Model(&t).Where("id = ? and is_del=?", t.Id, 0).Updates(values).Error } func (t Item) Delete(db *gorm.DB) error { return db.Where("id=? and is_del = ?", t.Id, 0).Delete(&t).Error }
true
ed97feb7965ba90386e2bf7999a3af404ad6819d
Go
stooke/fabric8-wit
/workitem/number_sequence/work_item_number_sequence_repository_test.go
UTF-8
2,097
2.84375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package numbersequence_test import ( "context" "fmt" "sync" "testing" "github.com/fabric8-services/fabric8-wit/application" "github.com/fabric8-services/fabric8-wit/gormtestsupport" "github.com/fabric8-services/fabric8-wit/resource" tf "github.com/fabric8-services/fabric8-wit/test/testfixture" . "github.com/fabric8-services/fabric8-wit/workitem/number_sequence" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) type workItemNumberSequenceTest struct { gormtestsupport.DBTestSuite repo WorkItemNumberSequenceRepository } func TestWorkItemNumberSequenceTest(t *testing.T) { resource.Require(t, resource.Database) suite.Run(t, &workItemNumberSequenceTest{DBTestSuite: gormtestsupport.NewDBTestSuite()}) } func (s *workItemNumberSequenceTest) SetupTest() { s.DBTestSuite.SetupTest() s.repo = NewWorkItemNumberSequenceRepository(s.DB) } func (s *workItemNumberSequenceTest) TestConcurrentNextVal() { // given fxt := tf.NewTestFixture(s.T(), s.DB, tf.Spaces(1)) type Report struct { id int total int failures int } routines := 10 itemsPerRoutine := 50 reports := make([]Report, routines) // when running concurrent go routines simultaneously var wg sync.WaitGroup for i := 0; i < routines; i++ { wg.Add(1) // in each go rountine, run 10 creations go func(routineID int) { defer wg.Done() report := Report{id: routineID} for j := 0; j < itemsPerRoutine; j++ { if err := application.Transactional(s.GormDB, func(app application.Application) error { _, err := s.repo.NextVal(context.Background(), fxt.Spaces[0].ID) return err }); err != nil { s.T().Logf("Creation failed: %s", err.Error()) report.failures++ } report.total++ } reports[routineID] = report }(i) } wg.Wait() // then // wait for all items to be created for _, report := range reports { fmt.Printf("Routine #%d done: %d creations, including %d failure(s)\n", report.id, report.total, report.failures) assert.Equal(s.T(), itemsPerRoutine, report.total) assert.Equal(s.T(), 0, report.failures) } }
true
a43f37f880285e8a5e1c2dc566f1dcab736845c7
Go
justdomepaul/leetcode-golang
/solutions/324.go
UTF-8
483
3.15625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package solutions import ( "sort" ) func wiggleSort(nums []int) { if len(nums) <= 1 { return } sort.Ints(nums) middle := len(nums) / 2 + len(nums) % 2 var result []int for i := 0; i < middle; i++ { result = append(result, nums[middle - i - 1]) if middle + i < len(nums){ result = append(result, nums[len(nums) - i - 1]) } } for i := 0; i < len(result); i++ { nums[i] = result[i] } }
true