_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q19500 | incSendChanRefCount | train | func (n *Graph) incSendChanRefCount(c reflect.Value) {
n.sendChanMutex.Lock()
defer n.sendChanMutex.Unlock()
ptr := c.Pointer()
cnt := n.sendChanRefCount[ptr]
cnt++
n.sendChanRefCount[ptr] = cnt
} | go | {
"resource": ""
} |
q19501 | decSendChanRefCount | train | func (n *Graph) decSendChanRefCount(c reflect.Value) bool {
n.sendChanMutex.Lock()
defer n.sendChanMutex.Unlock()
ptr := c.Pointer()
cnt := n.sendChanRefCount[ptr]
if cnt == 0 {
return true //yes you may try to close a nonexistant channel, see what happens...
}
cnt--
n.sendChanRefCount[ptr] = cnt
return cnt == 0
} | go | {
"resource": ""
} |
q19502 | getInPort | train | func (n *Graph) getInPort(name string) (reflect.Value, error) {
pName, ok := n.inPorts[name]
if !ok {
return reflect.ValueOf(nil), fmt.Errorf("Inport not found: '%s'", name)
}
return pName.channel, nil
} | go | {
"resource": ""
} |
q19503 | getOutPort | train | func (n *Graph) getOutPort(name string) (reflect.Value, error) {
pName, ok := n.outPorts[name]
if !ok {
return reflect.ValueOf(nil), fmt.Errorf("Outport not found: '%s'", name)
}
return pName.channel, nil
} | go | {
"resource": ""
} |
q19504 | MapInPort | train | func (n *Graph) MapInPort(name, procName, procPort string) error {
var channel reflect.Value
var err error
if p, procFound := n.procs[procName]; procFound {
if g, isNet := p.(*Graph); isNet {
// Is a subnet
channel, err = g.getInPort(procPort)
} else {
// Is a proc
channel, err = n.getProcPort(procName, procPort, reflect.RecvDir)
}
} else {
return fmt.Errorf("Could not map inport: process '%s' not found", procName)
}
if err == nil {
n.inPorts[name] = port{proc: procName, port: procPort, channel: channel}
}
return err
} | go | {
"resource": ""
} |
q19505 | AddIIP | train | func (n *Graph) AddIIP(processName, portName string, data interface{}) error {
if _, exists := n.procs[processName]; exists {
n.iips = append(n.iips, iip{data: data, proc: processName, port: portName})
return nil
}
return fmt.Errorf("AddIIP error: could not find '%s.%s'", processName, portName)
} | go | {
"resource": ""
} |
q19506 | RemoveIIP | train | func (n *Graph) RemoveIIP(processName, portName string) error {
for i, p := range n.iips {
if p.proc == processName && p.port == portName {
// Remove item from the slice
n.iips[len(n.iips)-1], n.iips[i], n.iips = iip{}, n.iips[len(n.iips)-1], n.iips[:len(n.iips)-1]
return nil
}
}
return fmt.Errorf("RemoveIIP error: could not find IIP for '%s.%s'", processName, portName)
} | go | {
"resource": ""
} |
q19507 | sendIIPs | train | func (n *Graph) sendIIPs() error {
// Send initial IPs
for _, ip := range n.iips {
// Get the reciever port channel
var channel reflect.Value
found := false
shouldClose := false
// Try to find it among network inports
for _, inPort := range n.inPorts {
if inPort.proc == ip.proc && inPort.port == ip.port {
channel = inPort.channel
found = true
break
}
}
if !found {
// Try to find among connections
for _, conn := range n.connections {
if conn.tgt.proc == ip.proc && conn.tgt.port == ip.port {
channel = conn.channel
found = true
break
}
}
}
if !found {
// Try to find a proc and attach a new channel to it
recvPort, err := n.getProcPort(ip.proc, ip.port, reflect.RecvDir)
if err != nil {
return err
}
// Make a channel of an appropriate type
chanType := reflect.ChanOf(reflect.BothDir, recvPort.Type().Elem())
channel = reflect.MakeChan(chanType, n.conf.BufferSize)
recvPort.Set(channel)
found = true
shouldClose = true
}
if found {
// Send data to the port
go func() {
channel.Send(reflect.ValueOf(ip.data))
if shouldClose {
channel.Close()
}
}()
} else {
return fmt.Errorf("IIP target not found: '%s.%s'"+ip.proc, ip.port)
}
}
return nil
} | go | {
"resource": ""
} |
q19508 | NewGraph | train | func NewGraph(config ...GraphConfig) *Graph {
conf := defaultGraphConfig()
if len(config) == 1 {
conf = config[0]
}
return &Graph{
conf: conf,
waitGrp: new(sync.WaitGroup),
procs: make(map[string]interface{}, conf.Capacity),
inPorts: make(map[string]port, conf.Capacity),
outPorts: make(map[string]port, conf.Capacity),
connections: make([]connection, 0, conf.Capacity),
sendChanRefCount: make(map[uintptr]uint, conf.Capacity),
sendChanMutex: new(sync.Mutex),
iips: make([]iip, 0, conf.Capacity),
}
} | go | {
"resource": ""
} |
q19509 | AddGraph | train | func (n *Graph) AddGraph(name string) error {
return n.Add(name, NewDefaultGraph())
} | go | {
"resource": ""
} |
q19510 | AddNew | train | func (n *Graph) AddNew(processName string, componentName string, f *Factory) error {
proc, err := f.Create(componentName)
if err != nil {
return err
}
return n.Add(processName, proc)
} | go | {
"resource": ""
} |
q19511 | Remove | train | func (n *Graph) Remove(processName string) error {
if _, exists := n.procs[processName]; !exists {
return fmt.Errorf("Could not remove process: '%s' does not exist", processName)
}
delete(n.procs, processName)
return nil
} | go | {
"resource": ""
} |
q19512 | DefaultAccounting | train | func DefaultAccounting(symbol string, precision int) *Accounting {
ac := &Accounting{Symbol:symbol,Precision:precision}
ac.init()
ac.isInitialized = true
return ac
} | go | {
"resource": ""
} |
q19513 | NewAccounting | train | func NewAccounting(symbol string, precision int, thousand, decimal, format, formatNegative, formatZero string) *Accounting {
ac := &Accounting{
Symbol: symbol,
Precision: precision,
Thousand: thousand,
Decimal: decimal,
Format: format,
FormatNegative: formatNegative,
FormatZero: formatZero,
}
ac.isInitialized = true
return ac
} | go | {
"resource": ""
} |
q19514 | FormatMoneyInt | train | func (accounting *Accounting) FormatMoneyInt(value int) string {
if !accounting.isInitialized {
accounting.init()
}
formattedNumber := FormatNumberInt(value, accounting.Precision, accounting.Thousand, accounting.Decimal)
return accounting.formatMoneyString(formattedNumber)
} | go | {
"resource": ""
} |
q19515 | FormatMoneyDecimal | train | func (accounting *Accounting) FormatMoneyDecimal(value decimal.Decimal) string {
accounting.init()
formattedNumber := FormatNumberDecimal(value, accounting.Precision, accounting.Thousand, accounting.Decimal)
return accounting.formatMoneyString(formattedNumber)
} | go | {
"resource": ""
} |
q19516 | FormatNumberInt | train | func FormatNumberInt(x int, precision int, thousand string, decimalStr string) string {
var result string
var minus bool
if x < 0 {
if x * -1 < 0 {
return FormatNumber(x, precision, thousand, decimalStr)
}
minus = true
x *= -1
}
for x >= 1000 {
result = fmt.Sprintf("%s%03d%s", thousand, x%1000, result)
x /= 1000
}
result = fmt.Sprintf("%d%s", x, result)
if minus {
result = "-" + result
}
if precision > 0 {
result += decimalStr + strings.Repeat("0", precision)
}
return result
} | go | {
"resource": ""
} |
q19517 | FormatNumberFloat64 | train | func FormatNumberFloat64(x float64, precision int, thousand string, decimalStr string) string {
return formatNumberString(fmt.Sprintf(fmt.Sprintf("%%.%df", precision), x), precision, thousand, decimalStr)
} | go | {
"resource": ""
} |
q19518 | FormatNumberDecimal | train | func FormatNumberDecimal(x decimal.Decimal, precision int, thousand string, decimalStr string) string {
return formatNumberString(x.StringFixed(int32(precision)), precision, thousand, decimalStr)
} | go | {
"resource": ""
} |
q19519 | BaseCommand | train | func BaseCommand(serviceName, shortDescription string) *cobra.Command {
command := &cobra.Command{
Use: serviceName,
Short: shortDescription,
}
command.PersistentFlags().StringVar(&service.Config.Host, "grpc_host", "0.0.0.0", "gRPC service hostname")
command.PersistentFlags().IntVar(&service.Config.Port, "grpc_port", 8000, "gRPC port")
command.PersistentFlags().StringVar(&service.PrometheusConfig.Host, "prometheus_host", "0.0.0.0", "Prometheus metrics hostname")
command.PersistentFlags().IntVar(&service.PrometheusConfig.Port, "prometheus_port", 9000, "Prometheus metrics port")
return command
} | go | {
"resource": ""
} |
q19520 | ServeGRPC | train | func ServeGRPC() error {
var err error
service.ServiceListener, err = net.Listen("tcp", service.Config.Address())
if err != nil {
return err
}
logrus.Infof("Serving gRPC on %s", service.Config.Address())
return createGrpcServer().Serve(service.ServiceListener)
} | go | {
"resource": ""
} |
q19521 | Shutdown | train | func Shutdown() {
logrus.Infof("lile: Gracefully shutting down gRPC and Prometheus")
if service.Registry != nil {
service.Registry.DeRegister(service)
}
service.GRPCServer.GracefulStop()
// 30 seconds is the default grace period in Kubernetes
ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
defer cancel()
if err := service.PrometheusServer.Shutdown(ctx); err != nil {
logrus.Infof("Timeout during shutdown of metrics server. Error: %v", err)
}
} | go | {
"resource": ""
} |
q19522 | SnakeCaseName | train | func (p project) SnakeCaseName() string {
return strings.Replace(strcase.ToSnake(p.Name), "-", "_", -1)
} | go | {
"resource": ""
} |
q19523 | Address | train | func (c *ServerConfig) Address() string {
return fmt.Sprintf("%s:%d", c.Host, c.Port)
} | go | {
"resource": ""
} |
q19524 | NewService | train | func NewService(n string) *Service {
return &Service{
ID: generateID(n),
Name: n,
Config: ServerConfig{Host: "0.0.0.0", Port: 8000},
PrometheusConfig: ServerConfig{Host: "0.0.0.0", Port: 9000},
GRPCImplementation: func(s *grpc.Server) {},
UnaryInts: []grpc.UnaryServerInterceptor{
grpc_prometheus.UnaryServerInterceptor,
grpc_recovery.UnaryServerInterceptor(),
},
StreamInts: []grpc.StreamServerInterceptor{
grpc_prometheus.StreamServerInterceptor,
grpc_recovery.StreamServerInterceptor(),
},
}
} | go | {
"resource": ""
} |
q19525 | Name | train | func Name(n string) {
service.ID = generateID(n)
service.Name = n
AddUnaryInterceptor(otgrpc.OpenTracingServerInterceptor(
fromenv.Tracer(n)))
} | go | {
"resource": ""
} |
q19526 | AddUnaryInterceptor | train | func AddUnaryInterceptor(unint grpc.UnaryServerInterceptor) {
service.UnaryInts = append(service.UnaryInts, unint)
} | go | {
"resource": ""
} |
q19527 | AddStreamInterceptor | train | func AddStreamInterceptor(sint grpc.StreamServerInterceptor) {
service.StreamInts = append(service.StreamInts, sint)
} | go | {
"resource": ""
} |
q19528 | URLForService | train | func URLForService(name string) string {
host := name
port := "80"
if val, ok := os.LookupEnv("SERVICE_HOST_OVERRIDE"); ok {
host = val
}
if val, ok := os.LookupEnv("SERVICE_PORT_OVERRIDE"); ok {
port = val
}
if service.Registry != nil {
url, err := service.Registry.Get(name)
if err != nil {
fmt.Printf("lile: error contacting registry for service %s. err: %s \n", name, err.Error())
}
return url
}
return fmt.Sprintf("%s:%s", host, port)
} | go | {
"resource": ""
} |
q19529 | ContextClientInterceptor | train | func ContextClientInterceptor() grpc.UnaryClientInterceptor {
return func(
ctx context.Context,
method string,
req, resp interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
pairs := make([]string, 0)
if md, ok := metadata.FromIncomingContext(ctx); ok {
for key, values := range md {
if strings.HasPrefix(strings.ToLower(key), "l5d") {
for _, value := range values {
pairs = append(pairs, key, value)
}
}
if strings.HasPrefix(strings.ToLower(key), "x-") {
for _, value := range values {
pairs = append(pairs, key, value)
}
}
}
}
ctx = metadata.AppendToOutgoingContext(ctx, pairs...)
return invoker(ctx, method, req, resp, cc, opts...)
}
} | go | {
"resource": ""
} |
q19530 | MustGetwd | train | func MustGetwd() string {
wd, err := os.Getwd()
if err != nil {
log.Fatalf("unable to determine current working directory: %v", err)
}
return wd
} | go | {
"resource": ""
} |
q19531 | MergeEnv | train | func MergeEnv(env []string, args map[string]string) []string {
m := make(map[string]string)
for _, e := range env {
v := strings.SplitN(e, "=", 2)
m[v[0]] = v[1]
}
for k, v := range args {
m[k] = v
}
env = make([]string, 0, len(m))
for k, v := range m {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
return env
} | go | {
"resource": ""
} |
q19532 | ExecuteConcurrent | train | func ExecuteConcurrent(a *Action, n int, interrupt <-chan struct{}) error {
var mu sync.Mutex // protects seen
seen := make(map[*Action]chan error)
get := func(result chan error) error {
err := <-result
result <- err
return err
}
permits := make(chan bool, n)
for i := 0; i < cap(permits); i++ {
permits <- true
}
// wg tracks all the outstanding actions
var wg sync.WaitGroup
var execute func(map[*Action]chan error, *Action) chan error
execute = func(seen map[*Action]chan error, a *Action) chan error {
// step 0, have we seen this action before ?
mu.Lock()
if result, ok := seen[a]; ok {
// yes! return the result channel so others can wait
// on our action
mu.Unlock()
return result
}
// step 1, we're the first to run this action
result := make(chan error, 1)
seen[a] = result
mu.Unlock()
// queue all dependant actions.
var results []chan error
for _, dep := range a.Deps {
results = append(results, execute(seen, dep))
}
wg.Add(1)
go func() {
defer wg.Done()
// wait for dependant actions
for _, r := range results {
if err := get(r); err != nil {
result <- err
return
}
}
// wait for a permit and execute our action
select {
case <-permits:
result <- a.Run()
permits <- true
case <-interrupt:
result <- errors.New("interrupted")
return
}
}()
return result
}
err := get(execute(seen, a))
wg.Wait()
return err
} | go | {
"resource": ""
} |
q19533 | RunCommand | train | func RunCommand(fs *flag.FlagSet, cmd *Command, projectroot, goroot string, args []string) error {
if cmd.AddFlags != nil {
cmd.AddFlags(fs)
}
if err := fs.Parse(args); err != nil {
fs.Usage()
os.Exit(1)
}
args = fs.Args() // reset to the remaining arguments
ctx, err := NewContext(projectroot, gb.GcToolchain())
if err != nil {
return errors.Wrap(err, "unable to construct context")
}
defer ctx.Destroy()
ctx.Debug("args: %v", args)
return cmd.Run(ctx, args)
} | go | {
"resource": ""
} |
q19534 | NewContext | train | func NewContext(projectroot string, options ...func(*gb.Context) error) (*gb.Context, error) {
if projectroot == "" {
return nil, errors.New("project root is blank")
}
root, err := FindProjectroot(projectroot)
if err != nil {
return nil, errors.Wrap(err, "could not locate project root")
}
proj := gb.NewProject(root)
ctx, err := gb.NewContext(proj, options...)
if err != nil {
return nil, err
}
ctx.Debug("project root %q", proj.Projectdir())
return ctx, err
} | go | {
"resource": ""
} |
q19535 | Untar | train | func Untar(dest string, r io.Reader) error {
if exists(dest) {
return errors.Errorf("%q must not exist", dest)
}
parent, _ := filepath.Split(dest)
tmpdir, err := ioutil.TempDir(parent, ".untar")
if err != nil {
return err
}
if err := untar(tmpdir, r); err != nil {
os.RemoveAll(tmpdir)
return err
}
if err := os.Rename(tmpdir, dest); err != nil {
os.RemoveAll(tmpdir)
return err
}
return nil
} | go | {
"resource": ""
} |
q19536 | ImportPaths | train | func ImportPaths(srcdir, cwd string, args []string) []string {
args = importPathsNoDotExpansion(srcdir, cwd, args)
var out []string
for _, a := range args {
if strings.Contains(a, "...") {
pkgs, err := matchPackages(srcdir, a)
if err != nil {
fmt.Printf("could not load all packages: %v\n", err)
}
out = append(out, pkgs...)
continue
}
out = append(out, a)
}
return out
} | go | {
"resource": ""
} |
q19537 | matchPackages | train | func matchPackages(srcdir, pattern string) ([]string, error) {
match := matchPattern(pattern)
treeCanMatch := treeCanMatchPattern(pattern)
var pkgs []string
src := srcdir + string(filepath.Separator)
err := filepath.Walk(src, func(path string, fi os.FileInfo, err error) error {
if err != nil || !fi.IsDir() || path == src {
return nil
}
// Avoid .foo, _foo, and testdata directory trees.
if skipElem(fi.Name()) {
return filepath.SkipDir
}
name := filepath.ToSlash(path[len(src):])
if pattern == "std" && strings.Contains(name, ".") {
return filepath.SkipDir
}
if !treeCanMatch(name) {
return filepath.SkipDir
}
if match(name) {
pkgs = append(pkgs, name)
}
return nil
})
return pkgs, err
} | go | {
"resource": ""
} |
q19538 | BuildPackage | train | func BuildPackage(targets map[string]*Action, pkg *Package) (*Action, error) {
// if this action is already present in the map, return it
// rather than creating a new action.
if a, ok := targets[pkg.ImportPath]; ok {
return a, nil
}
// step 0. are we stale ?
// if this package is not stale, then by definition none of its
// dependencies are stale, so ignore this whole tree.
if pkg.NotStale {
return nil, nil
}
// step 1. build dependencies
deps, err := BuildDependencies(targets, pkg)
if err != nil {
return nil, err
}
// step 2. build this package
build, err := Compile(pkg, deps...)
if err != nil {
return nil, err
}
if build == nil {
panic("build action was nil") // shouldn't happen
}
// record the final action as the action that represents
// building this package.
targets[pkg.ImportPath] = build
return build, nil
} | go | {
"resource": ""
} |
q19539 | BuildDependencies | train | func BuildDependencies(targets map[string]*Action, pkg *Package) ([]*Action, error) {
var deps []*Action
pkgs := pkg.Imports
var extra []string
switch {
case pkg.Main:
// all binaries depend on runtime, even if they do not
// explicitly import it.
extra = append(extra, "runtime")
if pkg.race {
// race binaries have extra implicit depdendenceis.
extra = append(extra, "runtime/race")
}
case len(pkg.CgoFiles) > 0 && pkg.ImportPath != "runtime/cgo":
// anything that uses cgo has a dependency on runtime/cgo which is
// only visible after cgo file generation.
// TODO(dfc) what about pkg.Main && pkg.CgoFiles > 0 ??
extra = append(extra, "runtime/cgo")
}
if pkg.TestScope {
extra = append(extra, "regexp")
if version.Version > 1.7 {
// since Go 1.8 tests have additional implicit dependencies
extra = append(extra, "testing/internal/testdeps")
}
}
for _, i := range extra {
p, err := pkg.ResolvePackage(i)
if err != nil {
return nil, err
}
pkgs = append(pkgs, p)
}
for _, i := range pkgs {
a, err := BuildPackage(targets, i)
if err != nil {
return nil, err
}
if a == nil {
// no action required for this Package
continue
}
deps = append(deps, a)
}
return deps, nil
} | go | {
"resource": ""
} |
q19540 | GOOS | train | func GOOS(goos string) func(*Context) error {
return func(c *Context) error {
if goos == "" {
return fmt.Errorf("GOOS cannot be blank")
}
c.gotargetos = goos
return nil
}
} | go | {
"resource": ""
} |
q19541 | GOARCH | train | func GOARCH(goarch string) func(*Context) error {
return func(c *Context) error {
if goarch == "" {
return fmt.Errorf("GOARCH cannot be blank")
}
c.gotargetarch = goarch
return nil
}
} | go | {
"resource": ""
} |
q19542 | Tags | train | func Tags(tags ...string) func(*Context) error {
return func(c *Context) error {
c.buildtags = append(c.buildtags, tags...)
return nil
}
} | go | {
"resource": ""
} |
q19543 | Gcflags | train | func Gcflags(flags ...string) func(*Context) error {
return func(c *Context) error {
c.gcflags = append(c.gcflags, flags...)
return nil
}
} | go | {
"resource": ""
} |
q19544 | Ldflags | train | func Ldflags(flags ...string) func(*Context) error {
return func(c *Context) error {
c.ldflags = append(c.ldflags, flags...)
return nil
}
} | go | {
"resource": ""
} |
q19545 | WithRace | train | func WithRace(c *Context) error {
c.race = true
Tags("race")(c)
Gcflags("-race")(c)
Ldflags("-race")(c)
return nil
} | go | {
"resource": ""
} |
q19546 | NewContext | train | func NewContext(p Project, opts ...func(*Context) error) (*Context, error) {
envOr := func(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
defaults := []func(*Context) error{
// must come before GcToolchain()
func(c *Context) error {
c.gohostos = runtime.GOOS
c.gohostarch = runtime.GOARCH
c.gotargetos = envOr("GOOS", runtime.GOOS)
c.gotargetarch = envOr("GOARCH", runtime.GOARCH)
c.debug = func(string, ...interface{}) {} // null logger
return nil
},
GcToolchain(),
}
workdir, err := ioutil.TempDir("", "gb")
if err != nil {
return nil, err
}
ctx := Context{
Project: p,
workdir: workdir,
buildmode: "exe",
pkgs: make(map[string]*Package),
}
for _, opt := range append(defaults, opts...) {
err := opt(&ctx)
if err != nil {
return nil, err
}
}
// sort build tags to ensure the ctxSring and Suffix is stable
sort.Strings(ctx.buildtags)
bc := build.Default
bc.GOOS = ctx.gotargetos
bc.GOARCH = ctx.gotargetarch
bc.CgoEnabled = cgoEnabled(ctx.gohostos, ctx.gohostarch, ctx.gotargetos, ctx.gotargetarch)
bc.ReleaseTags = releaseTags
bc.BuildTags = ctx.buildtags
i, err := buildImporter(&bc, &ctx)
if err != nil {
return nil, err
}
ctx.importer = i
// C and unsafe are fake packages synthesised by the compiler.
// Insert fake packages into the package cache.
for _, name := range []string{"C", "unsafe"} {
pkg, err := ctx.newPackage(&build.Package{
Name: name,
ImportPath: name,
Dir: name, // fake, but helps diagnostics
Goroot: true,
})
if err != nil {
return nil, err
}
pkg.NotStale = true
ctx.pkgs[pkg.ImportPath] = pkg
}
return &ctx, err
} | go | {
"resource": ""
} |
q19547 | NewPackage | train | func (c *Context) NewPackage(p *build.Package) (*Package, error) {
pkg, err := c.newPackage(p)
if err != nil {
return nil, err
}
pkg.NotStale = !pkg.isStale()
return pkg, nil
} | go | {
"resource": ""
} |
q19548 | Pkgdir | train | func (c *Context) Pkgdir() string {
return filepath.Join(c.Project.Pkgdir(), c.ctxString())
} | go | {
"resource": ""
} |
q19549 | ResolvePackage | train | func (c *Context) ResolvePackage(path string) (*Package, error) {
if path == "." {
return nil, errors.Errorf("%q is not a package", filepath.Join(c.Projectdir(), "src"))
}
path, err := relImportPath(filepath.Join(c.Projectdir(), "src"), path)
if err != nil {
return nil, err
}
if path == "." || path == ".." || strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../") {
return nil, errors.Errorf("import %q: relative import not supported", path)
}
return c.loadPackage(nil, path)
} | go | {
"resource": ""
} |
q19550 | loadPackage | train | func (c *Context) loadPackage(stack []string, path string) (*Package, error) {
if pkg, ok := c.pkgs[path]; ok {
// already loaded, just return
return pkg, nil
}
p, err := c.importer.Import(path)
if err != nil {
return nil, err
}
stack = append(stack, p.ImportPath)
var stale bool
for i, im := range p.Imports {
for _, p := range stack {
if p == im {
return nil, fmt.Errorf("import cycle detected: %s", strings.Join(append(stack, im), " -> "))
}
}
pkg, err := c.loadPackage(stack, im)
if err != nil {
return nil, err
}
// update the import path as the import may have been discovered via vendoring.
p.Imports[i] = pkg.ImportPath
stale = stale || !pkg.NotStale
}
pkg, err := c.newPackage(p)
if err != nil {
return nil, errors.Wrapf(err, "loadPackage(%q)", path)
}
pkg.Main = pkg.Name == "main"
pkg.NotStale = !(stale || pkg.isStale())
c.pkgs[p.ImportPath] = pkg
return pkg, nil
} | go | {
"resource": ""
} |
q19551 | Destroy | train | func (c *Context) Destroy() error {
c.debug("removing work directory: %v", c.workdir)
return os.RemoveAll(c.workdir)
} | go | {
"resource": ""
} |
q19552 | ctxString | train | func (c *Context) ctxString() string {
v := []string{
c.gotargetos,
c.gotargetarch,
}
v = append(v, c.buildtags...)
return strings.Join(v, "-")
} | go | {
"resource": ""
} |
q19553 | processSignals | train | func processSignals() {
sig := make(chan os.Signal)
signal.Notify(sig, signalsToIgnore...)
go func() {
<-sig
close(interrupted)
}()
} | go | {
"resource": ""
} |
q19554 | Copypath | train | func Copypath(dst string, src string) error {
err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasPrefix(filepath.Base(path), ".") {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
if info.IsDir() {
return nil
}
if info.Mode()&os.ModeSymlink != 0 {
if debugCopypath {
fmt.Printf("skipping symlink: %v\n", path)
}
return nil
}
dst := filepath.Join(dst, path[len(src):])
return Copyfile(dst, path)
})
if err != nil {
// if there was an error during copying, remove the partial copy.
RemoveAll(dst)
}
return err
} | go | {
"resource": ""
} |
q19555 | Copyfile | train | func Copyfile(dst, src string) error {
err := mkdir(filepath.Dir(dst))
if err != nil {
return errors.Wrap(err, "copyfile: mkdirall")
}
r, err := os.Open(src)
if err != nil {
return errors.Wrapf(err, "copyfile: open(%q)", src)
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return errors.Wrapf(err, "copyfile: create(%q)", dst)
}
defer w.Close()
if debugCopyfile {
fmt.Printf("copyfile(dst: %v, src: %v)\n", dst, src)
}
_, err = io.Copy(w, r)
return err
} | go | {
"resource": ""
} |
q19556 | rungcc1 | train | func rungcc1(pkg *Package, cgoCFLAGS []string, ofile, cfile string) error {
args := []string{"-g", "-O2",
"-I", pkg.Dir,
"-I", filepath.Dir(ofile),
}
args = append(args, cgoCFLAGS...)
args = append(args,
"-o", ofile,
"-c", cfile,
)
t0 := time.Now()
gcc := gccCmd(pkg, pkg.Dir)
var buf bytes.Buffer
err := runOut(&buf, pkg.Dir, nil, gcc[0], append(gcc[1:], args...)...)
if err != nil {
fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
io.Copy(os.Stderr, &buf)
}
pkg.Record(gcc[0], time.Since(t0))
return err
} | go | {
"resource": ""
} |
q19557 | gccld | train | func gccld(pkg *Package, cgoCFLAGS, cgoLDFLAGS []string, ofile string, ofiles []string) error {
args := []string{}
args = append(args, "-o", ofile)
args = append(args, ofiles...)
args = append(args, cgoLDFLAGS...) // this has to go at the end, because reasons!
t0 := time.Now()
var cmd []string
if len(pkg.CXXFiles) > 0 || len(pkg.SwigCXXFiles) > 0 {
cmd = gxxCmd(pkg, pkg.Dir)
} else {
cmd = gccCmd(pkg, pkg.Dir)
}
var buf bytes.Buffer
err := runOut(&buf, pkg.Dir, nil, cmd[0], append(cmd[1:], args...)...)
if err != nil {
fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
io.Copy(os.Stderr, &buf)
}
pkg.Record("gccld", time.Since(t0))
return err
} | go | {
"resource": ""
} |
q19558 | rungcc3 | train | func rungcc3(pkg *Package, dir string, ofile string, ofiles []string) error {
args := []string{}
args = append(args, "-o", ofile)
args = append(args, ofiles...)
args = append(args, "-Wl,-r", "-nostdlib")
if gccSupportsNoPie(pkg) {
args = append(args, "-no-pie")
}
var cmd []string
if len(pkg.CXXFiles) > 0 || len(pkg.SwigCXXFiles) > 0 {
cmd = gxxCmd(pkg, dir)
} else {
cmd = gccCmd(pkg, dir)
}
if !strings.HasPrefix(cmd[0], "clang") {
libgcc, err := libgcc(pkg.Context)
if err != nil {
return nil
}
args = append(args, libgcc)
}
t0 := time.Now()
var buf bytes.Buffer
err := runOut(&buf, dir, nil, cmd[0], append(cmd[1:], args...)...)
if err != nil {
fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
io.Copy(os.Stderr, &buf)
}
pkg.Record("gcc3", time.Since(t0))
return err
} | go | {
"resource": ""
} |
q19559 | libgcc | train | func libgcc(ctx *Context) (string, error) {
args := []string{
"-print-libgcc-file-name",
}
var buf bytes.Buffer
cmd := gccCmd(&Package{Context: ctx}, "") // TODO(dfc) hack
err := runOut(&buf, ".", nil, cmd[0], args...)
return strings.TrimSpace(buf.String()), err
} | go | {
"resource": ""
} |
q19560 | envList | train | func envList(key, def string) []string {
v := os.Getenv(key)
if v == "" {
v = def
}
return strings.Fields(v)
} | go | {
"resource": ""
} |
q19561 | cflags | train | func cflags(p *Package, def bool) (cppflags, cflags, cxxflags, ldflags []string) {
var defaults string
if def {
defaults = "-g -O2"
}
cppflags = stringList(envList("CGO_CPPFLAGS", ""), p.CgoCPPFLAGS)
cflags = stringList(envList("CGO_CFLAGS", defaults), p.CgoCFLAGS)
cxxflags = stringList(envList("CGO_CXXFLAGS", defaults), p.CgoCXXFLAGS)
ldflags = stringList(envList("CGO_LDFLAGS", defaults), p.CgoLDFLAGS)
return
} | go | {
"resource": ""
} |
q19562 | pkgconfig | train | func pkgconfig(p *Package) ([]string, []string, error) {
if len(p.CgoPkgConfig) == 0 {
return nil, nil, nil // nothing to do
}
args := []string{
"--cflags",
}
args = append(args, p.CgoPkgConfig...)
var out bytes.Buffer
err := runOut(&out, p.Dir, nil, "pkg-config", args...)
if err != nil {
return nil, nil, err
}
cflags := strings.Fields(out.String())
args = []string{
"--libs",
}
args = append(args, p.CgoPkgConfig...)
out.Reset()
err = runOut(&out, p.Dir, nil, "pkg-config", args...)
if err != nil {
return nil, nil, err
}
ldflags := strings.Fields(out.String())
return cflags, ldflags, nil
} | go | {
"resource": ""
} |
q19563 | runcgo1 | train | func runcgo1(pkg *Package, cflags, ldflags []string) error {
cgo := cgotool(pkg.Context)
workdir := cgoworkdir(pkg)
if err := mkdir(workdir); err != nil {
return err
}
args := []string{"-objdir", workdir}
switch {
case version.Version > 1.5:
args = append(args,
"-importpath", pkg.ImportPath,
"--",
"-I", workdir,
"-I", pkg.Dir,
)
default:
return errors.Errorf("unsupported Go version: %v", runtime.Version())
}
args = append(args, cflags...)
args = append(args, pkg.CgoFiles...)
cgoenv := []string{
"CGO_CFLAGS=" + strings.Join(quoteFlags(cflags), " "),
"CGO_LDFLAGS=" + strings.Join(quoteFlags(ldflags), " "),
}
var buf bytes.Buffer
err := runOut(&buf, pkg.Dir, cgoenv, cgo, args...)
if err != nil {
fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
io.Copy(os.Stderr, &buf)
}
return err
} | go | {
"resource": ""
} |
q19564 | runcgo2 | train | func runcgo2(pkg *Package, dynout, ofile string) error {
cgo := cgotool(pkg.Context)
workdir := cgoworkdir(pkg)
args := []string{
"-objdir", workdir,
}
switch {
case version.Version > 1.5:
args = append(args,
"-dynpackage", pkg.Name,
"-dynimport", ofile,
"-dynout", dynout,
)
default:
return errors.Errorf("unsuppored Go version: %v", runtime.Version())
}
var buf bytes.Buffer
err := runOut(&buf, pkg.Dir, nil, cgo, args...)
if err != nil {
fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
io.Copy(os.Stderr, &buf)
}
return err
} | go | {
"resource": ""
} |
q19565 | cgoworkdir | train | func cgoworkdir(pkg *Package) string {
return filepath.Join(pkg.Workdir(), pkg.pkgname(), "_cgo")
} | go | {
"resource": ""
} |
q19566 | gccCmd | train | func gccCmd(pkg *Package, objdir string) []string {
return ccompilerCmd(pkg, "CC", defaultCC, objdir)
} | go | {
"resource": ""
} |
q19567 | gxxCmd | train | func gxxCmd(pkg *Package, objdir string) []string {
return ccompilerCmd(pkg, "CXX", defaultCXX, objdir)
} | go | {
"resource": ""
} |
q19568 | ccompilerCmd | train | func ccompilerCmd(pkg *Package, envvar, defcmd, objdir string) []string {
compiler := envList(envvar, defcmd)
a := []string{compiler[0]}
if objdir != "" {
a = append(a, "-I", objdir)
}
a = append(a, compiler[1:]...)
// Definitely want -fPIC but on Windows gcc complains
// "-fPIC ignored for target (all code is position independent)"
if pkg.gotargetos != "windows" {
a = append(a, "-fPIC")
}
a = append(a, gccArchArgs(pkg.gotargetarch)...)
// gcc-4.5 and beyond require explicit "-pthread" flag
// for multithreading with pthread library.
switch pkg.gotargetos {
case "windows":
a = append(a, "-mthreads")
default:
a = append(a, "-pthread")
}
if strings.Contains(a[0], "clang") {
// disable ASCII art in clang errors, if possible
a = append(a, "-fno-caret-diagnostics")
// clang is too smart about command-line arguments
a = append(a, "-Qunused-arguments")
}
// disable word wrapping in error messages
a = append(a, "-fmessage-length=0")
// On OS X, some of the compilers behave as if -fno-common
// is always set, and the Mach-O linker in 6l/8l assumes this.
// See https://golang.org/issue/3253.
if pkg.gotargetos == "darwin" {
a = append(a, "-fno-common")
}
return a
} | go | {
"resource": ""
} |
q19569 | linkCmd | train | func linkCmd(pkg *Package, envvar, defcmd string) string {
compiler := envList(envvar, defcmd)
return compiler[0]
} | go | {
"resource": ""
} |
q19570 | stripext | train | func stripext(path string) string {
return path[:len(path)-len(filepath.Ext(path))]
} | go | {
"resource": ""
} |
q19571 | addDepfileDeps | train | func addDepfileDeps(bc *build.Context, ctx *Context) (Importer, error) {
i := Importer(new(nullImporter))
df, err := readDepfile(ctx)
if err != nil {
if !os.IsNotExist(errors.Cause(err)) {
return nil, errors.Wrap(err, "could not parse depfile")
}
ctx.debug("no depfile, nothing to do.")
return i, nil
}
re := regexp.MustCompile(semverRegex)
for prefix, kv := range df {
if version, ok := kv["version"]; ok {
if !re.MatchString(version) {
return nil, errors.Errorf("%s: %q is not a valid SemVer 2.0.0 version", prefix, version)
}
root := filepath.Join(cachePath(), hash(prefix, version))
dest := filepath.Join(root, "src", filepath.FromSlash(prefix))
fi, err := os.Stat(dest)
if err == nil {
if !fi.IsDir() {
return nil, errors.Errorf("%s is not a directory", dest)
}
}
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := fetchVersion(root, dest, prefix, version); err != nil {
return nil, err
}
}
i = &_importer{
Importer: i,
im: importer{
Context: bc,
Root: root,
},
}
ctx.debug("add importer for %q: %v", prefix+" "+version, root)
}
if tag, ok := kv["tag"]; ok {
root := filepath.Join(cachePath(), hash(prefix, tag))
dest := filepath.Join(root, "src", filepath.FromSlash(prefix))
fi, err := os.Stat(dest)
if err == nil {
if !fi.IsDir() {
return nil, errors.Errorf("%s is not a directory", dest)
}
}
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := fetchTag(root, dest, prefix, tag); err != nil {
return nil, err
}
}
i = &_importer{
Importer: i,
im: importer{
Context: bc,
Root: root,
},
}
ctx.debug("add importer for %q: %v", prefix+" "+tag, root)
}
}
return i, nil
} | go | {
"resource": ""
} |
q19572 | newPackage | train | func (ctx *Context) newPackage(p *build.Package) (*Package, error) {
pkg := &Package{
Context: ctx,
Package: p,
}
for _, i := range p.Imports {
dep, ok := ctx.pkgs[i]
if !ok {
return nil, errors.Errorf("newPackage(%q): could not locate dependant package %q ", p.Name, i)
}
pkg.Imports = append(pkg.Imports, dep)
}
return pkg, nil
} | go | {
"resource": ""
} |
q19573 | complete | train | func (p *Package) complete() bool {
// If we're giving the compiler the entire package (no C etc files), tell it that,
// so that it can give good error messages about forward declarations.
// Exceptions: a few standard packages have forward declarations for
// pieces supplied behind-the-scenes by package runtime.
extFiles := len(p.CgoFiles) + len(p.CFiles) + len(p.CXXFiles) + len(p.MFiles) + len(p.SFiles) + len(p.SysoFiles) + len(p.SwigFiles) + len(p.SwigCXXFiles)
if p.Goroot {
switch p.ImportPath {
case "bytes", "internal/poll", "net", "os", "runtime/pprof", "sync", "syscall", "time":
extFiles++
}
}
return extFiles == 0
} | go | {
"resource": ""
} |
q19574 | Binfile | train | func (pkg *Package) Binfile() string {
target := filepath.Join(pkg.bindir(), pkg.binname())
// if this is a cross compile or GOOS/GOARCH are both defined or there are build tags, add ctxString.
if pkg.isCrossCompile() || (os.Getenv("GOOS") != "" && os.Getenv("GOARCH") != "") {
target += "-" + pkg.ctxString()
} else if len(pkg.buildtags) > 0 {
target += "-" + strings.Join(pkg.buildtags, "-")
}
if pkg.gotargetos == "windows" {
target += ".exe"
}
return target
} | go | {
"resource": ""
} |
q19575 | objfile | train | func (pkg *Package) objfile() string {
return filepath.Join(pkg.Workdir(), pkg.objname())
} | go | {
"resource": ""
} |
q19576 | pkgpath | train | func (pkg *Package) pkgpath() string {
importpath := filepath.FromSlash(pkg.ImportPath) + ".a"
switch {
case pkg.isCrossCompile():
return filepath.Join(pkg.Pkgdir(), importpath)
case pkg.Goroot && pkg.race:
// race enabled standard lib
return filepath.Join(runtime.GOROOT(), "pkg", pkg.gotargetos+"_"+pkg.gotargetarch+"_race", importpath)
case pkg.Goroot:
// standard lib
return filepath.Join(runtime.GOROOT(), "pkg", pkg.gotargetos+"_"+pkg.gotargetarch, importpath)
default:
return filepath.Join(pkg.Pkgdir(), importpath)
}
} | go | {
"resource": ""
} |
q19577 | isStale | train | func (pkg *Package) isStale() bool {
switch pkg.ImportPath {
case "C", "unsafe":
// synthetic packages are never stale
return false
}
if !pkg.Goroot && pkg.Force {
return true
}
// tests are always stale, they are never installed
if pkg.TestScope {
return true
}
// Package is stale if completely unbuilt.
var built time.Time
if fi, err := os.Stat(pkg.pkgpath()); err == nil {
built = fi.ModTime()
}
if built.IsZero() {
pkg.debug("%s is missing", pkg.pkgpath())
return true
}
olderThan := func(file string) bool {
fi, err := os.Stat(file)
return err != nil || fi.ModTime().After(built)
}
newerThan := func(file string) bool {
fi, err := os.Stat(file)
return err != nil || fi.ModTime().Before(built)
}
// As a courtesy to developers installing new versions of the compiler
// frequently, define that packages are stale if they are
// older than the compiler, and commands if they are older than
// the linker. This heuristic will not work if the binaries are
// back-dated, as some binary distributions may do, but it does handle
// a very common case.
if !pkg.Goroot {
if olderThan(pkg.tc.compiler()) {
pkg.debug("%s is older than %s", pkg.pkgpath(), pkg.tc.compiler())
return true
}
if pkg.Main && olderThan(pkg.tc.linker()) {
pkg.debug("%s is older than %s", pkg.pkgpath(), pkg.tc.compiler())
return true
}
}
if pkg.Goroot && !pkg.isCrossCompile() {
// if this is a standard lib package, and we are not cross compiling
// then assume the package is up to date. This also works around
// golang/go#13769.
return false
}
// Package is stale if a dependency is newer.
for _, p := range pkg.Imports {
if p.ImportPath == "C" || p.ImportPath == "unsafe" {
continue // ignore stale imports of synthetic packages
}
if olderThan(p.pkgpath()) {
pkg.debug("%s is older than %s", pkg.pkgpath(), p.pkgpath())
return true
}
}
// if the main package is up to date but _newer_ than the binary (which
// could have been removed), then consider it stale.
if pkg.Main && newerThan(pkg.Binfile()) {
pkg.debug("%s is newer than %s", pkg.pkgpath(), pkg.Binfile())
return true
}
srcs := stringList(pkg.GoFiles, pkg.CFiles, pkg.CXXFiles, pkg.MFiles, pkg.HFiles, pkg.SFiles, pkg.CgoFiles, pkg.SysoFiles, pkg.SwigFiles, pkg.SwigCXXFiles)
for _, src := range srcs {
if olderThan(filepath.Join(pkg.Dir, src)) {
pkg.debug("%s is older than %s", pkg.pkgpath(), filepath.Join(pkg.Dir, src))
return true
}
}
return false
} | go | {
"resource": ""
} |
q19578 | difference | train | func difference(a, b map[string]bool) map[string]bool {
r := make(map[string]bool)
for k := range a {
if !b[k] {
r[k] = true
}
}
for k := range b {
if !a[k] {
r[k] = true
}
}
return r
} | go | {
"resource": ""
} |
q19579 | ParseFile | train | func ParseFile(path string) (map[string]map[string]string, error) {
r, err := os.Open(path)
if err != nil {
return nil, errors.Wrapf(err, "ParseFile")
}
defer r.Close()
return Parse(r)
} | go | {
"resource": ""
} |
q19580 | checkStackTracer | train | func checkStackTracer(req *http.Request, err error) error {
if nf, ok := err.(stackTracer); ok {
if nf.customFn != nil {
pc := make([]uintptr, 128)
npc := runtime.Callers(2, pc)
pc = pc[:npc]
var mesg bytes.Buffer
var netHTTPBegin, netHTTPEnd bool
// Start recording at first net/http call if any...
for {
frames := runtime.CallersFrames(pc)
var lastFn string
for {
frame, more := frames.Next()
if !netHTTPEnd {
if netHTTPBegin {
netHTTPEnd = !strings.HasPrefix(frame.Function, "net/http.")
} else {
netHTTPBegin = strings.HasPrefix(frame.Function, "net/http.")
}
}
if netHTTPEnd {
if lastFn != "" {
if mesg.Len() == 0 {
if nf.err != nil {
mesg.WriteString(nf.err.Error())
} else {
fmt.Fprintf(&mesg, "%s %s", req.Method, req.URL)
}
mesg.WriteString("\nCalled from ")
} else {
mesg.WriteString("\n ")
}
fmt.Fprintf(&mesg, "%s()\n at %s:%d", lastFn, frame.File, frame.Line)
}
}
lastFn = frame.Function
if !more {
break
}
}
// At least one net/http frame found
if mesg.Len() > 0 {
break
}
netHTTPEnd = true // retry without looking at net/http frames
}
nf.customFn(mesg.String())
}
err = nf.err
}
return err
} | go | {
"resource": ""
} |
q19581 | responderForKey | train | func (m *MockTransport) responderForKey(key routeKey) (Responder, routeKey, []string) {
m.mu.RLock()
defer m.mu.RUnlock()
return m.responders[key], key, nil
} | go | {
"resource": ""
} |
q19582 | regexpResponderForKey | train | func (m *MockTransport) regexpResponderForKey(key routeKey) (Responder, routeKey, []string) {
m.mu.RLock()
defer m.mu.RUnlock()
for _, regInfo := range m.regexpResponders {
if regInfo.method == key.Method {
if sm := regInfo.rx.FindStringSubmatch(key.URL); sm != nil {
if len(sm) == 1 {
sm = nil
} else {
sm = sm[1:]
}
return regInfo.responder, routeKey{
Method: key.Method,
URL: regInfo.origRx,
}, sm
}
}
}
return nil, key, nil
} | go | {
"resource": ""
} |
q19583 | RegisterNoResponder | train | func (m *MockTransport) RegisterNoResponder(responder Responder) {
m.mu.Lock()
m.noResponder = responder
m.mu.Unlock()
} | go | {
"resource": ""
} |
q19584 | GetTotalCallCount | train | func (m *MockTransport) GetTotalCallCount() int {
m.mu.RLock()
count := m.totalCallCount
m.mu.RUnlock()
return count
} | go | {
"resource": ""
} |
q19585 | Times | train | func (r Responder) Times(n int, fn ...func(...interface{})) Responder {
return r.times("Times", n, fn...)
} | go | {
"resource": ""
} |
q19586 | Encode | train | func (h *HashID) Encode(numbers []int) (string, error) {
numbers64 := make([]int64, 0, len(numbers))
for _, id := range numbers {
numbers64 = append(numbers64, int64(id))
}
return h.EncodeInt64(numbers64)
} | go | {
"resource": ""
} |
q19587 | DecodeWithError | train | func (h *HashID) DecodeWithError(hash string) ([]int, error) {
result64, err := h.DecodeInt64WithError(hash)
if err != nil {
return nil, err
}
result := make([]int, 0, len(result64))
for _, id := range result64 {
result = append(result, int(id))
}
return result, nil
} | go | {
"resource": ""
} |
q19588 | DecodeInt64WithError | train | func (h *HashID) DecodeInt64WithError(hash string) ([]int64, error) {
hashes := splitRunes([]rune(hash), h.guards)
hashIndex := 0
if len(hashes) == 2 || len(hashes) == 3 {
hashIndex = 1
}
result := make([]int64, 0, 10)
hashBreakdown := hashes[hashIndex]
if len(hashBreakdown) > 0 {
lottery := hashBreakdown[0]
hashBreakdown = hashBreakdown[1:]
hashes = splitRunes(hashBreakdown, h.seps)
alphabet := duplicateRuneSlice(h.alphabet)
buffer := make([]rune, len(alphabet)+len(h.salt)+1)
for _, subHash := range hashes {
buffer = buffer[:1]
buffer[0] = lottery
buffer = append(buffer, h.salt...)
buffer = append(buffer, alphabet...)
consistentShuffleInPlace(alphabet, buffer[:len(alphabet)])
number, err := unhash(subHash, alphabet)
if err != nil {
return nil, err
}
result = append(result, number)
}
}
sanityCheck, _ := h.EncodeInt64(result)
if sanityCheck != hash {
return result, fmt.Errorf("mismatch between encode and decode: %s start %s"+
" re-encoded. result: %v", hash, sanityCheck, result)
}
return result, nil
} | go | {
"resource": ""
} |
q19589 | UnmarshalJSON | train | func (cs *CharsetID) UnmarshalJSON(p []byte) error {
if len(p) == 0 {
return nil
}
if p[0] != '"' {
var u uint16
if err := json.Unmarshal(p, &u); err != nil {
return err
}
*cs = CharsetID(u)
return nil
}
var s string
if err := json.Unmarshal(p, &s); err != nil {
return err
}
u, err := strconv.ParseUint(s, 16, 16)
if err != nil {
return err
}
*cs = CharsetID(u)
return nil
} | go | {
"resource": ""
} |
q19590 | UnmarshalJSON | train | func (lng *LangID) UnmarshalJSON(p []byte) error {
if len(p) == 0 {
return nil
}
if p[0] != '"' {
var u uint16
if err := json.Unmarshal(p, &u); err != nil {
return err
}
*lng = LangID(u)
return nil
}
var s string
if err := json.Unmarshal(p, &s); err != nil {
return err
}
u, err := strconv.ParseUint(s, 16, 16)
if err != nil {
return err
}
*lng = LangID(u)
return nil
} | go | {
"resource": ""
} |
q19591 | Build | train | func (v *VersionInfo) Build() {
vi := VSVersionInfo{}
// 0 for binary, 1 for text
vi.WType = 0x00
vi.SzKey = padString("VS_VERSION_INFO", 0)
// Align to 32-bit boundary
// 6 is for the size of WLength, WValueLength, and WType (each is 1 word or 2 bytes: FF FF)
soFar := 2
for (len(vi.SzKey)+6+soFar)%4 != 0 {
soFar += 2
}
vi.Padding1 = padBytes(soFar)
soFar += len(vi.SzKey)
vi.Value = buildFixedFileInfo(v)
// Length of VSFixedFileInfo (always the same)
vi.WValueLength = 0x34
// Never needs padding, not included in WLength
vi.Padding2 = []byte{}
// Build strings
vi.Children = buildStringFileInfo(v)
// Build translation
vi.Children2 = buildVarFileInfo(v.VarFileInfo)
// Calculate the total size
vi.WLength += 6 + uint16(soFar) + vi.WValueLength + vi.Children.WLength + vi.Children2.WLength
v.Structure = vi
} | go | {
"resource": ""
} |
q19592 | GetVersionString | train | func (f FileVersion) GetVersionString() string {
return fmt.Sprintf("%d.%d.%d.%d", f.Major, f.Minor, f.Patch, f.Build)
} | go | {
"resource": ""
} |
q19593 | WriteSyso | train | func (vi *VersionInfo) WriteSyso(filename string, arch string) error {
// Channel for generating IDs
newID := make(chan uint16)
go func() {
for i := uint16(1); ; i++ {
newID <- i
}
}()
// Create a new RSRC section
coff := coff.NewRSRC()
// Set the architechture
err := coff.Arch(arch)
if err != nil {
return err
}
// ID 16 is for Version Information
coff.AddResource(16, 1, SizedReader{bytes.NewBuffer(vi.Buffer.Bytes())})
// If manifest is enabled
if vi.ManifestPath != "" {
manifest, err := binutil.SizedOpen(vi.ManifestPath)
if err != nil {
return err
}
defer manifest.Close()
id := <-newID
coff.AddResource(rtManifest, id, manifest)
}
// If icon is enabled
if vi.IconPath != "" {
if err := addIcon(coff, vi.IconPath, newID); err != nil {
return err
}
}
coff.Freeze()
// Write to file
return writeCoff(coff, filename)
} | go | {
"resource": ""
} |
q19594 | WriteHex | train | func (vi *VersionInfo) WriteHex(filename string) error {
return ioutil.WriteFile(filename, vi.Buffer.Bytes(), 0655)
} | go | {
"resource": ""
} |
q19595 | New | train | func New(schema *graphql.Schema) (*State, error) {
if schema == nil {
return nil, ErrNilSchema
}
s := &State{
schema: schema,
}
return s, nil
} | go | {
"resource": ""
} |
q19596 | Handler | train | func (s *State) Handler(ctx *gramework.Context) {
if s.schema == nil {
ctx.Logger.Error("schema is nil")
ctx.Err500()
return
}
// ok, we have the schema. try to decode request
req, err := ctx.DecodeGQL()
if err != nil {
ctx.Logger.Warn("gql request decoding failed")
ctx.Error("Invalid request", 400)
return
}
if s.NoIntrospection && strings.HasPrefix(strings.TrimSpace(req.Query), "query IntrospectionQuery") {
ctx.Forbidden()
return
}
// check if we got invalid content type
if req == nil {
ctx.Logger.Error("GQL request is nil: invalid content type")
ctx.Error("Invalid content type", 400)
return
}
ctx.Logger.Info("processing request")
if _, err := ctx.Encode(s.schema.Exec(ctx.ToContext(), req.Query, req.OperationName, req.Variables)); err != nil {
ctx.SetStatusCode(415)
}
ctx.Logger.Info("processing request done")
} | go | {
"resource": ""
} |
q19597 | Serve | train | func (app *App) Serve(ln net.Listener) error {
var err error
srv := app.copyServer()
app.runningServersMu.Lock()
app.runningServers = append(app.runningServers, runningServerInfo{
bind: ln.Addr().String(),
srv: srv,
})
app.runningServersMu.Unlock()
if err = srv.Serve(ln); err != nil {
app.internalLog.Errorf("ListenAndServe failed: %s", err)
}
return err
} | go | {
"resource": ""
} |
q19598 | GetTypeByString | train | func GetTypeByString(typeName string) (ServiceType, error) {
switch ServiceType(typeName) {
case HTTP:
return HTTP, nil
case HTTPS:
return HTTPS, nil
case TCP:
return TCP, nil
case UDP:
return UDP, nil
case Custom:
return Custom, nil
default:
return ServiceType(typeName), ErrServiceTypeNotFound
}
} | go | {
"resource": ""
} |
q19599 | SPAIndex | train | func (r *Router) SPAIndex(pathOrHandler interface{}) *Router {
switch v := pathOrHandler.(type) {
case string:
r.NotFound(func(ctx *Context) {
ctx.HTML()
ctx.SendFile(v)
})
default:
r.NotFound(r.determineHandler(v))
}
return r
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.