_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q8900 | New | train | func New(src, packageName string) (*Mocker, error) {
srcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax)
if err != nil {
return nil, fmt.Errorf("Couldn't load source package: %s", err)
}
pkgPath := srcPkg.PkgPath
if len(packageName) == 0 {
packageName = srcPkg.Name
} else {
mockPkgPath := filepath.Join(src, packageName)
if _, err := os.Stat(mockPkgPath); os.IsNotExist(err) {
os.Mkdir(mockPkgPath, os.ModePerm)
}
mockPkg, err := pkgInfoFromPath(mockPkgPath, packages.LoadFiles)
if err != nil {
return nil, fmt.Errorf("Couldn't load mock package: %s", err)
}
pkgPath = mockPkg.PkgPath
}
tmpl, err := template.New("moq").Funcs(templateFuncs).Parse(moqTemplate)
if err != nil {
return nil, err
}
return &Mocker{
tmpl: tmpl,
srcPkg: srcPkg,
pkgName: packageName,
pkgPath: pkgPath,
imports: make(map[string]bool),
}, nil
} | go | {
"resource": ""
} |
q8901 | Mock | train | func (m *Mocker) Mock(w io.Writer, name ...string) error {
if len(name) == 0 {
return errors.New("must specify one interface")
}
doc := doc{
PackageName: m.pkgName,
Imports: moqImports,
}
mocksMethods := false
tpkg := m.srcPkg.Types
for _, n := range name {
iface := tpkg.Scope().Lookup(n)
if iface == nil {
return fmt.Errorf("cannot find interface %s", n)
}
if !types.IsInterface(iface.Type()) {
return fmt.Errorf("%s (%s) not an interface", n, iface.Type().String())
}
iiface := iface.Type().Underlying().(*types.Interface).Complete()
obj := obj{
InterfaceName: n,
}
for i := 0; i < iiface.NumMethods(); i++ {
mocksMethods = true
meth := iiface.Method(i)
sig := meth.Type().(*types.Signature)
method := &method{
Name: meth.Name(),
}
obj.Methods = append(obj.Methods, method)
method.Params = m.extractArgs(sig, sig.Params(), "in%d")
method.Returns = m.extractArgs(sig, sig.Results(), "out%d")
}
doc.Objects = append(doc.Objects, obj)
}
if mocksMethods {
doc.Imports = append(doc.Imports, "sync")
}
for pkgToImport := range m.imports {
doc.Imports = append(doc.Imports, stripVendorPath(pkgToImport))
}
if tpkg.Name() != m.pkgName {
doc.SourcePackagePrefix = tpkg.Name() + "."
doc.Imports = append(doc.Imports, tpkg.Path())
}
var buf bytes.Buffer
err := m.tmpl.Execute(&buf, doc)
if err != nil {
return err
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
return fmt.Errorf("go/format: %s", err)
}
if _, err := w.Write(formatted); err != nil {
return err
}
return nil
} | go | {
"resource": ""
} |
q8902 | Stop | train | func (s *Supervisor) Stop() {
s.Lock()
if s.state == notRunning {
s.state = terminated
s.Unlock()
return
}
s.state = terminated
s.Unlock()
done := make(chan struct{})
if s.sendControl(stopSupervisor{done}) {
<-done
}
} | go | {
"resource": ""
} |
q8903 | NewClient | train | func NewClient(config *Config) (*Client, error) {
if len(config.Contexts) == 0 {
if config.CurrentContext != "" {
return nil, fmt.Errorf("no contexts with name %q", config.CurrentContext)
}
if n := len(config.Clusters); n == 0 {
return nil, errors.New("no clusters provided")
} else if n > 1 {
return nil, errors.New("multiple clusters but no current context")
}
if n := len(config.AuthInfos); n == 0 {
return nil, errors.New("no users provided")
} else if n > 1 {
return nil, errors.New("multiple users but no current context")
}
return newClient(config.Clusters[0].Cluster, config.AuthInfos[0].AuthInfo, namespaceDefault)
}
var ctx Context
if config.CurrentContext == "" {
if n := len(config.Contexts); n == 0 {
return nil, errors.New("no contexts provided")
} else if n > 1 {
return nil, errors.New("multiple contexts but no current context")
}
ctx = config.Contexts[0].Context
} else {
for _, c := range config.Contexts {
if c.Name == config.CurrentContext {
ctx = c.Context
goto configFound
}
}
return nil, fmt.Errorf("no config named %q", config.CurrentContext)
configFound:
}
if ctx.Cluster == "" {
return nil, fmt.Errorf("context doesn't have a cluster")
}
if ctx.AuthInfo == "" {
return nil, fmt.Errorf("context doesn't have a user")
}
var (
user AuthInfo
cluster Cluster
)
for _, u := range config.AuthInfos {
if u.Name == ctx.AuthInfo {
user = u.AuthInfo
goto userFound
}
}
return nil, fmt.Errorf("no user named %q", ctx.AuthInfo)
userFound:
for _, c := range config.Clusters {
if c.Name == ctx.Cluster {
cluster = c.Cluster
goto clusterFound
}
}
return nil, fmt.Errorf("no cluster named %q", ctx.Cluster)
clusterFound:
namespace := ctx.Namespace
if namespace == "" {
namespace = namespaceDefault
}
return newClient(cluster, user, namespace)
} | go | {
"resource": ""
} |
q8904 | NewInClusterClient | train | func NewInClusterClient() (*Client, error) {
host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT")
if len(host) == 0 || len(port) == 0 {
return nil, errors.New("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined")
}
namespace, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
return nil, err
}
server := url.URL{
Scheme: "https",
Host: net.JoinHostPort(host, port),
}
cluster := Cluster{
Server: server.String(),
CertificateAuthority: "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt",
}
user := AuthInfo{TokenFile: "/var/run/secrets/kubernetes.io/serviceaccount/token"}
return newClient(cluster, user, string(namespace))
} | go | {
"resource": ""
} |
q8905 | createConfigMap | train | func createConfigMap(client *k8s.Client, name string, values map[string]string) error {
cm := &v1.ConfigMap{
Metadata: &metav1.ObjectMeta{
Name: &name,
Namespace: &client.Namespace,
},
Data: values,
}
err := client.Create(context.Background(), cm)
// If an HTTP error was returned by the API server, it will be of type
// *k8s.APIError. This can be used to inspect the status code.
if apiErr, ok := err.(*k8s.APIError); ok {
// Resource already exists. Carry on.
if apiErr.Code == http.StatusConflict {
return nil
}
}
return fmt.Errorf("create configmap: %v", err)
} | go | {
"resource": ""
} |
q8906 | Eq | train | func (l *LabelSelector) Eq(key, val string) {
if !validLabelValue(key) || !validLabelValue(val) {
return
}
l.stmts = append(l.stmts, key+"="+val)
} | go | {
"resource": ""
} |
q8907 | In | train | func (l *LabelSelector) In(key string, vals ...string) {
if !validLabelValue(key) || len(vals) == 0 {
return
}
for _, val := range vals {
if !validLabelValue(val) {
return
}
}
l.stmts = append(l.stmts, key+" in ("+strings.Join(vals, ", ")+")")
} | go | {
"resource": ""
} |
q8908 | QueryParam | train | func QueryParam(name, value string) Option {
return optionFunc(func(base string, v url.Values) string {
v.Set(name, value)
return base
})
} | go | {
"resource": ""
} |
q8909 | Timeout | train | func Timeout(d time.Duration) Option {
return QueryParam(
"timeoutSeconds",
strconv.FormatInt(int64(d/time.Second), 10),
)
} | go | {
"resource": ""
} |
q8910 | loadClient | train | func loadClient(kubeconfigPath string) (*k8s.Client, error) {
data, err := ioutil.ReadFile(kubeconfigPath)
if err != nil {
return nil, fmt.Errorf("read kubeconfig: %v", err)
}
// Unmarshal YAML into a Kubernetes config object.
var config k8s.Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("unmarshal kubeconfig: %v", err)
}
return k8s.NewClient(&config)
} | go | {
"resource": ""
} |
q8911 | marshal | train | func marshal(i interface{}) (string, []byte, error) {
if _, ok := i.(proto.Message); ok {
data, err := marshalPB(i)
return contentTypePB, data, err
}
data, err := json.Marshal(i)
return contentTypeJSON, data, err
} | go | {
"resource": ""
} |
q8912 | unmarshal | train | func unmarshal(data []byte, contentType string, i interface{}) error {
msg, isPBMsg := i.(proto.Message)
if contentType == contentTypePB && isPBMsg {
if err := unmarshalPB(data, msg); err != nil {
return fmt.Errorf("decode protobuf: %v", err)
}
return nil
}
if isPBMsg {
// only decode into JSON of a protobuf message if the type
// explicitly implements json.Unmarshaler
if _, ok := i.(json.Unmarshaler); !ok {
return fmt.Errorf("cannot decode json payload into protobuf object %T", i)
}
}
if err := json.Unmarshal(data, i); err != nil {
return fmt.Errorf("decode json: %v", err)
}
return nil
} | go | {
"resource": ""
} |
q8913 | Next | train | func (w *Watcher) Next(r Resource) (string, error) {
return w.watcher.Next(r)
} | go | {
"resource": ""
} |
q8914 | MarshalJSON | train | func (t Time) MarshalJSON() ([]byte, error) {
var seconds, nanos int64
if t.Seconds != nil {
seconds = *t.Seconds
}
if t.Nanos != nil {
nanos = int64(*t.Nanos)
}
return json.Marshal(time.Unix(seconds, nanos))
} | go | {
"resource": ""
} |
q8915 | Has | train | func (t *LLRB) Has(key Item) bool {
return t.Get(key) != nil
} | go | {
"resource": ""
} |
q8916 | Get | train | func (t *LLRB) Get(key Item) Item {
h := t.root
for h != nil {
switch {
case less(key, h.Item):
h = h.Left
case less(h.Item, key):
h = h.Right
default:
return h.Item
}
}
return nil
} | go | {
"resource": ""
} |
q8917 | Min | train | func (t *LLRB) Min() Item {
h := t.root
if h == nil {
return nil
}
for h.Left != nil {
h = h.Left
}
return h.Item
} | go | {
"resource": ""
} |
q8918 | Max | train | func (t *LLRB) Max() Item {
h := t.root
if h == nil {
return nil
}
for h.Right != nil {
h = h.Right
}
return h.Item
} | go | {
"resource": ""
} |
q8919 | ReplaceOrInsert | train | func (t *LLRB) ReplaceOrInsert(item Item) Item {
if item == nil {
panic("inserting nil item")
}
var replaced Item
t.root, replaced = t.replaceOrInsert(t.root, item)
t.root.Black = true
if replaced == nil {
t.count++
}
return replaced
} | go | {
"resource": ""
} |
q8920 | InsertNoReplace | train | func (t *LLRB) InsertNoReplace(item Item) {
if item == nil {
panic("inserting nil item")
}
t.root = t.insertNoReplace(t.root, item)
t.root.Black = true
t.count++
} | go | {
"resource": ""
} |
q8921 | walkDownRot234 | train | func walkDownRot234(h *Node) *Node {
if isRed(h.Left) && isRed(h.Right) {
flip(h)
}
return h
} | go | {
"resource": ""
} |
q8922 | DeleteMin | train | func (t *LLRB) DeleteMin() Item {
var deleted Item
t.root, deleted = deleteMin(t.root)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
} | go | {
"resource": ""
} |
q8923 | deleteMin | train | func deleteMin(h *Node) (*Node, Item) {
if h == nil {
return nil, nil
}
if h.Left == nil {
return nil, h.Item
}
if !isRed(h.Left) && !isRed(h.Left.Left) {
h = moveRedLeft(h)
}
var deleted Item
h.Left, deleted = deleteMin(h.Left)
return fixUp(h), deleted
} | go | {
"resource": ""
} |
q8924 | DeleteMax | train | func (t *LLRB) DeleteMax() Item {
var deleted Item
t.root, deleted = deleteMax(t.root)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
} | go | {
"resource": ""
} |
q8925 | Delete | train | func (t *LLRB) Delete(key Item) Item {
var deleted Item
t.root, deleted = t.delete(t.root, key)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
} | go | {
"resource": ""
} |
q8926 | AscendGreaterOrEqual | train | func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
t.ascendGreaterOrEqual(t.root, pivot, iterator)
} | go | {
"resource": ""
} |
q8927 | DescendLessOrEqual | train | func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
t.descendLessOrEqual(t.root, pivot, iterator)
} | go | {
"resource": ""
} |
q8928 | WithValue | train | func (r *Runtime) WithValue(key string, value interface{}) *Runtime {
r.ctx[key] = value
return r
} | go | {
"resource": ""
} |
q8929 | UnmarshalPayload | train | func (r *Runtime) UnmarshalPayload(reader io.Reader, model interface{}) error {
return r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error {
return UnmarshalPayload(reader, model)
})
} | go | {
"resource": ""
} |
q8930 | UnmarshalManyPayload | train | func (r *Runtime) UnmarshalManyPayload(reader io.Reader, kind reflect.Type) (elems []interface{}, err error) {
r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error {
elems, err = UnmarshalManyPayload(reader, kind)
return err
})
return
} | go | {
"resource": ""
} |
q8931 | UnmarshalManyPayload | train | func UnmarshalManyPayload(in io.Reader, t reflect.Type) ([]interface{}, error) {
payload := new(ManyPayload)
if err := json.NewDecoder(in).Decode(payload); err != nil {
return nil, err
}
models := []interface{}{} // will be populated from the "data"
includedMap := map[string]*Node{} // will be populate from the "included"
if payload.Included != nil {
for _, included := range payload.Included {
key := fmt.Sprintf("%s,%s", included.Type, included.ID)
includedMap[key] = included
}
}
for _, data := range payload.Data {
model := reflect.New(t.Elem())
err := unmarshalNode(data, model, &includedMap)
if err != nil {
return nil, err
}
models = append(models, model.Interface())
}
return models, nil
} | go | {
"resource": ""
} |
q8932 | assign | train | func assign(field, value reflect.Value) {
value = reflect.Indirect(value)
if field.Kind() == reflect.Ptr {
// initialize pointer so it's value
// can be set by assignValue
field.Set(reflect.New(field.Type().Elem()))
field = field.Elem()
}
assignValue(field, value)
} | go | {
"resource": ""
} |
q8933 | assignValue | train | func assignValue(field, value reflect.Value) {
switch field.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
field.SetInt(value.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
field.SetUint(value.Uint())
case reflect.Float32, reflect.Float64:
field.SetFloat(value.Float())
case reflect.String:
field.SetString(value.String())
case reflect.Bool:
field.SetBool(value.Bool())
default:
field.Set(value)
}
} | go | {
"resource": ""
} |
q8934 | Marshal | train | func Marshal(models interface{}) (Payloader, error) {
switch vals := reflect.ValueOf(models); vals.Kind() {
case reflect.Slice:
m, err := convertToSliceInterface(&models)
if err != nil {
return nil, err
}
payload, err := marshalMany(m)
if err != nil {
return nil, err
}
if linkableModels, isLinkable := models.(Linkable); isLinkable {
jl := linkableModels.JSONAPILinks()
if er := jl.validate(); er != nil {
return nil, er
}
payload.Links = linkableModels.JSONAPILinks()
}
if metableModels, ok := models.(Metable); ok {
payload.Meta = metableModels.JSONAPIMeta()
}
return payload, nil
case reflect.Ptr:
// Check that the pointer was to a struct
if reflect.Indirect(vals).Kind() != reflect.Struct {
return nil, ErrUnexpectedType
}
return marshalOne(models)
default:
return nil, ErrUnexpectedType
}
} | go | {
"resource": ""
} |
q8935 | marshalOne | train | func marshalOne(model interface{}) (*OnePayload, error) {
included := make(map[string]*Node)
rootNode, err := visitModelNode(model, &included, true)
if err != nil {
return nil, err
}
payload := &OnePayload{Data: rootNode}
payload.Included = nodeMapValues(&included)
return payload, nil
} | go | {
"resource": ""
} |
q8936 | marshalMany | train | func marshalMany(models []interface{}) (*ManyPayload, error) {
payload := &ManyPayload{
Data: []*Node{},
}
included := map[string]*Node{}
for _, model := range models {
node, err := visitModelNode(model, &included, true)
if err != nil {
return nil, err
}
payload.Data = append(payload.Data, node)
}
payload.Included = nodeMapValues(&included)
return payload, nil
} | go | {
"resource": ""
} |
q8937 | JSONAPILinks | train | func (blog Blog) JSONAPILinks() *jsonapi.Links {
return &jsonapi.Links{
"self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID),
}
} | go | {
"resource": ""
} |
q8938 | JSONAPIRelationshipLinks | train | func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links {
if relation == "posts" {
return &jsonapi.Links{
"related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID),
}
}
if relation == "current_post" {
return &jsonapi.Links{
"related": fmt.Sprintf("https://example.com/blogs/%d/current_post", blog.ID),
}
}
return nil
} | go | {
"resource": ""
} |
q8939 | JSONAPIRelationshipMeta | train | func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta {
if relation == "posts" {
return &jsonapi.Meta{
"detail": "posts meta information",
}
}
if relation == "current_post" {
return &jsonapi.Meta{
"detail": "current post meta information",
}
}
return nil
} | go | {
"resource": ""
} |
q8940 | applyTransform | train | func applyTransform(str string, transform sf) (out string) {
out = ""
for idx, line := range strings.Split(str, "\n") {
out += transform(idx, line)
}
return
} | go | {
"resource": ""
} |
q8941 | MoveCursor | train | func MoveCursor(x int, y int) {
fmt.Fprintf(Screen, "\033[%d;%dH", y, x)
} | go | {
"resource": ""
} |
q8942 | MoveTo | train | func MoveTo(str string, x int, y int) (out string) {
x, y = GetXY(x, y)
return applyTransform(str, func(idx int, line string) string {
return fmt.Sprintf("\033[%d;%dH%s", y+idx, x, line)
})
} | go | {
"resource": ""
} |
q8943 | ResetLine | train | func ResetLine(str string) (out string) {
return applyTransform(str, func(idx int, line string) string {
return fmt.Sprintf("%s%s", RESET_LINE, line)
})
} | go | {
"resource": ""
} |
q8944 | Width | train | func Width() int {
ws, err := getWinsize()
if err != nil {
return -1
}
return int(ws.Col)
} | go | {
"resource": ""
} |
q8945 | Height | train | func Height() int {
ws, err := getWinsize()
if err != nil {
return -1
}
return int(ws.Row)
} | go | {
"resource": ""
} |
q8946 | Flush | train | func Flush() {
for idx, str := range strings.SplitAfter(Screen.String(), "\n") {
if idx > Height() {
return
}
Output.WriteString(str)
}
Output.Flush()
Screen.Reset()
} | go | {
"resource": ""
} |
q8947 | getChartData | train | func getChartData(data *DataTable, index int) (out [][]float64) {
for _, r := range data.rows {
out = append(out, []float64{r[0], r[index]})
}
return
} | go | {
"resource": ""
} |
q8948 | Save | train | func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
// Generate an encoded cookie value with the CSRF token.
encoded, err := cs.sc.Encode(cs.name, token)
if err != nil {
return err
}
cookie := &http.Cookie{
Name: cs.name,
Value: encoded,
MaxAge: cs.maxAge,
HttpOnly: cs.httpOnly,
Secure: cs.secure,
Path: cs.path,
Domain: cs.domain,
}
// Set the Expires field on the cookie based on the MaxAge
// If MaxAge <= 0, we don't set the Expires attribute, making the cookie
// session-only.
if cs.maxAge > 0 {
cookie.Expires = time.Now().Add(
time.Duration(cs.maxAge) * time.Second)
}
// Write the authenticated cookie to the response.
http.SetCookie(w, cookie)
return nil
} | go | {
"resource": ""
} |
q8949 | RequestHeader | train | func RequestHeader(header string) Option {
return func(cs *csrf) {
cs.opts.RequestHeader = header
}
} | go | {
"resource": ""
} |
q8950 | CookieName | train | func CookieName(name string) Option {
return func(cs *csrf) {
cs.opts.CookieName = name
}
} | go | {
"resource": ""
} |
q8951 | parseOptions | train | func parseOptions(h http.Handler, opts ...Option) *csrf {
// Set the handler to call after processing.
cs := &csrf{
h: h,
}
// Default to true. See Secure & HttpOnly function comments for rationale.
// Set here to allow package users to override the default.
cs.opts.Secure = true
cs.opts.HttpOnly = true
// Range over each options function and apply it
// to our csrf type to configure it. Options functions are
// applied in order, with any conflicting options overriding
// earlier calls.
for _, option := range opts {
option(cs)
}
return cs
} | go | {
"resource": ""
} |
q8952 | FailureReason | train | func FailureReason(r *http.Request) error {
if val, err := contextGet(r, errorKey); err == nil {
if err, ok := val.(error); ok {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q8953 | envError | train | func envError(r *http.Request, err error) *http.Request {
return contextSave(r, errorKey, err)
} | go | {
"resource": ""
} |
q8954 | ServeHTTP | train | func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Skip the check if directed to. This should always be a bool.
if val, err := contextGet(r, skipCheckKey); err == nil {
if skip, ok := val.(bool); ok {
if skip {
cs.h.ServeHTTP(w, r)
return
}
}
}
// Retrieve the token from the session.
// An error represents either a cookie that failed HMAC validation
// or that doesn't exist.
realToken, err := cs.st.Get(r)
if err != nil || len(realToken) != tokenLength {
// If there was an error retrieving the token, the token doesn't exist
// yet, or it's the wrong length, generate a new token.
// Note that the new token will (correctly) fail validation downstream
// as it will no longer match the request token.
realToken, err = generateRandomBytes(tokenLength)
if err != nil {
r = envError(r, err)
cs.opts.ErrorHandler.ServeHTTP(w, r)
return
}
// Save the new (real) token in the session store.
err = cs.st.Save(realToken, w)
if err != nil {
r = envError(r, err)
cs.opts.ErrorHandler.ServeHTTP(w, r)
return
}
}
// Save the masked token to the request context
r = contextSave(r, tokenKey, mask(realToken, r))
// Save the field name to the request context
r = contextSave(r, formKey, cs.opts.FieldName)
// HTTP methods not defined as idempotent ("safe") under RFC7231 require
// inspection.
if !contains(safeMethods, r.Method) {
// Enforce an origin check for HTTPS connections. As per the Django CSRF
// implementation (https://goo.gl/vKA7GE) the Referer header is almost
// always present for same-domain HTTP requests.
if r.URL.Scheme == "https" {
// Fetch the Referer value. Call the error handler if it's empty or
// otherwise fails to parse.
referer, err := url.Parse(r.Referer())
if err != nil || referer.String() == "" {
r = envError(r, ErrNoReferer)
cs.opts.ErrorHandler.ServeHTTP(w, r)
return
}
if sameOrigin(r.URL, referer) == false {
r = envError(r, ErrBadReferer)
cs.opts.ErrorHandler.ServeHTTP(w, r)
return
}
}
// If the token returned from the session store is nil for non-idempotent
// ("unsafe") methods, call the error handler.
if realToken == nil {
r = envError(r, ErrNoToken)
cs.opts.ErrorHandler.ServeHTTP(w, r)
return
}
// Retrieve the combined token (pad + masked) token and unmask it.
requestToken := unmask(cs.requestToken(r))
// Compare the request token against the real token
if !compareTokens(requestToken, realToken) {
r = envError(r, ErrBadToken)
cs.opts.ErrorHandler.ServeHTTP(w, r)
return
}
}
// Set the Vary: Cookie header to protect clients from caching the response.
w.Header().Add("Vary", "Cookie")
// Call the wrapped handler/router on success.
cs.h.ServeHTTP(w, r)
// Clear the request context after the handler has completed.
contextClear(r)
} | go | {
"resource": ""
} |
q8955 | unauthorizedHandler | train | func unauthorizedHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%s - %s",
http.StatusText(http.StatusForbidden), FailureReason(r)),
http.StatusForbidden)
return
} | go | {
"resource": ""
} |
q8956 | JsonToSexp | train | func JsonToSexp(json []byte, env *Zlisp) (Sexp, error) {
iface, err := JsonToGo(json)
if err != nil {
return nil, err
}
return GoToSexp(iface, env)
} | go | {
"resource": ""
} |
q8957 | SexpToJson | train | func SexpToJson(exp Sexp) string {
switch e := exp.(type) {
case *SexpHash:
return e.jsonHashHelper()
case *SexpArray:
return e.jsonArrayHelper()
case *SexpSymbol:
return `"` + e.name + `"`
default:
return exp.SexpString(nil)
}
} | go | {
"resource": ""
} |
q8958 | JsonToGo | train | func JsonToGo(json []byte) (interface{}, error) {
var iface interface{}
decoder := codec.NewDecoderBytes(json, &msgpHelper.jh)
err := decoder.Decode(&iface)
if err != nil {
panic(err)
}
VPrintf("\n decoded type : %T\n", iface)
VPrintf("\n decoded value: %#v\n", iface)
return iface, nil
} | go | {
"resource": ""
} |
q8959 | GoToJson | train | func GoToJson(iface interface{}) []byte {
var w bytes.Buffer
encoder := codec.NewEncoder(&w, &msgpHelper.jh)
err := encoder.Encode(&iface)
if err != nil {
panic(err)
}
return w.Bytes()
} | go | {
"resource": ""
} |
q8960 | MsgpackToSexp | train | func MsgpackToSexp(msgp []byte, env *Zlisp) (Sexp, error) {
iface, err := MsgpackToGo(msgp)
if err != nil {
return nil, fmt.Errorf("MsgpackToSexp failed at MsgpackToGo step: '%s", err)
}
sexp, err := GoToSexp(iface, env)
if err != nil {
return nil, fmt.Errorf("MsgpackToSexp failed at GoToSexp step: '%s", err)
}
return sexp, nil
} | go | {
"resource": ""
} |
q8961 | MsgpackToGo | train | func MsgpackToGo(msgp []byte) (interface{}, error) {
var iface interface{}
dec := codec.NewDecoderBytes(msgp, &msgpHelper.mh)
err := dec.Decode(&iface)
if err != nil {
return nil, err
}
//fmt.Printf("\n decoded type : %T\n", iface)
//fmt.Printf("\n decoded value: %#v\n", iface)
return iface, nil
} | go | {
"resource": ""
} |
q8962 | dumpComment | train | func (lexer *Lexer) dumpComment() {
str := lexer.buffer.String()
lexer.buffer.Reset()
lexer.AppendToken(lexer.Token(TokenComment, str))
} | go | {
"resource": ""
} |
q8963 | SexpString | train | func (s *Scope) SexpString(ps *PrintState) string {
var label string
head := ""
if s.IsPackage {
head = "(package " + s.PackageName
} else {
label = "scope " + s.Name
if s.IsGlobal {
label += " (global)"
}
}
str, err := s.Show(s.env, ps, s.Name)
if err != nil {
return "(" + label + ")"
}
return head + " " + str + " )"
} | go | {
"resource": ""
} |
q8964 | LookupSymbolNonGlobal | train | func (stack *Stack) LookupSymbolNonGlobal(sym *SexpSymbol) (Sexp, error, *Scope) {
return stack.lookupSymbol(sym, 1, nil)
} | go | {
"resource": ""
} |
q8965 | MsgpackMapMacro | train | func MsgpackMapMacro(env *Zlisp, name string,
args []Sexp) (Sexp, error) {
if len(args) < 1 {
return SexpNull, fmt.Errorf("struct-name is missing. use: " +
"(msgpack-map struct-name)\n")
}
return MakeList([]Sexp{
env.MakeSymbol("def"),
args[0],
MakeList([]Sexp{
env.MakeSymbol("quote"),
env.MakeSymbol("msgmap"),
&SexpStr{S: args[0].(*SexpSymbol).name},
}),
}), nil
} | go | {
"resource": ""
} |
q8966 | RemoveEndsFilter | train | func RemoveEndsFilter(x Sexp) bool {
switch n := x.(type) {
case *SexpSentinel:
if n.Val == SexpEnd.Val {
return false
}
}
return true
} | go | {
"resource": ""
} |
q8967 | MergeFuncMap | train | func MergeFuncMap(funcs ...map[string]ZlispUserFunction) map[string]ZlispUserFunction {
n := make(map[string]ZlispUserFunction)
for _, f := range funcs {
for k, v := range f {
// disallow dups, avoiding possible security implications and confusion generally.
if _, dup := n[k]; dup {
panic(fmt.Sprintf(" duplicate function '%s' not allowed", k))
}
n[k] = v
}
}
return n
} | go | {
"resource": ""
} |
q8968 | CoreFunctions | train | func CoreFunctions() map[string]ZlispUserFunction {
return map[string]ZlispUserFunction{
"pretty": SetPrettyPrintFlag,
"<": CompareFunction,
">": CompareFunction,
"<=": CompareFunction,
">=": CompareFunction,
"==": CompareFunction,
"!=": CompareFunction,
"isnan": IsNaNFunction,
"isNaN": IsNaNFunction,
"sll": BinaryIntFunction,
"sra": BinaryIntFunction,
"srl": BinaryIntFunction,
"mod": BinaryIntFunction,
"+": NumericFunction,
"-": NumericFunction,
"*": PointerOrNumericFunction,
"**": NumericFunction,
"/": NumericFunction,
"bitAnd": BitwiseFunction,
"bitOr": BitwiseFunction,
"bitXor": BitwiseFunction,
"bitNot": ComplementFunction,
"read": ReadFunction,
"cons": ConsFunction,
"first": FirstFunction,
"second": SecondFunction,
"rest": RestFunction,
"car": FirstFunction,
"cdr": RestFunction,
"type?": TypeQueryFunction,
"list?": TypeQueryFunction,
"null?": TypeQueryFunction,
"array?": TypeQueryFunction,
"hash?": TypeQueryFunction,
"number?": TypeQueryFunction,
"int?": TypeQueryFunction,
"float?": TypeQueryFunction,
"char?": TypeQueryFunction,
"symbol?": TypeQueryFunction,
"string?": TypeQueryFunction,
"zero?": TypeQueryFunction,
"empty?": TypeQueryFunction,
"func?": TypeQueryFunction,
"not": NotFunction,
"apply": ApplyFunction,
"map": MapFunction,
"makeArray": MakeArrayFunction,
"aget": ArrayAccessFunction,
"aset": ArrayAccessFunction,
"sget": SgetFunction,
"hget": GenericAccessFunction, // handles arrays or hashes
//":": ColonAccessFunction,
"hset": HashAccessFunction,
"hdel": HashAccessFunction,
"keys": HashAccessFunction,
"hpair": GenericHpairFunction,
"slice": SliceFunction,
"len": LenFunction,
"append": AppendFunction,
"appendslice": AppendFunction,
"concat": ConcatFunction,
"field": ConstructorFunction,
"struct": ConstructorFunction,
"array": ConstructorFunction,
"list": ConstructorFunction,
"hash": ConstructorFunction,
"raw": ConstructorFunction,
"str": StringifyFunction,
"->": ThreadMapFunction,
"flatten": FlattenToWordsFunction,
"quotelist": QuoteListFunction,
"=": AssignmentFunction,
":=": AssignmentFunction,
"fieldls": GoFieldListFunction,
"defined?": DefinedFunction,
"stop": StopFunction,
"joinsym": JoinSymFunction,
"GOOS": GOOSFunction,
"&": AddressOfFunction,
"derefSet": DerefFunction,
"deref": DerefFunction,
".": DotFunction,
"arrayidx": ArrayIndexFunction,
"hashidx": HashIndexFunction,
"asUint64": AsUint64Function,
}
} | go | {
"resource": ""
} |
q8969 | GenericAccessFunction | train | func GenericAccessFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) < 1 || len(args) > 3 {
return SexpNull, WrongNargs
}
// handle *SexpSelector
container := args[0]
var err error
if ptr, isPtrLike := container.(Selector); isPtrLike {
container, err = ptr.RHS(env)
if err != nil {
return SexpNull, err
}
}
switch container.(type) {
case *SexpHash:
return HashAccessFunction(env, name, args)
case *SexpArray:
return ArrayAccessFunction(env, name, args)
}
return SexpNull, fmt.Errorf("first argument to hget function must be hash or array")
} | go | {
"resource": ""
} |
q8970 | AssignmentFunction | train | func AssignmentFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
Q("\n AssignmentFunction called with name ='%s'. args='%s'\n", name,
env.NewSexpArray(args).SexpString(nil))
narg := len(args)
if narg != 2 {
return SexpNull, fmt.Errorf("assignment requires two arguments: a left-hand-side and a right-hand-side argument")
}
var sym *SexpSymbol
switch s := args[0].(type) {
case *SexpSymbol:
sym = s
case Selector:
err := s.AssignToSelection(env, args[1])
return args[1], err
default:
return SexpNull, fmt.Errorf("assignment needs left-hand-side"+
" argument to be a symbol; we got %T", s)
}
if !sym.isDot {
Q("assignment sees LHS symbol but is not dot, binding '%s' to '%s'\n",
sym.name, args[1].SexpString(nil))
err := env.LexicalBindSymbol(sym, args[1])
if err != nil {
return SexpNull, err
}
return args[1], nil
}
Q("assignment calling dotGetSetHelper()\n")
return dotGetSetHelper(env, sym.name, &args[1])
} | go | {
"resource": ""
} |
q8971 | errIfPrivate | train | func errIfPrivate(pathPart string, pkg *Stack) error {
noDot := stripAnyDotPrefix(pathPart)
// references through a package must be Public
if !unicode.IsUpper([]rune(noDot)[0]) {
return fmt.Errorf("Cannot access private member '%s' of package '%s'",
noDot, pkg.PackageName)
}
return nil
} | go | {
"resource": ""
} |
q8972 | DotFunction | train | func DotFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 2 {
return SexpNull, WrongNargs
}
P("in DotFunction(), name='%v', args[0] = '%v', args[1]= '%v'",
name,
args[0].SexpString(nil),
args[1].SexpString(nil))
return SexpNull, nil
/*
var ret Sexp = SexpNull
var err error
lenpath := len(path)
if lenpath == 1 && setVal != nil {
// single path element set, bind it now.
a := path[0][1:] // strip off the dot
asym := env.MakeSymbol(a)
// check conflict
//Q("asym = %#v\n", asym)
builtin, typ := env.IsBuiltinSym(asym)
if builtin {
return SexpNull, fmt.Errorf("'%s' is a %s, cannot assign to it with dot-symbol", asym.name, typ)
}
err := env.LexicalBindSymbol(asym, *setVal)
if err != nil {
return SexpNull, err
}
return *setVal, nil
}
// handle multiple paths that index into hashes after the
// the first
key := path[0][1:] // strip off the dot
//Q("\n in dotGetSetHelper(), looking up '%s'\n", key)
ret, err, _ = env.LexicalLookupSymbol(env.MakeSymbol(key), false)
if err != nil {
Q("\n in dotGetSetHelper(), '%s' not found\n", key)
return SexpNull, err
}
return ret, err
*/
} | go | {
"resource": ""
} |
q8973 | AsUint64Function | train | func AsUint64Function(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
var val uint64
switch x := args[0].(type) {
case *SexpInt:
val = uint64(x.Val)
case *SexpFloat:
val = uint64(x.Val)
default:
return SexpNull, fmt.Errorf("Cannot convert %s to uint64", TypeOf(args[0]).SexpString(nil))
}
return &SexpUint64{Val: val}, nil
} | go | {
"resource": ""
} |
q8974 | GenericHpairFunction | train | func GenericHpairFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 2 {
return SexpNull, WrongNargs
}
posreq, isInt := args[1].(*SexpInt)
if !isInt {
return SexpNull, fmt.Errorf("hpair position request must be an integer")
}
pos := int(posreq.Val)
switch seq := args[0].(type) {
case *SexpHash:
if pos < 0 || pos >= len(seq.KeyOrder) {
return SexpNull, fmt.Errorf("hpair position request %d out of bounds", pos)
}
return seq.HashPairi(pos)
case *SexpArray:
if pos < 0 || pos >= len(seq.Val) {
return SexpNull, fmt.Errorf("hpair position request %d out of bounds", pos)
}
return Cons(&SexpInt{Val: int64(pos)}, Cons(seq.Val[pos], SexpNull)), nil
default:
return SexpNull, errors.New("first argument of to hpair function must be hash, list, or array")
}
//return SexpNull, nil
} | go | {
"resource": ""
} |
q8975 | CloneFrom | train | func (p *SexpHash) CloneFrom(src *SexpHash) {
p.TypeName = src.TypeName
p.Map = *(src.CopyMap())
p.KeyOrder = src.KeyOrder
p.GoStructFactory = src.GoStructFactory
p.NumKeys = src.NumKeys
p.GoMethods = src.GoMethods
p.GoFields = src.GoFields
p.GoMethSx = src.GoMethSx
p.GoFieldSx = src.GoFieldSx
p.GoType = src.GoType
p.NumMethod = src.NumMethod
p.GoShadowStruct = src.GoShadowStruct
p.GoShadowStructVa = src.GoShadowStructVa
p.ShadowSet = src.ShadowSet
// json tag name -> pointers to example values, as factories for SexpToGoStructs()
p.JsonTagMap = make(map[string]*HashFieldDet)
for k, v := range src.JsonTagMap {
p.JsonTagMap[k] = v
}
p.DetOrder = src.DetOrder
// for using these as a scoping model
p.DefnEnv = src.DefnEnv
p.SuperClass = src.SuperClass
p.ZMain = src.ZMain
p.ZMethods = make(map[string]*SexpFunction)
for k, v := range src.ZMethods {
p.ZMethods[k] = v
}
p.Env = src.Env
} | go | {
"resource": ""
} |
q8976 | Start | train | func (p *Parser) Start() {
go func() {
defer close(p.Done)
expressions := make([]Sexp, 0, SliceDefaultCap)
// maybe we already have input, be optimistic!
// no need to call p.GetMoreInput() before staring
// our loop.
for {
expr, err := p.ParseExpression(0)
if err != nil || expr == SexpEnd {
if err == ParserHaltRequested {
return
}
err = p.GetMoreInput(expressions, err)
if err == ParserHaltRequested {
return
}
// GetMoreInput will have delivered what we gave them. Reset since we
// don't own that memory any more.
expressions = make([]Sexp, 0, SliceDefaultCap)
} else {
// INVAR: err == nil && expr is not SexpEnd
expressions = append(expressions, expr)
}
}
}()
} | go | {
"resource": ""
} |
q8977 | getExpressionWithLiner | train | func (pr *Prompter) getExpressionWithLiner(env *Glisp) (readin string, xs []Sexp, err error) {
line, err := pr.Getline(nil)
if err != nil {
return "", nil, err
}
err = UnexpectedEnd
var x []Sexp
// parse and pause the parser if we need more input.
env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\n")))
x, err = env.parser.ParseTokens()
if len(x) > 0 {
xs = append(xs, x...)
}
for err == ErrMoreInputNeeded || err == UnexpectedEnd || err == ResetRequested {
nextline, err := pr.Getline(&continuationPrompt)
if err != nil {
return "", nil, err
}
// provide more input
env.parser.NewInput(bytes.NewBuffer([]byte(nextline + "\n")))
// get parsed expression tree(s) back in x
x, err = env.parser.ParseTokens()
if len(x) > 0 {
for i := range x {
if x[i] == SexpEnd {
P("found an SexpEnd token, omitting it")
continue
}
xs = append(xs, x[i])
}
}
switch err {
case nil:
line += "\n" + nextline
// no problem, parsing went fine.
return line, xs, nil
case ResetRequested:
continue
case ErrMoreInputNeeded:
continue
default:
return "", nil, fmt.Errorf("Error on line %d: %v\n", env.parser.lexer.Linenum(), err)
}
}
return line, xs, nil
} | go | {
"resource": ""
} |
q8978 | TSPrintf | train | func TSPrintf(format string, a ...interface{}) {
fmt.Printf("%s ", ts())
fmt.Printf(format, a...)
} | go | {
"resource": ""
} |
q8979 | MyWordCompleter | train | func MyWordCompleter(line string, pos int) (head string, c []string, tail string) {
beg := []rune(line[:pos])
end := line[pos:]
Q("\nline = '%s' pos=%v\n", line, pos)
Q("\nbeg = '%v'\nend = '%s'\n", string(beg), end)
// find most recent paren in beg
n := len(beg)
last := n - 1
var i int
var p int = -1
outer:
for i = last; i >= 0; i-- {
Q("\nbeg[i=%v] is '%v'\n", i, string(beg[i]))
switch beg[i] {
case ' ':
break outer
case '(':
p = i
Q("\n found paren at p = %v\n", i)
break outer
}
}
Q("p=%d\n", p)
prefix := string(beg)
extendme := ""
if p == 0 {
prefix = ""
extendme = string(beg)
} else if p > 0 {
prefix = string(beg[:p])
extendme = string(beg[p:])
}
Q("prefix = '%s'\nextendme = '%s'\n", prefix, extendme)
for _, n := range completion_keywords {
if strings.HasPrefix(n, strings.ToLower(extendme)) {
Q("n='%s' has prefix = '%s'\n", n, extendme)
c = append(c, n)
}
}
return prefix, c, end
} | go | {
"resource": ""
} |
q8980 | Assignment | train | func (env *Zlisp) Assignment(op string, bp int) *InfixOp {
oper := env.MakeSymbol(op)
operSet := env.MakeSymbol("set")
iop := &InfixOp{
Sym: oper,
Bp: bp,
MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) {
// TODO: check that left is okay as an LVALUE.
right, err := pr.Expression(env, bp-1)
if err != nil {
return SexpNull, err
}
if op == "=" || op == ":=" {
oper = operSet
}
list := MakeList([]Sexp{
oper, left, right,
})
Q("assignment returning list: '%v'", list.SexpString(nil))
return list, nil
},
IsAssign: true,
}
env.infixOps[op] = iop
return iop
} | go | {
"resource": ""
} |
q8981 | PostfixAssign | train | func (env *Zlisp) PostfixAssign(op string, bp int) *InfixOp {
oper := env.MakeSymbol(op)
iop := &InfixOp{
Sym: oper,
Bp: bp,
MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) {
// TODO: check that left is okay as an LVALUE
list := MakeList([]Sexp{
oper, left,
})
Q("postfix assignment returning list: '%v'", list.SexpString(nil))
return list, nil
},
}
env.infixOps[op] = iop
return iop
} | go | {
"resource": ""
} |
q8982 | Advance | train | func (p *Pratt) Advance() error {
p.Pos++
if p.Pos >= len(p.Stream) {
return io.EOF
}
p.NextToken = p.Stream[p.Pos]
Q("end of Advance, p.NextToken = '%v'", p.NextToken.SexpString(nil))
return nil
} | go | {
"resource": ""
} |
q8983 | LookupSymbolInParentChainOfClosures | train | func (sf *SexpFunction) LookupSymbolInParentChainOfClosures(sym *SexpSymbol, setVal *Sexp, env *Zlisp) (Sexp, error, *Scope) {
cur := sf
par := sf.parent
for par != nil {
//fmt.Printf(" parent chain: cur:%v -> parent:%v\n", cur.name, par.name)
//fmt.Printf(" cur.closures = %s", ClosureToString(cur, env))
exp, err, scope := cur.ClosingLookupSymbolUntilFunc(sym, setVal, 1, false)
if err == nil {
//P("LookupSymbolInParentChainOfClosures(sym='%s') found in scope '%s'\n", sym.name, scope.Name)
return exp, err, scope
}
cur = par
par = par.parent
}
return SexpNull, SymNotFound, nil
} | go | {
"resource": ""
} |
q8984 | NilOrHoldsNil | train | func NilOrHoldsNil(iface interface{}) bool {
if iface == nil {
return true
}
return reflect.ValueOf(iface).IsNil()
} | go | {
"resource": ""
} |
q8985 | ImportPackageBuilder | train | func ImportPackageBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) {
//P("starting ImportPackageBuilder")
n := len(args)
if n != 1 && n != 2 {
return SexpNull, WrongNargs
}
var path Sexp
var alias string
switch n {
case 1:
path = args[0]
case 2:
path = args[1]
//P("import debug: alias position at args[0] is '%#v'", args[0])
switch sy := args[0].(type) {
case *SexpSymbol:
//P("import debug: alias is symbol, ok: '%v'", sy.name)
alias = sy.name
default:
return SexpNull, fmt.Errorf("import error: alias was not a symbol name")
}
}
var pth string
switch x := path.(type) {
case *SexpStr:
pth = x.S
default:
return SexpNull, fmt.Errorf("import error: path argument must be string")
}
if !FileExists(pth) {
return SexpNull, fmt.Errorf("import error: path '%s' does not exist", pth)
}
pkg, err := SourceFileFunction(env, "source", []Sexp{path})
if err != nil {
return SexpNull, fmt.Errorf("import error: attempt to import path '%s' resulted in: '%s'", pth, err)
}
//P("pkg = '%#v'", pkg)
asPkg, isPkg := pkg.(*Stack)
if !isPkg || !asPkg.IsPackage {
return SexpNull, fmt.Errorf("import error: attempt to import path '%s' resulted value that was not a package, but rather '%T'", pth, pkg)
}
if n == 1 {
alias = asPkg.PackageName
}
//P("using alias = '%s'", alias)
// now set alias in the current env
err = env.LexicalBindSymbol(env.MakeSymbol(alias), asPkg)
if err != nil {
return SexpNull, err
}
return pkg, nil
} | go | {
"resource": ""
} |
q8986 | GenerateNewScope | train | func (gen *Generator) GenerateNewScope(expressions []Sexp) error {
size := len(expressions)
oldtail := gen.Tail
gen.Tail = false
if size == 0 {
return nil
//return NoExpressionsFound
}
gen.AddInstruction(AddScopeInstr{Name: "newScope"})
for _, expr := range expressions[:size-1] {
err := gen.Generate(expr)
if err != nil {
return err
}
// insert pops after all but the last instruction
// that way the stack remains clean... Q: how does this extra popping not mess up the expressions?
gen.AddInstruction(PopInstr(0))
}
gen.Tail = oldtail
err := gen.Generate(expressions[size-1])
if err != nil {
return err
}
gen.AddInstruction(RemoveScopeInstr{})
return nil
} | go | {
"resource": ""
} |
q8987 | SetShellCmd | train | func SetShellCmd() {
if runtime.GOOS == "windows" {
ShellCmd = os.Getenv("COMSPEC")
return
}
try := []string{"/usr/bin/bash"}
if !FileExists(ShellCmd) {
for i := range try {
b := try[i]
if FileExists(b) {
ShellCmd = b
return
}
}
}
} | go | {
"resource": ""
} |
q8988 | SystemBuilder | train | func SystemBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) {
//P("SystemBuilder called with args='%#v'", args)
return SystemFunction(env, name, args)
} | go | {
"resource": ""
} |
q8989 | DumpFunction | train | func DumpFunction(fun ZlispFunction, pc int) {
blank := " "
extra := blank
for i, instr := range fun {
if i == pc {
extra = " PC-> "
} else {
extra = blank
}
fmt.Printf("%s %d: %s\n", extra, i, instr.InstrString())
}
if pc == len(fun) {
fmt.Printf(" PC just past end at %d -----\n\n", pc)
}
} | go | {
"resource": ""
} |
q8990 | FindLoop | train | func (env *Zlisp) FindLoop(target *Loop) (int, error) {
if env.curfunc.user {
panic(fmt.Errorf("impossible in user-defined-function to find a loop '%s'", target.stmtname.name))
}
instruc := env.curfunc.fun
for i := range instruc {
switch loop := instruc[i].(type) {
case LoopStartInstr:
if loop.loop == target {
return i, nil
}
}
}
return -1, fmt.Errorf("could not find loop target '%s'", target.stmtname.name)
} | go | {
"resource": ""
} |
q8991 | SplitStringFunction | train | func SplitStringFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 2 {
return SexpNull, WrongNargs
}
// make sure the two args are strings
s1, ok := args[0].(*SexpStr)
if !ok {
return SexpNull, fmt.Errorf("split requires a string to split, got %T", args[0])
}
s2, ok := args[1].(*SexpStr)
if !ok {
return SexpNull, fmt.Errorf("split requires a string as a delimiter, got %T", args[1])
}
toSplit := s1.S
splitter := s2.S
s := strings.Split(toSplit, splitter)
split := make([]Sexp, len(s))
for i := range split {
split[i] = &SexpStr{S: s[i]}
}
return env.NewSexpArray(split), nil
} | go | {
"resource": ""
} |
q8992 | isBalanced | train | func isBalanced(str string) bool {
parens := 0
squares := 0
for _, c := range str {
switch c {
case '(':
parens++
case ')':
parens--
case '[':
squares++
case ']':
squares--
}
}
return parens == 0 && squares == 0
} | go | {
"resource": ""
} |
q8993 | getExpressionWithLiner | train | func (pr *Prompter) getExpressionWithLiner(env *Zlisp, reader *bufio.Reader, noLiner bool) (readin string, xs []Sexp, err error) {
var line, nextline string
if noLiner {
fmt.Printf(pr.prompt)
line, err = getLine(reader)
} else {
line, err = pr.Getline(nil)
}
if err != nil {
return "", nil, err
}
err = UnexpectedEnd
var x []Sexp
// test parse, but don't load or generate bytecode
env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\n")))
x, err = env.parser.ParseTokens()
//P("\n after ResetAddNewInput, err = %v. x = '%s'\n", err, SexpArray(x).SexpString())
if len(x) > 0 {
xs = append(xs, x...)
}
for err == ErrMoreInputNeeded || err == UnexpectedEnd || err == ResetRequested {
if noLiner {
fmt.Printf(continuationPrompt)
nextline, err = getLine(reader)
} else {
nextline, err = pr.Getline(&continuationPrompt)
}
if err != nil {
return "", nil, err
}
env.parser.NewInput(bytes.NewBuffer([]byte(nextline + "\n")))
x, err = env.parser.ParseTokens()
if len(x) > 0 {
for i := range x {
if x[i] == SexpEnd {
P("found an SexpEnd token, omitting it")
continue
}
xs = append(xs, x[i])
}
}
switch err {
case nil:
line += "\n" + nextline
Q("no problem parsing line '%s' into '%s', proceeding...\n", line, (&SexpArray{Val: x, Env: env}).SexpString(nil))
return line, xs, nil
case ResetRequested:
continue
case ErrMoreInputNeeded:
continue
default:
return "", nil, fmt.Errorf("Error on line %d: %v\n", env.parser.lexer.Linenum(), err)
}
}
return line, xs, nil
} | go | {
"resource": ""
} |
q8994 | AsTmFunction | train | func AsTmFunction(env *Zlisp, name string,
args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
var str *SexpStr
switch t := args[0].(type) {
case *SexpStr:
str = t
default:
return SexpNull,
errors.New("argument of astm should be a string RFC3999Nano timestamp that we want to convert to time.Time")
}
tm, err := time.ParseInLocation(time.RFC3339Nano, str.S, NYC)
if err != nil {
return SexpNull, err
}
return &SexpTime{Tm: tm.In(NYC)}, nil
} | go | {
"resource": ""
} |
q8995 | SimpleSourceFunction | train | func SimpleSourceFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
src, isStr := args[0].(*SexpStr)
if !isStr {
return SexpNull, fmt.Errorf("-> error: first argument must be a string")
}
file := src.S
if !FileExists(file) {
return SexpNull, fmt.Errorf("path '%s' does not exist", file)
}
env2 := env.Duplicate()
f, err := os.Open(file)
if err != nil {
return SexpNull, err
}
defer f.Close()
err = env2.LoadFile(f)
if err != nil {
return SexpNull, err
}
_, err = env2.Run()
return SexpNull, err
} | go | {
"resource": ""
} |
q8996 | SourceExpressions | train | func (env *Zlisp) SourceExpressions(expressions []Sexp) error {
gen := NewGenerator(env)
err := gen.GenerateBegin(expressions)
if err != nil {
return err
}
//P("debug: in SourceExpressions, FROM expressions='%s'", (&SexpArray{Val: expressions, Env: env}).SexpString(0))
//P("debug: in SourceExpressions, gen=")
//DumpFunction(ZlispFunction(gen.instructions), -1)
curfunc := env.curfunc
curpc := env.pc
env.curfunc = env.MakeFunction("__source", 0, false,
gen.instructions, nil)
env.pc = 0
result, err := env.Run()
if err != nil {
return err
}
//P("end of SourceExpressions, result going onto datastack is: '%s'", result.SexpString(0))
env.datastack.PushExpr(result)
//P("debug done with Run in source, now stack is:")
//env.datastack.PrintStack()
env.pc = curpc
env.curfunc = curfunc
return nil
} | go | {
"resource": ""
} |
q8997 | sourceItem | train | func (env *Zlisp) sourceItem(item Sexp) error {
switch t := item.(type) {
case *SexpArray:
for _, v := range t.Val {
if err := env.sourceItem(v); err != nil {
return err
}
}
case *SexpPair:
expr := item
for expr != SexpNull {
list := expr.(*SexpPair)
if err := env.sourceItem(list.Head); err != nil {
return err
}
expr = list.Tail
}
case *SexpStr:
var f *os.File
var err error
if f, err = os.Open(t.S); err != nil {
return err
}
defer f.Close()
if err = env.SourceFile(f); err != nil {
return err
}
default:
return fmt.Errorf("source: Expected `string`, `list`, `array`. Instead found type %T val %v", item, item)
}
return nil
} | go | {
"resource": ""
} |
q8998 | SexpString | train | func (p *RecordDefn) SexpString(ps *PrintState) string {
Q("RecordDefn::SexpString() called!")
if len(p.Fields) == 0 {
return fmt.Sprintf("(struct %s)", p.Name)
}
s := fmt.Sprintf("(struct %s [\n", p.Name)
w := make([][]int, len(p.Fields))
maxnfield := 0
for i, f := range p.Fields {
w[i] = f.FieldWidths()
Q("w[i=%v] = %v", i, w[i])
maxnfield = maxi(maxnfield, len(w[i]))
}
biggestCol := make([]int, maxnfield)
Q("\n")
for j := 0; j < maxnfield; j++ {
for i := range p.Fields {
Q("i= %v, j=%v, len(w[i])=%v check=%v", i, j, len(w[i]), len(w[i]) < j)
if j < len(w[i]) {
biggestCol[j] = maxi(biggestCol[j], w[i][j]+1)
}
}
}
Q("RecordDefn::SexpString(): maxnfield = %v, out of %v", maxnfield, len(p.Fields))
Q("RecordDefn::SexpString(): biggestCol = %#v", biggestCol)
// computing padding
// x
// xx xx
// xxxxxxx x
// xxx x x x
//
// becomes
//
// x
// xx xx
// xxxxxxx
// xxx x x x
Q("pad = %#v", biggestCol)
for _, f := range p.Fields {
s += " " + f.AlignString(biggestCol) + "\n"
}
s += " ])\n"
return s
} | go | {
"resource": ""
} |
q8999 | FieldWidths | train | func (f *SexpField) FieldWidths() []int {
hash := (*SexpHash)(f)
wide := []int{}
for _, key := range hash.KeyOrder {
val, err := hash.HashGet(nil, key)
str := ""
if err == nil {
switch s := key.(type) {
case *SexpStr:
str += s.S + ":"
case *SexpSymbol:
str += s.name + ":"
default:
str += key.SexpString(nil) + ":"
}
wide = append(wide, len(str))
wide = append(wide, len(val.SexpString(nil))+1)
} else {
panic(err)
}
}
return wide
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.