_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q18000
PanicOnError
train
func PanicOnError(err error, msg string) { if revErr, ok := err.(*Error); (ok && revErr != nil) || (!ok && err != nil) { Logger.Panicf("Abort: %s: %s %s", msg, revErr, err) } }
go
{ "resource": "" }
q18001
CopyDir
train
func CopyDir(destDir, srcDir string, data map[string]interface{}) error { if !DirExists(srcDir) { return nil } return fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error { // Get the relative path from the source base, and the corresponding path in // the dest directory. relSrcPath := strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)) destPath := filepath.Join(destDir, relSrcPath) // Skip dot files and dot directories. if strings.HasPrefix(relSrcPath, ".") { if info.IsDir() { return filepath.SkipDir } return nil } // Create a subdirectory if necessary. if info.IsDir() { err := os.MkdirAll(filepath.Join(destDir, relSrcPath), 0777) if !os.IsExist(err) { return NewBuildIfError(err, "Failed to create directory", "path", destDir+"/"+relSrcPath) } return nil } // If this file ends in ".template", render it as a template. if strings.HasSuffix(relSrcPath, ".template") { return RenderTemplate(destPath[:len(destPath)-len(".template")], srcPath, data) } // Else, just copy it over. return CopyFile(destPath, srcPath) }) }
go
{ "resource": "" }
q18002
TarGzDir
train
func TarGzDir(destFilename, srcDir string) (name string, err error) { zipFile, err := os.Create(destFilename) if err != nil { return "", NewBuildIfError(err, "Failed to create archive", "file", destFilename) } defer func() { _ = zipFile.Close() }() gzipWriter := gzip.NewWriter(zipFile) defer func() { _ = gzipWriter.Close() }() tarWriter := tar.NewWriter(gzipWriter) defer func() { _ = tarWriter.Close() }() err = fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error { if info.IsDir() { return nil } srcFile, err := os.Open(srcPath) if err != nil { return NewBuildIfError(err, "Failed to read file", "file", srcPath) } defer func() { _ = srcFile.Close() }() err = tarWriter.WriteHeader(&tar.Header{ Name: strings.TrimLeft(srcPath[len(srcDir):], string(os.PathSeparator)), Size: info.Size(), Mode: int64(info.Mode()), ModTime: info.ModTime(), }) if err != nil { return NewBuildIfError(err, "Failed to write tar entry header", "file", srcPath) } _, err = io.Copy(tarWriter, srcFile) if err != nil { return NewBuildIfError(err, "Failed to copy file", "file", srcPath) } return nil }) return zipFile.Name(), err }
go
{ "resource": "" }
q18003
Empty
train
func Empty(dirname string) bool { dir, err := os.Open(dirname) if err != nil { Logger.Infof("error opening directory: %s", err) } defer func() { _ = dir.Close() }() results, _ := dir.Readdir(1) return len(results) == 0 }
go
{ "resource": "" }
q18004
FindSrcPaths
train
func FindSrcPaths(appImportPath, revelImportPath string, packageResolver func(pkgName string) error) (appSourcePath, revelSourcePath string, err error) { var ( gopaths = filepath.SplitList(build.Default.GOPATH) goroot = build.Default.GOROOT ) if len(gopaths) == 0 { err = errors.New("GOPATH environment variable is not set. " + "Please refer to http://golang.org/doc/code.html to configure your Go environment.") return } if ContainsString(gopaths, goroot) { err = fmt.Errorf("GOPATH (%s) must not include your GOROOT (%s). "+ "Please refer to http://golang.org/doc/code.html to configure your Go environment. ", build.Default.GOPATH, goroot) return } appPkgDir := "" appPkgSrcDir := "" if len(appImportPath)>0 { Logger.Info("Seeking app package","app",appImportPath) appPkg, err := build.Import(appImportPath, "", build.FindOnly) if err != nil { err = fmt.Errorf("Failed to import " + appImportPath + " with error %s", err.Error()) return "","",err } appPkgDir,appPkgSrcDir =appPkg.Dir, appPkg.SrcRoot } Logger.Info("Seeking remote package","using",appImportPath, "remote",revelImportPath) revelPkg, err := build.Default.Import(revelImportPath, appPkgDir, build.FindOnly) if err != nil { Logger.Info("Resolved called Seeking remote package","using",appImportPath, "remote",revelImportPath) packageResolver(revelImportPath) revelPkg, err = build.Import(revelImportPath, appPkgDir, build.FindOnly) if err != nil { err = fmt.Errorf("Failed to find Revel with error: %s", err.Error()) return } } revelSourcePath, appSourcePath = revelPkg.Dir[:len(revelPkg.Dir)-len(revelImportPath)], appPkgSrcDir return }
go
{ "resource": "" }
q18005
intOrZero
train
func (v *Version) intOrZero(input string) (value int) { if input != "" { value, _ = strconv.Atoi(input) } return value }
go
{ "resource": "" }
q18006
CompatibleFramework
train
func (v *Version) CompatibleFramework(c *CommandConfig) error { for i, rv := range frameworkCompatibleRangeList { start, _ := ParseVersion(rv[0]) end, _ := ParseVersion(rv[1]) if !v.Newer(start) || v.Newer(end) { continue } // Framework is older then 0.20, turn on historic mode if i == 0 { c.HistoricMode = true } return nil } return errors.New("Tool out of date - do a 'go get -u github.com/revel/cmd/revel'") }
go
{ "resource": "" }
q18007
MajorNewer
train
func (v *Version) MajorNewer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } return false }
go
{ "resource": "" }
q18008
MinorNewer
train
func (v *Version) MinorNewer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } if v.Minor != o.Minor { return v.Minor > o.Minor } return false }
go
{ "resource": "" }
q18009
Newer
train
func (v *Version) Newer(o *Version) bool { if v.Major != o.Major { return v.Major > o.Major } if v.Minor != o.Minor { return v.Minor > o.Minor } if v.Maintenance != o.Maintenance { return v.Maintenance > o.Maintenance } return false }
go
{ "resource": "" }
q18010
VersionString
train
func (v *Version) VersionString() string { return fmt.Sprintf("%s%d.%d.%d%s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix) }
go
{ "resource": "" }
q18011
String
train
func (v *Version) String() string { return fmt.Sprintf("Version: %s%d.%d.%d%s\nBuild Date: %s\n Minimium Go Version: %s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion) }
go
{ "resource": "" }
q18012
ServeHTTP
train
func (h *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Don't rebuild the app for favicon requests. if lastRequestHadError > 0 && r.URL.Path == "/favicon.ico" { return } // Flush any change events and rebuild app if necessary. // Render an error page if the rebuild / restart failed. err := h.watcher.Notify() if err != nil { // In a thread safe manner update the flag so that a request for // /favicon.ico does not trigger a rebuild atomic.CompareAndSwapInt32(&lastRequestHadError, 0, 1) h.renderError(w, r, err) return } // In a thread safe manner update the flag so that a request for // /favicon.ico is allowed atomic.CompareAndSwapInt32(&lastRequestHadError, 1, 0) // Reverse proxy the request. // (Need special code for websockets, courtesy of bradfitz) if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { h.proxyWebsocket(w, r, h.serverHost) } else { h.proxy.ServeHTTP(w, r) } }
go
{ "resource": "" }
q18013
NewHarness
train
func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode string, noProxy bool) *Harness { // Get a template loader to render errors. // Prefer the app's views/errors directory, and fall back to the stock error pages. //revel.MainTemplateLoader = revel.NewTemplateLoader( // []string{filepath.Join(revel.RevelPath, "templates")}) //if err := revel.MainTemplateLoader.Refresh(); err != nil { // revel.RevelLog.Error("Template loader error", "error", err) //} addr := paths.HTTPAddr port := paths.Config.IntDefault("harness.port", 0) scheme := "http" if paths.HTTPSsl { scheme = "https" } // If the server is running on the wildcard address, use "localhost" if addr == "" { utils.Logger.Warn("No http.addr specified in the app.conf listening on localhost interface only. " + "This will not allow external access to your application") addr = "localhost" } if port == 0 { port = getFreePort() } serverURL, _ := url.ParseRequestURI(fmt.Sprintf(scheme+"://%s:%d", addr, port)) serverHarness := &Harness{ port: port, serverHost: serverURL.String()[len(scheme+"://"):], proxy: httputil.NewSingleHostReverseProxy(serverURL), mutex: &sync.Mutex{}, paths: paths, useProxy: !noProxy, config: c, runMode: runMode, } if paths.HTTPSsl { serverHarness.proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } } return serverHarness }
go
{ "resource": "" }
q18014
Refresh
train
func (h *Harness) Refresh() (err *utils.Error) { // Allow only one thread to rebuild the process // If multiple requests to rebuild are queued only the last one is executed on // So before a build is started we wait for a second to determine if // more requests for a build are triggered. // Once no more requests are triggered the build will be processed h.mutex.Lock() defer h.mutex.Unlock() if h.app != nil { h.app.Kill() } utils.Logger.Info("Rebuild Called") var newErr error h.app, newErr = Build(h.config, h.paths) if newErr != nil { utils.Logger.Error("Build detected an error", "error", newErr) if castErr, ok := newErr.(*utils.Error); ok { return castErr } err = &utils.Error{ Title: "App failed to start up", Description: err.Error(), } return } if h.useProxy { h.app.Port = h.port if err2 := h.app.Cmd(h.runMode).Start(h.config); err2 != nil { utils.Logger.Error("Could not start application", "error", err2) if err,k :=err2.(*utils.Error);k { return err } return &utils.Error{ Title: "App failed to start up", Description: err2.Error(), } } } else { h.app = nil } return }
go
{ "resource": "" }
q18015
WatchDir
train
func (h *Harness) WatchDir(info os.FileInfo) bool { return !utils.ContainsString(doNotWatch, info.Name()) }
go
{ "resource": "" }
q18016
Run
train
func (h *Harness) Run() { var paths []string if h.paths.Config.BoolDefault("watch.gopath", false) { gopaths := filepath.SplitList(build.Default.GOPATH) paths = append(paths, gopaths...) } paths = append(paths, h.paths.CodePaths...) h.watcher = watcher.NewWatcher(h.paths, false) h.watcher.Listen(h, paths...) h.watcher.Notify() if h.useProxy { go func() { // Check the port to start on a random port if h.paths.HTTPPort == 0 { h.paths.HTTPPort = getFreePort() } addr := fmt.Sprintf("%s:%d", h.paths.HTTPAddr, h.paths.HTTPPort) utils.Logger.Infof("Proxy server is listening on %s", addr) var err error if h.paths.HTTPSsl { err = http.ListenAndServeTLS( addr, h.paths.HTTPSslCert, h.paths.HTTPSslKey, h) } else { err = http.ListenAndServe(addr, h) } if err != nil { utils.Logger.Error("Failed to start reverse proxy:", "error", err) } }() } // Kill the app on signal. ch := make(chan os.Signal) signal.Notify(ch, os.Interrupt, os.Kill) <-ch if h.app != nil { h.app.Kill() } os.Exit(1) }
go
{ "resource": "" }
q18017
getFreePort
train
func getFreePort() (port int) { conn, err := net.Listen("tcp", ":0") if err != nil { utils.Logger.Fatal("Unable to fetch a freee port address", "error", err) } port = conn.Addr().(*net.TCPAddr).Port err = conn.Close() if err != nil { utils.Logger.Fatal("Unable to close port", "error", err) } return port }
go
{ "resource": "" }
q18018
appendStruct
train
func appendStruct(fileName string, specs []*model.TypeInfo, pkgImportPath string, pkg *ast.Package, decl ast.Decl, imports map[string]string, fset *token.FileSet) []*model.TypeInfo { // Filter out non-Struct type declarations. spec, found := getStructTypeDecl(decl, fset) if !found { return specs } structType := spec.Type.(*ast.StructType) // At this point we know it's a type declaration for a struct. // Fill in the rest of the info by diving into the fields. // Add it provisionally to the Controller list -- it's later filtered using field info. controllerSpec := &model.TypeInfo{ StructName: spec.Name.Name, ImportPath: pkgImportPath, PackageName: pkg.Name, } for _, field := range structType.Fields.List { // If field.Names is set, it's not an embedded type. if field.Names != nil { continue } // A direct "sub-type" has an ast.Field as either: // Ident { "AppController" } // SelectorExpr { "rev", "Controller" } // Additionally, that can be wrapped by StarExprs. fieldType := field.Type pkgName, typeName := func() (string, string) { // Drill through any StarExprs. for { if starExpr, ok := fieldType.(*ast.StarExpr); ok { fieldType = starExpr.X continue } break } // If the embedded type is in the same package, it's an Ident. if ident, ok := fieldType.(*ast.Ident); ok { return "", ident.Name } if selectorExpr, ok := fieldType.(*ast.SelectorExpr); ok { if pkgIdent, ok := selectorExpr.X.(*ast.Ident); ok { return pkgIdent.Name, selectorExpr.Sel.Name } } return "", "" }() // If a typename wasn't found, skip it. if typeName == "" { continue } // Find the import path for this type. // If it was referenced without a package name, use the current package import path. // Else, look up the package's import path by name. var importPath string if pkgName == "" { importPath = pkgImportPath } else { var ok bool if importPath, ok = imports[pkgName]; !ok { utils.Logger.Error("Error: Failed to find import path for ", "package", pkgName, "type", typeName) continue } } controllerSpec.EmbeddedTypes = append(controllerSpec.EmbeddedTypes, &model.EmbeddedTypeName{ ImportPath: importPath, StructName: typeName, }) } return append(specs, controllerSpec) }
go
{ "resource": "" }
q18019
appendSourceInfo
train
func appendSourceInfo(srcInfo1, srcInfo2 *model.SourceInfo) *model.SourceInfo { if srcInfo1 == nil { return srcInfo2 } srcInfo1.StructSpecs = append(srcInfo1.StructSpecs, srcInfo2.StructSpecs...) srcInfo1.InitImportPaths = append(srcInfo1.InitImportPaths, srcInfo2.InitImportPaths...) for k, v := range srcInfo2.ValidationKeys { if _, ok := srcInfo1.ValidationKeys[k]; ok { utils.Logger.Warn("Warn: Key conflict when scanning validation calls:", "key", k) continue } srcInfo1.ValidationKeys[k] = v } return srcInfo1 }
go
{ "resource": "" }
q18020
NewBuildError
train
func NewBuildError(message string, args ...interface{}) (b *BuildError) { Logger.Info(message, args...) b = &BuildError{} b.Message = message b.Args = args b.Stack = logger.NewCallStack() Logger.Info("Stack", "stack", b.Stack) return b }
go
{ "resource": "" }
q18021
NewBuildIfError
train
func NewBuildIfError(err error, message string, args ...interface{}) (b error) { if err != nil { if berr, ok := err.(*BuildError); ok { // This is already a build error so just append the args berr.Args = append(berr.Args, args...) return berr } else { args = append(args, "error", err.Error()) b = NewBuildError(message, args...) } } return }
go
{ "resource": "" }
q18022
ProcessSource
train
func ProcessSource(paths *model.RevelContainer) (_ *model.SourceInfo, compileError error) { pc := &processContainer{paths: paths} for _, root := range paths.CodePaths { rootImportPath := importPathFromPath(root, paths.BasePath) if rootImportPath == "" { utils.Logger.Info("Skipping empty code path", "path", root) continue } pc.root, pc.rootImportPath = root, rootImportPath // Start walking the directory tree. compileError = utils.Walk(root, pc.processPath) if compileError != nil { return } } return pc.srcInfo, compileError }
go
{ "resource": "" }
q18023
processPath
train
func (pc *processContainer) processPath(path string, info os.FileInfo, err error) error { if err != nil { utils.Logger.Error("Error scanning app source:", "error", err) return nil } if !info.IsDir() || info.Name() == "tmp" { return nil } // Get the import path of the package. pkgImportPath := pc.rootImportPath if pc.root != path { pkgImportPath = pc.rootImportPath + "/" + filepath.ToSlash(path[len(pc.root)+1:]) } // Parse files within the path. var pkgs map[string]*ast.Package fset := token.NewFileSet() pkgs, err = parser.ParseDir( fset, path, func(f os.FileInfo) bool { return !f.IsDir() && !strings.HasPrefix(f.Name(), ".") && strings.HasSuffix(f.Name(), ".go") }, 0) if err != nil { if errList, ok := err.(scanner.ErrorList); ok { var pos = errList[0].Pos newError := &utils.Error{ SourceType: ".go source", Title: "Go Compilation Error", Path: pos.Filename, Description: errList[0].Msg, Line: pos.Line, Column: pos.Column, SourceLines: utils.MustReadLines(pos.Filename), } errorLink := pc.paths.Config.StringDefault("error.link", "") if errorLink != "" { newError.SetLink(errorLink) } return newError } // This is exception, err already checked above. Here just a print ast.Print(nil, err) utils.Logger.Fatal("Failed to parse dir", "error", err) } // Skip "main" packages. delete(pkgs, "main") // Ignore packages that end with _test // These cannot be included in source code that is not generated specifically as a test for i := range pkgs { if len(i) > 6 { if string(i[len(i)-5:]) == "_test" { delete(pkgs, i) } } } // If there is no code in this directory, skip it. if len(pkgs) == 0 { return nil } // There should be only one package in this directory. if len(pkgs) > 1 { for i := range pkgs { println("Found package ", i) } utils.Logger.Fatal("Most unexpected! Multiple packages in a single directory:", "packages", pkgs) } var pkg *ast.Package for _, v := range pkgs { pkg = v } if pkg != nil { pc.srcInfo = appendSourceInfo(pc.srcInfo, processPackage(fset, pkgImportPath, path, pkg)) } else { utils.Logger.Info("Ignoring package, because it contained no packages", "path", path) } return nil }
go
{ "resource": "" }
q18024
processPackage
train
func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo { var ( structSpecs []*model.TypeInfo initImportPaths []string methodSpecs = make(methodMap) validationKeys = make(map[string]map[int]string) scanControllers = strings.HasSuffix(pkgImportPath, "/controllers") || strings.Contains(pkgImportPath, "/controllers/") scanTests = strings.HasSuffix(pkgImportPath, "/tests") || strings.Contains(pkgImportPath, "/tests/") ) // For each source file in the package... utils.Logger.Info("Exaimining files in path", "package", pkgPath) for fname, file := range pkg.Files { // Imports maps the package key to the full import path. // e.g. import "sample/app/models" => "models": "sample/app/models" imports := map[string]string{} // For each declaration in the source file... for _, decl := range file.Decls { addImports(imports, decl, pkgPath) if scanControllers { // Match and add both structs and methods structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset) appendAction(fset, methodSpecs, decl, pkgImportPath, pkg.Name, imports) } else if scanTests { structSpecs = appendStruct(fname, structSpecs, pkgImportPath, pkg, decl, imports, fset) } // If this is a func... (ignore nil for external (non-Go) function) if funcDecl, ok := decl.(*ast.FuncDecl); ok && funcDecl.Body != nil { // Scan it for validation calls lineKeys := GetValidationKeys(fname, fset, funcDecl, imports) if len(lineKeys) > 0 { validationKeys[pkgImportPath+"."+getFuncName(funcDecl)] = lineKeys } // Check if it's an init function. if funcDecl.Name.Name == "init" { initImportPaths = []string{pkgImportPath} } } } } // Add the method specs to the struct specs. for _, spec := range structSpecs { spec.MethodSpecs = methodSpecs[spec.StructName] } return &model.SourceInfo{ StructSpecs: structSpecs, ValidationKeys: validationKeys, InitImportPaths: initImportPaths, } }
go
{ "resource": "" }
q18025
getStructTypeDecl
train
func getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) { genDecl, ok := decl.(*ast.GenDecl) if !ok { return } if genDecl.Tok != token.TYPE { return } if len(genDecl.Specs) == 0 { utils.Logger.Warn("Warn: Surprising: %s:%d Decl contains no specifications", fset.Position(decl.Pos()).Filename, fset.Position(decl.Pos()).Line) return } spec = genDecl.Specs[0].(*ast.TypeSpec) _, found = spec.Type.(*ast.StructType) return }
go
{ "resource": "" }
q18026
NewApp
train
func NewApp(binPath string, paths *model.RevelContainer) *App { return &App{BinaryPath: binPath, Paths: paths, Port: paths.HTTPPort} }
go
{ "resource": "" }
q18027
Cmd
train
func (a *App) Cmd(runMode string) AppCmd { a.cmd = NewAppCmd(a.BinaryPath, a.Port, runMode, a.Paths) return a.cmd }
go
{ "resource": "" }
q18028
NewAppCmd
train
func NewAppCmd(binPath string, port int, runMode string, paths *model.RevelContainer) AppCmd { cmd := exec.Command(binPath, fmt.Sprintf("-port=%d", port), fmt.Sprintf("-importPath=%s", paths.ImportPath), fmt.Sprintf("-runMode=%s", runMode)) cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr return AppCmd{cmd} }
go
{ "resource": "" }
q18029
Start
train
func (cmd AppCmd) Start(c *model.CommandConfig) error { listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}} cmd.Stdout = listeningWriter utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args, "dir", cmd.Dir, "env", cmd.Env) utils.CmdInit(cmd.Cmd, c.AppPath) if err := cmd.Cmd.Start(); err != nil { utils.Logger.Fatal("Error running:", "error", err) } select { case exitState := <-cmd.waitChan(): fmt.Println("Startup failure view previous messages, \n Proxy is listening :", c.Run.Port) err := utils.NewError("","Revel Run Error", "starting your application there was an exception. See terminal output, " + exitState,"") // TODO pretiffy command line output // err.MetaError = listeningWriter.getLastOutput() return err case <-time.After(60 * time.Second): println("Revel proxy is listening, point your browser to :", c.Run.Port) utils.Logger.Error("Killing revel server process did not respond after wait timeout.", "processid", cmd.Process.Pid) cmd.Kill() return errors.New("revel/harness: app timed out") case <-listeningWriter.notifyReady: println("Revel proxy is listening, point your browser to :", c.Run.Port) return nil } }
go
{ "resource": "" }
q18030
Run
train
func (cmd AppCmd) Run() { utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args) if err := cmd.Cmd.Run(); err != nil { utils.Logger.Fatal("Error running:", "error", err) } }
go
{ "resource": "" }
q18031
Kill
train
func (cmd AppCmd) Kill() { if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) { // Windows appears to send the kill to all threads, shutting down the // server before this can, this check will ensure the process is still running if _, err := os.FindProcess(int(cmd.Process.Pid));err!=nil { // Server has already exited utils.Logger.Info("Killing revel server pid", "pid", cmd.Process.Pid) return } // Send an interrupt signal to allow for a graceful shutdown utils.Logger.Info("Killing revel server pid", "pid", cmd.Process.Pid) var err error if runtime.GOOS == "windows" { // os.Interrupt is not available on windows err = cmd.Process.Signal(os.Kill) } else { err = cmd.Process.Signal(os.Interrupt) } if err != nil { utils.Logger.Error( "Revel app failed to kill process.", "processid", cmd.Process.Pid,"error",err, "killerror", cmd.Process.Kill()) return } // Wait for the shutdown ch := make(chan bool, 1) go func() { s, err := cmd.Process.Wait() defer func() { ch <- true }() if err != nil { utils.Logger.Info("Wait failed for process ", "error", err) } if s != nil { utils.Logger.Info("Revel App exited", "state", s.String()) } }() // Use a timer to ensure that the process exits utils.Logger.Info("Waiting to exit") select { case <-ch: return case <-time.After(60 * time.Second): // Kill the process utils.Logger.Error( "Revel app failed to exit in 60 seconds - killing.", "processid", cmd.Process.Pid, "killerror", cmd.Process.Kill()) } utils.Logger.Info("Done Waiting to exit") } }
go
{ "resource": "" }
q18032
Write
train
func (w *startupListeningWriter) Write(p []byte) (int, error) { if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) { w.notifyReady <- true w.notifyReady = nil } if w.c.HistoricMode { if w.notifyReady != nil && bytes.Contains(p, []byte("Listening on")) { w.notifyReady <- true w.notifyReady = nil } } if w.notifyReady!=nil { w.buffer.Write(p) } return w.dest.Write(p) }
go
{ "resource": "" }
q18033
NewWatcher
train
func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher { return &Watcher{ forceRefresh: true, lastError: -1, paths: paths, refreshTimerMS: time.Duration(paths.Config.IntDefault("watch.rebuild.delay", 10)), eagerRefresh: eagerRefresh || paths.DevMode && paths.Config.BoolDefault("watch", true) && paths.Config.StringDefault("watch.mode", "normal") == "eager", timerMutex: &sync.Mutex{}, refreshChannel: make(chan *utils.Error, 10), refreshChannelCount: 0, } }
go
{ "resource": "" }
q18034
NotifyWhenUpdated
train
func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher) { for { select { case ev := <-watcher.Events: if w.rebuildRequired(ev, listener) { if w.serial { // Serialize listener.Refresh() calls. w.notifyMutex.Lock() if err := listener.Refresh(); err != nil { utils.Logger.Error("Watcher: Listener refresh reported error:", "error", err) } w.notifyMutex.Unlock() } else { // Run refresh in parallel go func() { w.notifyInProcess(listener) }() } } case <-watcher.Errors: continue } } }
go
{ "resource": "" }
q18035
notifyInProcess
train
func (w *Watcher) notifyInProcess(listener Listener) (err *utils.Error) { shouldReturn := false // This code block ensures that either a timer is created // or that a process would be added the the h.refreshChannel func() { w.timerMutex.Lock() defer w.timerMutex.Unlock() // If we are in the process of a rebuild, forceRefresh will always be true w.forceRefresh = true if w.refreshTimer != nil { utils.Logger.Info("Found existing timer running, resetting") w.refreshTimer.Reset(time.Millisecond * w.refreshTimerMS) shouldReturn = true w.refreshChannelCount++ } else { w.refreshTimer = time.NewTimer(time.Millisecond * w.refreshTimerMS) } }() // If another process is already waiting for the timer this one // only needs to return the output from the channel if shouldReturn { return <-w.refreshChannel } utils.Logger.Info("Waiting for refresh timer to expire") <-w.refreshTimer.C w.timerMutex.Lock() // Ensure the queue is properly dispatched even if a panic occurs defer func() { for x := 0; x < w.refreshChannelCount; x++ { w.refreshChannel <- err } w.refreshChannelCount = 0 w.refreshTimer = nil w.timerMutex.Unlock() }() err = listener.Refresh() if err != nil { utils.Logger.Info("Watcher: Recording error last build, setting rebuild on", "error", err) } else { w.lastError = -1 w.forceRefresh = false } utils.Logger.Info("Rebuilt, result", "error", err) return }
go
{ "resource": "" }
q18036
updateCleanConfig
train
func updateCleanConfig(c *model.CommandConfig, args []string) bool { c.Index = model.CLEAN if len(args) == 0 { fmt.Fprintf(os.Stderr, cmdClean.Long) return false } c.Clean.ImportPath = args[0] return true }
go
{ "resource": "" }
q18037
cleanApp
train
func cleanApp(c *model.CommandConfig) (err error) { appPkg, err := build.Import(c.ImportPath, "", build.FindOnly) if err != nil { utils.Logger.Fatal("Abort: Failed to find import path:", "error", err) } purgeDirs := []string{ filepath.Join(appPkg.Dir, "app", "tmp"), filepath.Join(appPkg.Dir, "app", "routes"), } for _, dir := range purgeDirs { fmt.Println("Removing:", dir) err = os.RemoveAll(dir) if err != nil { utils.Logger.Error("Failed to clean dir", "error", err) return } } return err }
go
{ "resource": "" }
q18038
generateSecret
train
func generateSecret() string { chars := make([]byte, 64) for i := 0; i < 64; i++ { chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))] } return string(chars) }
go
{ "resource": "" }
q18039
setApplicationPath
train
func setApplicationPath(c *model.CommandConfig) (err error) { // revel/revel#1014 validate relative path, we cannot use built-in functions // since Go import path is valid relative path too. // so check basic part of the path, which is "." if filepath.IsAbs(c.ImportPath) || strings.HasPrefix(c.ImportPath, ".") { utils.Logger.Fatalf("Abort: '%s' looks like a directory. Please provide a Go import path instead.", c.ImportPath) } // If we are running a vendored version of Revel we do not need to check for it. if !c.New.Vendored { _, err = build.Import(model.RevelImportPath, "", build.FindOnly) if err != nil { //// Go get the revel project err = c.PackageResolver(model.RevelImportPath) if err != nil { return utils.NewBuildIfError(err, "Failed to fetch revel "+model.RevelImportPath) } } } c.AppName = filepath.Base(c.AppPath) return nil }
go
{ "resource": "" }
q18040
setSkeletonPath
train
func setSkeletonPath(c *model.CommandConfig) (err error) { if len(c.New.SkeletonPath) == 0 { c.New.SkeletonPath = "https://" + RevelSkeletonsImportPath + ":basic/bootstrap4" } // First check to see the protocol of the string sp, err := url.Parse(c.New.SkeletonPath) if err == nil { utils.Logger.Info("Detected skeleton path", "path", sp) switch strings.ToLower(sp.Scheme) { // TODO Add support for ftp, sftp, scp ?? case "" : sp.Scheme="file" fallthrough case "file" : fullpath := sp.String()[7:] if !filepath.IsAbs(fullpath) { fullpath, err = filepath.Abs(fullpath) if err!=nil { return } } c.New.SkeletonPath = fullpath utils.Logger.Info("Set skeleton path to ", fullpath) if !utils.DirExists(fullpath) { return fmt.Errorf("Failed to find skeleton in filepath %s %s", fullpath, sp.String()) } case "git": fallthrough case "http": fallthrough case "https": if err := newLoadFromGit(c, sp); err != nil { return err } default: utils.Logger.Fatal("Unsupported skeleton schema ", "path", c.New.SkeletonPath) } // TODO check to see if the path needs to be extracted } else { utils.Logger.Fatal("Invalid skeleton path format", "path", c.New.SkeletonPath) } return }
go
{ "resource": "" }
q18041
newLoadFromGit
train
func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) { // This method indicates we need to fetch from a repository using git // Execute "git clone get <pkg>" targetPath := filepath.Join(os.TempDir(), "revel", "skeleton") os.RemoveAll(targetPath) pathpart := strings.Split(sp.Path, ":") getCmd := exec.Command("git", "clone", sp.Scheme+"://"+sp.Host+pathpart[0], targetPath) utils.Logger.Info("Exec:", "args", getCmd.Args) getOutput, err := getCmd.CombinedOutput() if err != nil { utils.Logger.Fatal("Abort: could not clone the Skeleton source code: ","output", string(getOutput), "path", c.New.SkeletonPath) } outputPath := targetPath if len(pathpart) > 1 { outputPath = filepath.Join(targetPath, filepath.Join(strings.Split(pathpart[1], string('/'))...)) } outputPath, _ = filepath.Abs(outputPath) if !strings.HasPrefix(outputPath, targetPath) { utils.Logger.Fatal("Unusual target path outside root path", "target", outputPath, "root", targetPath) } c.New.SkeletonPath = outputPath return }
go
{ "resource": "" }
q18042
Retry
train
func Retry(format string, args ...interface{}) { // Ensure the user's command prompt starts on the next line. if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(os.Stderr, format, args...) panic(format) // Panic instead of os.Exit so that deferred will run. }
go
{ "resource": "" }
q18043
New
train
func New(key string) *Client { c := &Client{ Endpoint: Endpoint, Interval: 5 * time.Second, Size: 250, Logger: log.New(os.Stderr, "segment ", log.LstdFlags), Verbose: false, Client: *http.DefaultClient, key: key, msgs: make(chan interface{}, 100), quit: make(chan struct{}), shutdown: make(chan struct{}), now: time.Now, uid: uid, } c.logf("You are currently using the v2 version analytics-go, which is being deprecated. Please update to v3 as soon as you can https://segment.com/docs/sources/server/go/#migrating-from-v2") c.upcond.L = &c.upmtx return c }
go
{ "resource": "" }
q18044
Alias
train
func (c *Client) Alias(msg *Alias) error { if msg.UserId == "" { return errors.New("You must pass a 'userId'.") } if msg.PreviousId == "" { return errors.New("You must pass a 'previousId'.") } msg.Type = "alias" c.queue(msg) return nil }
go
{ "resource": "" }
q18045
Page
train
func (c *Client) Page(msg *Page) error { if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "page" c.queue(msg) return nil }
go
{ "resource": "" }
q18046
Group
train
func (c *Client) Group(msg *Group) error { if msg.GroupId == "" { return errors.New("You must pass a 'groupId'.") } if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "group" c.queue(msg) return nil }
go
{ "resource": "" }
q18047
Track
train
func (c *Client) Track(msg *Track) error { if msg.Event == "" { return errors.New("You must pass 'event'.") } if msg.UserId == "" && msg.AnonymousId == "" { return errors.New("You must pass either an 'anonymousId' or 'userId'.") } msg.Type = "track" c.queue(msg) return nil }
go
{ "resource": "" }
q18048
queue
train
func (c *Client) queue(msg message) { c.once.Do(c.startLoop) msg.setMessageId(c.uid()) msg.setTimestamp(timestamp(c.now())) c.msgs <- msg }
go
{ "resource": "" }
q18049
Close
train
func (c *Client) Close() error { c.once.Do(c.startLoop) c.quit <- struct{}{} close(c.msgs) <-c.shutdown return nil }
go
{ "resource": "" }
q18050
send
train
func (c *Client) send(msgs []interface{}) error { if len(msgs) == 0 { return nil } batch := new(Batch) batch.Messages = msgs batch.MessageId = c.uid() batch.SentAt = timestamp(c.now()) batch.Context = DefaultContext b, err := json.Marshal(batch) if err != nil { return fmt.Errorf("error marshalling msgs: %s", err) } for i := 0; i < 10; i++ { if err = c.upload(b); err == nil { return nil } Backo.Sleep(i) } return err }
go
{ "resource": "" }
q18051
upload
train
func (c *Client) upload(b []byte) error { url := c.Endpoint + "/v1/batch" req, err := http.NewRequest("POST", url, bytes.NewReader(b)) if err != nil { return fmt.Errorf("error creating request: %s", err) } req.Header.Add("User-Agent", "analytics-go (version: "+Version+")") req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Length", string(len(b))) req.SetBasicAuth(c.key, "") res, err := c.Client.Do(req) if err != nil { return fmt.Errorf("error sending request: %s", err) } defer res.Body.Close() if res.StatusCode < 400 { c.verbose("response %s", res.Status) return nil } body, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("error reading response body: %s", err) } return fmt.Errorf("response %s: %d – %s", res.Status, res.StatusCode, string(body)) }
go
{ "resource": "" }
q18052
loop
train
func (c *Client) loop() { var msgs []interface{} tick := time.NewTicker(c.Interval) for { select { case msg := <-c.msgs: c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg) msgs = append(msgs, msg) if len(msgs) == c.Size { c.verbose("exceeded %d messages – flushing", c.Size) c.sendAsync(msgs) msgs = make([]interface{}, 0, c.Size) } case <-tick.C: if len(msgs) > 0 { c.verbose("interval reached - flushing %d", len(msgs)) c.sendAsync(msgs) msgs = make([]interface{}, 0, c.Size) } else { c.verbose("interval reached – nothing to send") } case <-c.quit: tick.Stop() c.verbose("exit requested – draining msgs") // drain the msg channel. for msg := range c.msgs { c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg) msgs = append(msgs, msg) } c.verbose("exit requested – flushing %d", len(msgs)) c.sendAsync(msgs) c.wg.Wait() c.verbose("exit") c.shutdown <- struct{}{} return } } }
go
{ "resource": "" }
q18053
verbose
train
func (c *Client) verbose(msg string, args ...interface{}) { if c.Verbose { c.Logger.Printf(msg, args...) } }
go
{ "resource": "" }
q18054
logf
train
func (c *Client) logf(msg string, args ...interface{}) { c.Logger.Printf(msg, args...) }
go
{ "resource": "" }
q18055
setTimestamp
train
func (m *Message) setTimestamp(s string) { if m.Timestamp == "" { m.Timestamp = s } }
go
{ "resource": "" }
q18056
setMessageId
train
func (m *Message) setMessageId(s string) { if m.MessageId == "" { m.MessageId = s } }
go
{ "resource": "" }
q18057
New
train
func New(db *gorm.DB) i18n.Backend { db.AutoMigrate(&Translation{}) if err := db.Model(&Translation{}).AddUniqueIndex("idx_translations_key_with_locale", "locale", "key").Error; err != nil { fmt.Printf("Failed to create unique index for translations key & locale, got: %v\n", err.Error()) } return &Backend{DB: db} }
go
{ "resource": "" }
q18058
LoadTranslations
train
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) { backend.DB.Find(&translations) return translations }
go
{ "resource": "" }
q18059
SaveTranslation
train
func (backend *Backend) SaveTranslation(t *i18n.Translation) error { return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}). Assign(Translation{Value: t.Value}). FirstOrCreate(&Translation{}).Error }
go
{ "resource": "" }
q18060
DeleteTranslation
train
func (backend *Backend) DeleteTranslation(t *i18n.Translation) error { return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}).Delete(&Translation{}).Error }
go
{ "resource": "" }
q18061
New
train
func New(paths ...string) *Backend { backend := &Backend{} var files []string for _, p := range paths { if file, err := os.Open(p); err == nil { defer file.Close() if fileInfo, err := file.Stat(); err == nil { if fileInfo.IsDir() { yamlFiles, _ := filepath.Glob(filepath.Join(p, "*.yaml")) files = append(files, yamlFiles...) ymlFiles, _ := filepath.Glob(filepath.Join(p, "*.yml")) files = append(files, ymlFiles...) } else if fileInfo.Mode().IsRegular() { files = append(files, p) } } } } for _, file := range files { if content, err := ioutil.ReadFile(file); err == nil { backend.contents = append(backend.contents, content) } } return backend }
go
{ "resource": "" }
q18062
NewWithWalk
train
func NewWithWalk(paths ...string) i18n.Backend { backend := &Backend{} var files []string for _, p := range paths { filepath.Walk(p, func(path string, fileInfo os.FileInfo, err error) error { if isYamlFile(fileInfo) { files = append(files, path) } return nil }) } for _, file := range files { if content, err := ioutil.ReadFile(file); err == nil { backend.contents = append(backend.contents, content) } } return backend }
go
{ "resource": "" }
q18063
NewWithFilesystem
train
func NewWithFilesystem(fss ...http.FileSystem) i18n.Backend { backend := &Backend{} for _, fs := range fss { backend.contents = append(backend.contents, walkFilesystem(fs, nil, "/")...) } return backend }
go
{ "resource": "" }
q18064
LoadYAMLContent
train
func (backend *Backend) LoadYAMLContent(content []byte) (translations []*i18n.Translation, err error) { var slice yaml.MapSlice if err = yaml.Unmarshal(content, &slice); err == nil { for _, item := range slice { translations = append(translations, loadTranslationsFromYaml(item.Key.(string) /* locale */, item.Value, []string{})...) } } return translations, err }
go
{ "resource": "" }
q18065
LoadTranslations
train
func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) { for _, content := range backend.contents { if results, err := backend.LoadYAMLContent(content); err == nil { translations = append(translations, results...) } else { panic(err) } } return translations }
go
{ "resource": "" }
q18066
New
train
func New(backends ...Backend) *I18n { i18n := &I18n{Backends: backends, cacheStore: memory.New()} i18n.loadToCacheStore() return i18n }
go
{ "resource": "" }
q18067
SetCacheStore
train
func (i18n *I18n) SetCacheStore(cacheStore cache.CacheStoreInterface) { i18n.cacheStore = cacheStore i18n.loadToCacheStore() }
go
{ "resource": "" }
q18068
AddTranslation
train
func (i18n *I18n) AddTranslation(translation *Translation) error { return i18n.cacheStore.Set(cacheKey(translation.Locale, translation.Key), translation) }
go
{ "resource": "" }
q18069
SaveTranslation
train
func (i18n *I18n) SaveTranslation(translation *Translation) error { for _, backend := range i18n.Backends { if backend.SaveTranslation(translation) == nil { i18n.AddTranslation(translation) return nil } } return errors.New("failed to save translation") }
go
{ "resource": "" }
q18070
DeleteTranslation
train
func (i18n *I18n) DeleteTranslation(translation *Translation) (err error) { for _, backend := range i18n.Backends { backend.DeleteTranslation(translation) } return i18n.cacheStore.Delete(cacheKey(translation.Locale, translation.Key)) }
go
{ "resource": "" }
q18071
Scope
train
func (i18n *I18n) Scope(scope string) admin.I18n { return &I18n{cacheStore: i18n.cacheStore, scope: scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: i18n.fallbackLocales} }
go
{ "resource": "" }
q18072
Fallbacks
train
func (i18n *I18n) Fallbacks(locale ...string) admin.I18n { return &I18n{cacheStore: i18n.cacheStore, scope: i18n.scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: locale} }
go
{ "resource": "" }
q18073
T
train
func (i18n *I18n) T(locale, key string, args ...interface{}) template.HTML { var ( value = i18n.value translationKey = key fallbackLocales = i18n.fallbackLocales ) if locale == "" { locale = Default } if locales, ok := i18n.FallbackLocales[locale]; ok { fallbackLocales = append(fallbackLocales, locales...) } fallbackLocales = append(fallbackLocales, Default) if i18n.scope != "" { translationKey = strings.Join([]string{i18n.scope, key}, ".") } var translation Translation if err := i18n.cacheStore.Unmarshal(cacheKey(locale, key), &translation); err != nil || translation.Value == "" { for _, fallbackLocale := range fallbackLocales { if err := i18n.cacheStore.Unmarshal(cacheKey(fallbackLocale, key), &translation); err == nil && translation.Value != "" { break } } if translation.Value == "" { // Get default translation if not translated if err := i18n.cacheStore.Unmarshal(cacheKey(Default, key), &translation); err != nil || translation.Value == "" { // If not initialized var defaultBackend Backend if len(i18n.Backends) > 0 { defaultBackend = i18n.Backends[0] } translation = Translation{Key: translationKey, Value: value, Locale: locale, Backend: defaultBackend} // Save translation i18n.SaveTranslation(&translation) } } } if translation.Value != "" { value = translation.Value } else { value = key } if str, err := cldr.Parse(locale, value, args...); err == nil { value = str } return template.HTML(value) }
go
{ "resource": "" }
q18074
FuncMap
train
func FuncMap(I18n *i18n.I18n, locale string, enableInlineEdit bool) template.FuncMap { return template.FuncMap{ "t": InlineEdit(I18n, locale, enableInlineEdit), } }
go
{ "resource": "" }
q18075
InlineEdit
train
func InlineEdit(I18n *i18n.I18n, locale string, isInline bool) func(string, ...interface{}) template.HTML { return func(key string, args ...interface{}) template.HTML { // Get Translation Value var value template.HTML var defaultValue string if len(args) > 0 { if args[0] == nil { defaultValue = key } else { defaultValue = fmt.Sprint(args[0]) } value = I18n.Default(defaultValue).T(locale, key, args[1:]...) } else { value = I18n.T(locale, key) } // Append inline-edit script/tag if isInline { var editType string if len(value) > 25 { editType = "data-type=\"textarea\"" } prefix := I18n.Resource.GetAdmin().GetRouter().Prefix assetsTag := fmt.Sprintf("<script data-prefix=\"%v\" src=\"%v/assets/javascripts/i18n-checker.js?theme=i18n\"></script>", prefix, prefix) return template.HTML(fmt.Sprintf("%s<span class=\"qor-i18n-inline\" %s data-locale=\"%s\" data-key=\"%s\">%s</span>", assetsTag, editType, locale, key, string(value))) } return value } }
go
{ "resource": "" }
q18076
AsFloatBuffer
train
func (b *PCMBuffer) AsFloatBuffer() *FloatBuffer { newB := &FloatBuffer{} newB.Data = b.AsF64() if b.Format != nil { newB.Format = &Format{ NumChannels: b.Format.NumChannels, SampleRate: b.Format.SampleRate, } } return newB }
go
{ "resource": "" }
q18077
AsIntBuffer
train
func (b *PCMBuffer) AsIntBuffer() *IntBuffer { newB := &IntBuffer{} newB.Data = b.AsInt() if b.Format != nil { newB.Format = &Format{ NumChannels: b.Format.NumChannels, SampleRate: b.Format.SampleRate, } } return newB }
go
{ "resource": "" }
q18078
AsI8
train
func (b *PCMBuffer) AsI8() (out []int8) { if b == nil { return nil } switch b.DataType { case DataTypeI8: return b.I8 case DataTypeI16: out = make([]int8, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = int8(b.I16[i]) } case DataTypeI32: out = make([]int8, len(b.I32)) for i := 0; i < len(b.I32); i++ { out[i] = int8(b.I32[i]) } case DataTypeF32: out = make([]int8, len(b.F32)) for i := 0; i < len(b.F32); i++ { out[i] = int8(b.F32[i]) } case DataTypeF64: out = make([]int8, len(b.F64)) for i := 0; i < len(b.F64); i++ { out[i] = int8(b.F64[i]) } } return out }
go
{ "resource": "" }
q18079
AsF64
train
func (b *PCMBuffer) AsF64() (out []float64) { if b == nil { return nil } switch b.DataType { case DataTypeI8: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I8)) for i := 0; i < len(b.I8); i++ { out[i] = float64(int64(b.I8[i])) / factor } case DataTypeI16: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = float64(int64(b.I16[i])) / factor } case DataTypeI32: bitDepth := b.calculateIntBitDepth() factor := math.Pow(2, 8*float64(bitDepth/8)-1) out = make([]float64, len(b.I16)) for i := 0; i < len(b.I16); i++ { out[i] = float64(int64(b.I16[i])) / factor } case DataTypeF32: out = make([]float64, len(b.F32)) for i := 0; i < len(b.F32); i++ { out[i] = float64(b.F32[i]) } case DataTypeF64: return b.F64 } return out }
go
{ "resource": "" }
q18080
calculateIntBitDepth
train
func (b *PCMBuffer) calculateIntBitDepth() uint8 { if b == nil { return 0 } bitDepth := b.SourceBitDepth if bitDepth != 0 { return bitDepth } var max int64 switch b.DataType { case DataTypeI8: var i8max int8 for _, s := range b.I8 { if s > i8max { i8max = s } } max = int64(i8max) case DataTypeI16: var i16max int16 for _, s := range b.I16 { if s > i16max { i16max = s } } max = int64(i16max) case DataTypeI32: var i32max int32 for _, s := range b.I32 { if s > i32max { i32max = s } } max = int64(i32max) default: // This method is only meant to be used on int buffers. return bitDepth } bitDepth = 8 if max > 127 { bitDepth = 16 } // greater than int16, expecting int24 if max > 32767 { bitDepth = 24 } // int 32 if max > 8388607 { bitDepth = 32 } // int 64 if max > 4294967295 { bitDepth = 64 } return bitDepth }
go
{ "resource": "" }
q18081
AsFloat32Buffer
train
func (buf *IntBuffer) AsFloat32Buffer() *Float32Buffer { newB := &Float32Buffer{} newB.Data = make([]float32, len(buf.Data)) max := int64(0) // try to guess the bit depths without knowing the source if buf.SourceBitDepth == 0 { for _, s := range buf.Data { if int64(s) > max { max = int64(s) } } buf.SourceBitDepth = 8 if max > 127 { buf.SourceBitDepth = 16 } // greater than int16, expecting int24 if max > 32767 { buf.SourceBitDepth = 24 } // int 32 if max > 8388607 { buf.SourceBitDepth = 32 } // int 64 if max > 4294967295 { buf.SourceBitDepth = 64 } } newB.SourceBitDepth = buf.SourceBitDepth factor := math.Pow(2, float64(buf.SourceBitDepth)-1) for i := 0; i < len(buf.Data); i++ { newB.Data[i] = float32(float64(buf.Data[i]) / factor) } newB.Format = &Format{ NumChannels: buf.Format.NumChannels, SampleRate: buf.Format.SampleRate, } return newB }
go
{ "resource": "" }
q18082
IEEEFloatToInt
train
func IEEEFloatToInt(b [10]byte) int { var i uint32 // Negative number if (b[0] & 0x80) == 1 { return 0 } // Less than 1 if b[0] <= 0x3F { return 1 } // Too big if b[0] > 0x40 { return 67108864 } // Still too big if b[0] == 0x40 && b[1] > 0x1C { return 800000000 } i = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1) i >>= (29 - uint32(b[1])) return int(i) }
go
{ "resource": "" }
q18083
IntToIEEEFloat
train
func IntToIEEEFloat(i int) [10]byte { b := [10]byte{} num := float64(i) var sign int var expon int var fMant, fsMant float64 var hiMant, loMant uint if num < 0 { sign = 0x8000 } else { sign = 0 } if num == 0 { expon = 0 hiMant = 0 loMant = 0 } else { fMant, expon = math.Frexp(num) if (expon > 16384) || !(fMant < 1) { /* Infinity or NaN */ expon = sign | 0x7FFF hiMant = 0 loMant = 0 /* infinity */ } else { /* Finite */ expon += 16382 if expon < 0 { /* denormalized */ fMant = math.Ldexp(fMant, expon) expon = 0 } expon |= sign fMant = math.Ldexp(fMant, 32) fsMant = math.Floor(fMant) hiMant = uint(fsMant) fMant = math.Ldexp(fMant-fsMant, 32) fsMant = math.Floor(fMant) loMant = uint(fsMant) } } b[0] = byte(expon >> 8) b[1] = byte(expon) b[2] = byte(hiMant >> 24) b[3] = byte(hiMant >> 16) b[4] = byte(hiMant >> 8) b[5] = byte(hiMant) b[6] = byte(loMant >> 24) b[7] = byte(loMant >> 16) b[8] = byte(loMant >> 8) b[9] = byte(loMant) return b }
go
{ "resource": "" }
q18084
Uint24to32
train
func Uint24to32(bytes []byte) uint32 { var output uint32 output |= uint32(bytes[2]) << 0 output |= uint32(bytes[1]) << 8 output |= uint32(bytes[0]) << 16 return output }
go
{ "resource": "" }
q18085
Int24BETo32
train
func Int24BETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(0xFF&bytes[0])<<16 | int32(0xFF&bytes[1])<<8 | int32(0xFF&bytes[2]) if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss }
go
{ "resource": "" }
q18086
Int24LETo32
train
func Int24LETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(bytes[0]) | int32(bytes[1])<<8 | int32(bytes[2])<<16 if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss }
go
{ "resource": "" }
q18087
Uint32toUint24Bytes
train
func Uint32toUint24Bytes(n uint32) []byte { bytes := make([]byte, 3) bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
go
{ "resource": "" }
q18088
Int32toInt24LEBytes
train
func Int32toInt24LEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[2] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[0] = byte(n >> 0) return bytes }
go
{ "resource": "" }
q18089
Int32toInt24BEBytes
train
func Int32toInt24BEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
go
{ "resource": "" }
q18090
AsFloatBuffer
train
func (buf *Float32Buffer) AsFloatBuffer() *FloatBuffer { newB := &FloatBuffer{} newB.Data = make([]float64, len(buf.Data)) for i := 0; i < len(buf.Data); i++ { newB.Data[i] = float64(buf.Data[i]) } newB.Format = &Format{ NumChannels: buf.Format.NumChannels, SampleRate: buf.Format.SampleRate, } return newB }
go
{ "resource": "" }
q18091
TraceHandler
train
func (s *Sensor) TraceHandler(name, pattern string, handler http.HandlerFunc) (string, http.HandlerFunc) { return pattern, s.TracingHandler(name, handler) }
go
{ "resource": "" }
q18092
TracingHandler
train
func (s *Sensor) TracingHandler(name string, handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { s.WithTracingContext(name, w, req, func(span ot.Span, ctx context.Context) { // Capture response code for span hooks := httpsnoop.Hooks{ WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { return func(code int) { next(code) span.SetTag(string(ext.HTTPStatusCode), code) } }, } // Add hooks to response writer wrappedWriter := httpsnoop.Wrap(w, hooks) // Serve original handler handler.ServeHTTP(wrappedWriter, req.WithContext(ctx)) }) } }
go
{ "resource": "" }
q18093
TracingHttpRequest
train
func (s *Sensor) TracingHttpRequest(name string, parent, req *http.Request, client http.Client) (res *http.Response, err error) { var span ot.Span if parentSpan, ok := parent.Context().Value("parentSpan").(ot.Span); ok { span = s.tracer.StartSpan("client", ot.ChildOf(parentSpan.Context())) } else { span = s.tracer.StartSpan("client") } defer span.Finish() headersCarrier := ot.HTTPHeadersCarrier(req.Header) if err := s.tracer.Inject(span.Context(), ot.HTTPHeaders, headersCarrier); err != nil { return nil, err } res, err = client.Do(req.WithContext(context.Background())) span.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCClientEnum)) span.SetTag(string(ext.PeerHostname), req.Host) span.SetTag(string(ext.HTTPUrl), req.URL.String()) span.SetTag(string(ext.HTTPMethod), req.Method) span.SetTag(string(ext.HTTPStatusCode), res.StatusCode) if err != nil { if e, ok := err.(error); ok { span.LogFields(otlog.Error(e)) } else { span.LogFields(otlog.Object("error", err)) } } return }
go
{ "resource": "" }
q18094
WithTracingContext
train
func (s *Sensor) WithTracingContext(name string, w http.ResponseWriter, req *http.Request, f ContextSensitiveFunc) { s.WithTracingSpan(name, w, req, func(span ot.Span) { ctx := context.WithValue(req.Context(), "parentSpan", span) f(span, ctx) }) }
go
{ "resource": "" }
q18095
EumSnippet
train
func EumSnippet(apiKey string, traceID string, meta map[string]string) string { if len(apiKey) == 0 || len(traceID) == 0 { return "" } b, err := ioutil.ReadFile(eumTemplate) if err != nil { return "" } var snippet = string(b) var metaBuffer bytes.Buffer snippet = strings.Replace(snippet, "$apiKey", apiKey, -1) snippet = strings.Replace(snippet, "$traceId", traceID, -1) for key, value := range meta { metaBuffer.WriteString(" ineum('meta', '" + key + "', '" + value + "');\n") } snippet = strings.Replace(snippet, "$meta", metaBuffer.String(), -1) return snippet }
go
{ "resource": "" }
q18096
Header2ID
train
func Header2ID(header string) (int64, error) { // FIXME: We're assuming LittleEndian here // Parse unsigned 64 bit hex string into unsigned 64 bit base 10 integer if unsignedID, err := strconv.ParseUint(header, 16, 64); err == nil { // Write out _unsigned_ 64bit integer to byte buffer buf := new(bytes.Buffer) if err = binary.Write(buf, binary.LittleEndian, unsignedID); err == nil { // Read bytes back into _signed_ 64 bit integer var signedID int64 if err = binary.Read(buf, binary.LittleEndian, &signedID); err == nil { // The success case return signedID, nil } log.debug(err) } else { log.debug(err) } } else { log.debug(err) } return int64(0), errors.New("context corrupted; could not convert value") }
go
{ "resource": "" }
q18097
hexGatewayToAddr
train
func hexGatewayToAddr(gateway []rune) (string, error) { // gateway address is encoded in reverse order in hex if len(gateway) != 8 { return "", errors.New("invalid gateway length") } var octets [4]uint8 for i, hexOctet := range [4]string{ string(gateway[6:8]), // first octet of IP Address string(gateway[4:6]), // second octet string(gateway[2:4]), // third octet string(gateway[0:2]), // last octet } { octet, err := strconv.ParseUint(hexOctet, 16, 8) if err != nil { return "", err } octets[i] = uint8(octet) } return fmt.Sprintf("%v.%v.%v.%v", octets[0], octets[1], octets[2], octets[3]), nil }
go
{ "resource": "" }
q18098
SendDefaultServiceEvent
train
func SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) { if sensor == nil { // Since no sensor was initialized, there is no default service (as // configured on the sensor) so we send blank. SendServiceEvent("", title, text, sev, duration) } else { SendServiceEvent(sensor.serviceName, title, text, sev, duration) } }
go
{ "resource": "" }
q18099
SendServiceEvent
train
func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Severity: int(sev), Plugin: ServicePlugin, ID: service, Host: ServiceHost, Duration: int(duration / time.Millisecond), }) }
go
{ "resource": "" }