// lookdot0 returns the number of fields or methods named s associated // with Type t. If exactly one exists, it will be returned in *save // (if save is not nil). func lookdot0(s *Sym, t *Type, save **Field, ignorecase bool) int { u := t if u.IsPtr() { u = u.Elem() } c := 0 if u.IsStruct() || u.IsInterface() { for _, f := range u.Fields().Slice() { if f.Sym == s || (ignorecase && f.Type.Etype == TFUNC && f.Type.Recv() != nil && strings.EqualFold(f.Sym.Name, s.Name)) { if save != nil { *save = f } c++ } } } u = methtype(t, 0) if u != nil { for _, f := range u.Methods().Slice() { if f.Embedded == 0 && (f.Sym == s || (ignorecase && strings.EqualFold(f.Sym.Name, s.Name))) { if save != nil { *save = f } c++ } } } return c }
func TestParseServerInfo(t *testing.T) { data := []byte{ 0xFF, 0xFF, 0xFF, 0xFF, 0x49, 0x11, 0x71, 0x6C, 0x2E, 0x73, 0x79, 0x6E, 0x63, 0x6F, 0x72, 0x65, 0x2E, 0x6F, 0x72, 0x67, 0x20, 0x2D, 0x20, 0x55, 0x53, 0x20, 0x43, 0x45, 0x4E, 0x54, 0x52, 0x41, 0x4C, 0x20, 0x23, 0x31, 0x00, 0x74, 0x68, 0x75, 0x6E, 0x64, 0x65, 0x72, 0x73, 0x74, 0x72, 0x75, 0x63, 0x6B, 0x00, 0x62, 0x61, 0x73, 0x65, 0x71, 0x33, 0x00, 0x43, 0x6C, 0x61, 0x6E, 0x20, 0x41, 0x72, 0x65, 0x6E, 0x61, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x64, 0x6C, 0x00, 0x01, 0x31, 0x30, 0x36, 0x33, 0x00, 0xB1, 0x38, 0x6D, 0x02, 0xF8, 0xC1, 0x4D, 0x7B, 0x17, 0x40, 0x01, 0x63, 0x6C, 0x61, 0x6E, 0x61, 0x72, 0x65, 0x6E, 0x61, 0x2C, 0x73, 0x79, 0x6E, 0x63, 0x6F, 0x72, 0x65, 0x2C, 0x74, 0x65, 0x78, 0x61, 0x73, 0x00, 0x48, 0x4F, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} sinfo, err := parseServerInfo(data) if err != nil { t.Fatalf("Unexpected error when parsing server info") } if !strings.EqualFold(sinfo.Name, "ql.syncore.org - US CENTRAL #1") { t.Fatalf("Expected server name: ql.syncore.org - US CENTRAL #1 got: %s", sinfo.Name) } if !strings.EqualFold(sinfo.Environment, "Linux") { t.Fatalf("Expected server environment: Linux got: %s", sinfo.Environment) } if sinfo.Players != 2 { t.Fatalf("Expected server to contain 2 players, got: %d", sinfo.Players) } if !strings.EqualFold(sinfo.Folder, "baseq3") { t.Fatalf("Expected server's game folder to be baseq3, got: %s", sinfo.Folder) } }
// parseMetaGoImports returns meta imports from the HTML in r. // Parsing ends at the end of the <head> section or the beginning of the <body>. func parseMetaGoImports(r io.Reader) (imports []metaImport) { d := xml.NewDecoder(r) d.Strict = false for { t, err := d.Token() if err != nil { return } if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") { return } if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") { return } e, ok := t.(xml.StartElement) if !ok || !strings.EqualFold(e.Name.Local, "meta") { continue } if attrValue(e.Attr, "name") != "go-import" { continue } if f := strings.Fields(attrValue(e.Attr, "content")); len(f) == 3 { imports = append(imports, metaImport{ Prefix: f[0], VCS: f[1], RepoRoot: f[2], }) } } return }
func (c *Context) LoadEnv() (*rancherClient.Environment, error) { if c.Environment != nil { return c.Environment, nil } projectName := c.sanitizedProjectName() if _, err := c.loadClient(); err != nil { return nil, err } logrus.Debugf("Looking for stack %s", projectName) // First try by name envs, err := c.Client.Environment.List(&rancherClient.ListOpts{ Filters: map[string]interface{}{ "name": projectName, "removed_null": nil, }, }) if err != nil { return nil, err } for _, env := range envs.Data { if strings.EqualFold(projectName, env.Name) { logrus.Debugf("Found stack: %s(%s)", env.Name, env.Id) c.Environment = &env return c.Environment, nil } } // Now try not by name for case sensitive databases envs, err = c.Client.Environment.List(&rancherClient.ListOpts{ Filters: map[string]interface{}{ "removed_null": nil, }, }) if err != nil { return nil, err } for _, env := range envs.Data { if strings.EqualFold(projectName, env.Name) { logrus.Debugf("Found stack: %s(%s)", env.Name, env.Id) c.Environment = &env return c.Environment, nil } } logrus.Infof("Creating stack %s", projectName) env, err := c.Client.Environment.Create(&rancherClient.Environment{ Name: projectName, }) if err != nil { return nil, err } c.Environment = env return c.Environment, nil }
func (c *CommandLine) Insert(stmt string) error { i, point := parseNextIdentifier(stmt) if !strings.EqualFold(i, "insert") { fmt.Printf("ERR: found %s, expected INSERT\n", i) return nil } if i, r := parseNextIdentifier(point); strings.EqualFold(i, "into") { point = c.parseInto(r) } _, err := c.Client.Write(client.BatchPoints{ Points: []client.Point{ client.Point{Raw: point}, }, Database: c.Database, RetentionPolicy: c.RetentionPolicy, Precision: "n", WriteConsistency: c.WriteConsistency, }) if err != nil { fmt.Printf("ERR: %s\n", err) if c.Database == "" { fmt.Println("Note: error may be due to not setting a database or retention policy.") fmt.Println(`Please set a database with the command "use <database>" or`) fmt.Println("INSERT INTO <database>.<retention-policy> <point>") } return err } return nil }
// DecodeStrict returns an error if env contains prefixed variables that do not // correspond to either field names in v, or keys in ignoreEnv. func (env Environment) DecodeStrict(prefix, sep string, v interface{}, ignoreEnv map[string]interface{}) error { var fields []string if err := env.decode(prefix, sep, v, &fields); err != nil { return err } getEnv: for key := range env { if !hasPrefixFold(key, prefix) { continue } if _, ok := ignoreEnv[key]; ok { continue } for _, field := range fields { if strings.EqualFold(key, field) { continue getEnv } } for field := range ignoreEnv { if strings.EqualFold(key, field) { continue getEnv } } return fmt.Errorf("Unrecognized environment variable '%s'", key) } return nil }
// checks if partial is any of the words or phrases within whole func phrasesMatch(partial, whole string) bool { // create words of whole words := strings.Fields(whole) // tag partial apart and put it back together with standard space partials := strings.Fields(partial) partialWords := len(partials) partial = strings.Join(partials, " ") // check if partial matches any of whole's phrases for i := 0; (i + partialWords) <= len(words); i++ { slidingBit := strings.Join(words[i:(i+partialWords)], " ") if strings.EqualFold(slidingBit, partial) { return true } if strings.HasSuffix(slidingBit, "'s") { if strings.EqualFold(strings.TrimSuffix(slidingBit, "'s"), partial) { return true } } } return false }
func Read(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { requestType := r.FormValue("request_type") channelIdStr := r.FormValue("channel_id") userId := context.Get(r, "user_id").(int) var channelDetails []channeldetail.ChannelDetail if strings.EqualFold(requestType, "id") { channelDetails = channeldetail.Read(userId) } else if strings.EqualFold(requestType, "channel") { if helper.IsValidRequest(channelIdStr) { channelId, _ := strconv.Atoi(channelIdStr) channelDetails = channeldetail.ReadByChannel(channelId) } } else { channelDetails = nil } if channelDetails != nil { responseJson, responseCode := helper.GetResponseJson(channelDetails) middleware.Output.Response = responseJson middleware.Output.ResponseCode = responseCode } else { middleware.Output.ResponseCode = http.StatusBadRequest } }
func syslogStreamer(target Target, types []string, logstream chan *Log) { typestr := "," + strings.Join(types, ",") + "," for logline := range logstream { if typestr != ",," && !strings.Contains(typestr, logline.Type) { continue } tag, pid := getLogName(logline.Name) var conn net.Conn if strings.EqualFold(target.Protocol, "tcp") { addr, err := net.ResolveTCPAddr("tcp", target.Addr) assert(err, "syslog") tcpconn, err := net.DialTCP("tcp", nil, addr) assert(err, "syslog") assert(tcpconn.SetWriteBuffer(1048576), "syslog") conn = tcpconn } else if strings.EqualFold(target.Protocol, "udp") { addr, err := net.ResolveUDPAddr("udp", target.Addr) assert(err, "syslog") udpconn, err := net.DialUDP("udp", nil, addr) assert(err, "syslog") assert(udpconn.SetWriteBuffer(1048576), "syslog") conn = udpconn } else { assert(fmt.Errorf("%s is not a supported protocol, use either udp or tcp", target.Protocol), "syslog") } // HACK: Go's syslog package hardcodes the log format, so let's send our own message _, err := fmt.Fprintf(conn, "%s %s[%s]: %s", time.Now().Format(getopt("DATETIME_FORMAT", dtime.DeisDatetimeFormat)), tag, pid, logline.Data) assert(err, "syslog") } }
func chackDqsjAccount(ctx *context.Context) (bool, string) { ck, err := ctx.Request.Cookie(DQSJ_USERNAME) if err != nil { return false, "" } username := ck.Value ck, err = ctx.Request.Cookie(DQSJ_PASSWORD) if err != nil { return false, "" } password := ck.Value admin, err := models.GetOneDqsjAdmin(username) beego.Debug("GetOneDqsjAdmin admin:", admin) if err != nil { return false, "" } if admin != nil && strings.EqualFold(username, admin.Username) && strings.EqualFold(password, admin.Password) { beego.Debug(" cookie username ", username) return true, username } else { return false, username } }
func testCgroupspath(linuxSpec *specs.LinuxSpec, linuxRuntimeSpec *specs.LinuxRuntimeSpec) (string, error) { configFile := "./config.json" runtimeFile := "./runtime.json" // check whether the container mounts Cgroup filesystem and get the mount point hasCgFs := false var cgmnt string for k, v := range linuxRuntimeSpec.RuntimeSpec.Mounts { if strings.EqualFold(v.Type, "cgroup") { hasCgFs = true for _, u := range linuxSpec.Spec.Mounts { if strings.EqualFold(u.Name, k) { cgmnt = u.Path } } } } if hasCgFs == false { return manager.UNSPPORTED, errors.New("Container doesn't support cgroup") } linuxSpec.Spec.Process.Args = []string{"/bin/bash", "-c", "find " + cgmnt + "/ -name " + linuxRuntimeSpec.Linux.CgroupsPath} err := configconvert.LinuxSpecToConfig(configFile, linuxSpec) err = configconvert.LinuxRuntimeToConfig(runtimeFile, linuxRuntimeSpec) out, err := adaptor.StartRunc(configFile, runtimeFile) if err != nil { return manager.UNKNOWNERR, errors.New("StartRunc error :" + out + "," + err.Error()) } else if strings.Contains(out, linuxRuntimeSpec.Linux.CgroupsPath) { return manager.PASSED, nil } else { return manager.FAILED, errors.New("may be NOT SUPPORT setting cgrouppath") } }
func getConnectionToken(try int, tokenReq *rclient.HostApiProxyToken, rancherClient *rclient.RancherClient) (*rclient.HostApiProxyToken, error) { if try >= maxWaitOnHostTries { return nil, fmt.Errorf("Reached max retry attempts for getting token.") } tokenResponse, err := rancherClient.HostApiProxyToken.Create(tokenReq) if err != nil { if apiError, ok := err.(*rclient.ApiError); ok { if apiError.StatusCode == 422 { parsed := &ParsedError{} if uErr := json.Unmarshal([]byte(apiError.Body), &parsed); uErr == nil { if strings.EqualFold(parsed.Code, "InvalidReference") && strings.EqualFold(parsed.FieldName, "reportedUuid") { logrus.WithField("reportedUuid", config.Config.HostUuid).WithField("Attempt", try).Infof("Host not registered yet. Sleeping 1 second and trying again.") time.Sleep(time.Second) try += 1 return getConnectionToken(try, tokenReq, rancherClient) // Recursion! } } else { return nil, uErr } } else if apiError.StatusCode == 501 { logrus.Infof("Host-api proxy disabled. Will not connect.") return nil, nil } return nil, err } } return tokenResponse, nil }
func GenerateKey(passpharse []byte, config ConfigType) (err error) { pubBlock, priBlock, err := _generateKey(passpharse, config) if err != nil { return } pubkeyOut, err := os.OpenFile(config.PublicKeyDir, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { if strings.EqualFold(config.PublicKeyDir, "") { pubkeyOut = os.Stdout } else { return } } prikeyOut, err := os.OpenFile(config.PrivateKeyDir, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { if strings.EqualFold(config.PrivateKeyDir, "") { prikeyOut = os.Stdout } else { return } } err = pem.Encode(pubkeyOut, pubBlock) if err != nil { return } err = pem.Encode(prikeyOut, priBlock) return }
// ParseContent asserts that Transmission.Content is valid. func ParseContent(content interface{}) (err error) { switch rVal := content.(type) { case map[string]interface{}: for k, v := range rVal { switch vVal := v.(type) { case string: if strings.EqualFold(k, "template_id") { return nil } default: return fmt.Errorf("Transmission.Content objects must contain string values, not [%s]", reflect.TypeOf(vVal)) } } return fmt.Errorf("Transmission.Content objects must contain a key `template_id`") case map[string]string: for k, _ := range rVal { if strings.EqualFold(k, "template_id") { return nil } } return fmt.Errorf("Transmission.Content objects must contain a key `template_id`") case Content: te := &Template{Name: "tmp", Content: rVal} return te.Validate() default: return fmt.Errorf("Unsupported Transmission.Content type [%s]", reflect.TypeOf(rVal)) } return }
func TestEcKeyErrors(t *testing.T) { k := Key{ module: &mockCtx{}, tokenLabel: "token label", pin: "unused", } // Trying to load private EC key with no public key err := k.setup("no_public_key_ec") if err == nil { t.Errorf("Unexpected success") } if !strings.EqualFold(err.Error(), "public key not found") { t.Errorf("Unexpected error value: %v", err) } // Trying to load private EC key with invalid EC point err = k.setup("invalid_ec_point") if err == nil { t.Errorf("Unexpected success") } if !strings.EqualFold(err.Error(), "invalid EC Point") { t.Errorf("Unexpected error value: %v", err) } }
/** * Exclude sources that look private (e.g., start with '.', '_'; are a directory known * to be used by a dependency manager; are a test file (with suffix '_test.go'); or are * otherwise known to be problematic for some reason) */ func looksPrivateSourceFilter(n string) bool { ts := "_test.go" base := path.Base(n) switch { case len(base) < 1 || base[0] == '.' || base[0] == '_': return false case len(base) > len(ts) && strings.EqualFold(base[:len(base)-len(ts)], ts): return false case strings.EqualFold(base, "vendor"): return false case strings.EqualFold(base, "Godep"): return false case strings.EqualFold(base, "third_party"): return false case strings.EqualFold(base, "pkg"): return false } for _, e := range defaultExcludePackages { if strings.HasSuffix(n, e) { return false } } return true }
func ScrapeTeamsForEvent(eventCode string, year int) ([]string, error) { var url string for event := range cmpStrings { if strings.EqualFold(strings.ToLower(eventCode), event) { url = fmt.Sprintf("https://my.usfirst.org/myarea/index.lasso?page=teamlist&event_type=FRC&sort_teams=number&year=%d&event=cmp&division=%s", year, cmpStrings[event]) break } } if strings.EqualFold(url, "") { url = fmt.Sprintf("https://my.usfirst.org/myarea/index.lasso?page=teamlist&event_type=FRC&sort_teams=number&year=%d&event=%s", year, eventCode) } doc, err := getDoc(url) if err != nil { return nil, err } tds := doc.Find("tr").FilterFunction(func(i int, s *goquery.Selection) bool { t := s.Find("td") return t.Length() > 0 }) if tds.Length() <= 3 { return nil, ErrNoData } m := []string{} tds.Slice(3, tds.Length()).Each(func(i int, s *goquery.Selection) { info := s.Find("td") team := trimWhitespace(info.Eq(2).Text()) m = append(m, team) }) return m, nil }
// Handles returns whether this plugin will handle the given parameters func (plugin *wf) Handles(req *comm.Request) bool { if len(req.Arguments) < 3 || len(req.Arguments) > 5 { return false } if !strings.EqualFold(req.Arguments[0], "vro") { return false } if !strings.EqualFold(req.Arguments[1], "workflow") && !strings.EqualFold(req.Arguments[1], "wf") { return false } if _, err := strconv.Atoi(req.Arguments[2]); err != nil { return false } if len(req.Arguments) > 3 && !strings.EqualFold(req.Arguments[3], "ob") && !strings.EqualFold(req.Arguments[3], "sb") { return false } return true }
func (c *Context) LoadStack() (*client.Stack, error) { if c.Stack != nil { return c.Stack, nil } projectName := c.sanitizedProjectName() if _, err := c.loadClient(); err != nil { return nil, err } logrus.Debugf("Looking for stack %s", projectName) // First try by name stacks, err := c.Client.Stack.List(&client.ListOpts{ Filters: map[string]interface{}{ "name": projectName, "removed_null": nil, }, }) if err != nil { return nil, err } for _, stack := range stacks.Data { if strings.EqualFold(projectName, stack.Name) { logrus.Debugf("Found stack: %s(%s)", stack.Name, stack.Id) c.Stack = &stack return c.Stack, nil } } // Now try not by name for case sensitive databases stacks, err = c.Client.Stack.List(&client.ListOpts{ Filters: map[string]interface{}{ "removed_null": nil, }, }) if err != nil { return nil, err } for _, stack := range stacks.Data { if strings.EqualFold(projectName, stack.Name) { logrus.Debugf("Found stack: %s(%s)", stack.Name, stack.Id) c.Stack = &stack return c.Stack, nil } } logrus.Infof("Creating stack %s", projectName) stack, err := c.Client.Stack.Create(&client.Stack{ Name: projectName, }) if err != nil { return nil, err } c.Stack = stack return c.Stack, nil }
func HandleMessage(ws *WSConn, ch <-chan Message) { defer log.Println("loop closed somehow") channels := slurpFile("channels.txt") for { m := <-ch d := s.Split(m.Data, " ") ld := s.Split(s.ToLower(m.Data), " ") if m.Nick == "dbc__" || m.Nick == "tenseyi" { switch m.Command { case "MSG": if s.EqualFold(d[0], "!join") { if !inSlice(ld[1], channels) { channels = append(channels, ld[1]) writeFile("channels.txt", channels) ws.Write("JOIN #" + ld[1]) ws.Write("PRIVMSG #" + m.Channel + " :Logging " + ld[1]) } ws.Write("PRIVMSG #" + m.Channel + " :Already logging " + ld[1]) continue } if s.EqualFold(d[0], "!leave") { if inSlice(ld[1], channels) { channels = remove(ld[1], channels) writeFile("channels.txt", channels) ws.Write("PART #" + ld[1]) ws.Write("PRIVMSG #" + m.Channel + " :Leaving " + ld[1]) } } } } } }
// parseMeta looks for the first meta tag in the given reader that // will give us the source URL. func (g *HttpGetter) parseMeta(r io.Reader) (string, error) { d := xml.NewDecoder(r) d.CharsetReader = charsetReader d.Strict = false var err error var t xml.Token for { t, err = d.Token() if err != nil { if err == io.EOF { err = nil } return "", err } if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") { return "", nil } if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") { return "", nil } e, ok := t.(xml.StartElement) if !ok || !strings.EqualFold(e.Name.Local, "meta") { continue } if attrValue(e.Attr, "name") != "terraform-get" { continue } if f := attrValue(e.Attr, "content"); f != "" { return f, nil } } }
func (d DigitalOceanClient) Image(slug_or_name_or_id string) (Image, error) { images, err := d.Images() if err != nil { return Image{}, err } for _, image := range images { if strings.EqualFold(image.Slug, slug_or_name_or_id) { return image, nil } } for _, image := range images { if strings.EqualFold(image.Name, slug_or_name_or_id) { return image, nil } } for _, image := range images { id, err := strconv.Atoi(slug_or_name_or_id) if err == nil { if image.Id == uint(id) { return image, nil } } } err = errors.New(fmt.Sprintf("Unknown image '%v'", slug_or_name_or_id)) return Image{}, err }
func (a *h2i) cmdSettings(args []string) error { if len(args) == 1 && strings.EqualFold(args[0], "ACK") { return a.framer.WriteSettingsAck() } var settings []http2.Setting for _, arg := range args { if strings.EqualFold(arg, "ACK") { a.logf("Error: ACK must be only argument with the SETTINGS command") return nil } eq := strings.Index(arg, "=") if eq == -1 { a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) return nil } sid, ok := settingByName(arg[:eq]) if !ok { a.logf("Error: unknown setting name %q", arg[:eq]) return nil } val, err := strconv.ParseUint(arg[eq+1:], 10, 32) if err != nil { a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) return nil } settings = append(settings, http2.Setting{ ID: sid, Val: uint32(val), }) } a.logf("Sending: %v", settings) return a.framer.WriteSettings(settings...) }
func (d DigitalOceanClient) Region(slug_or_name_or_id string) (Region, error) { regions, err := d.Regions() if err != nil { return Region{}, err } for _, region := range regions { if strings.EqualFold(region.Slug, slug_or_name_or_id) { return region, nil } } for _, region := range regions { if strings.EqualFold(region.Name, slug_or_name_or_id) { return region, nil } } for _, region := range regions { id, err := strconv.Atoi(slug_or_name_or_id) if err == nil { if region.Id == uint(id) { return region, nil } } } err = errors.New(fmt.Sprintf("Unknown region '%v'", slug_or_name_or_id)) return Region{}, err }
func TestReadConfig(t *testing.T) { if config, err := ReadConfig("config_for_test.json"); err != nil { t.Error(err) } else if !strings.EqualFold(config.ApplicationId, "1939") || !strings.EqualFold(config.ApiKey, "SuperSecretAPIKey") { t.Error("Config not parsed correctly") } }
func (d DigitalOceanClient) Size(slug_or_name_or_id string) (Size, error) { sizes, err := d.Sizes() if err != nil { return Size{}, err } for _, size := range sizes { if strings.EqualFold(size.Slug, slug_or_name_or_id) { return size, nil } } for _, size := range sizes { if strings.EqualFold(size.Name, slug_or_name_or_id) { return size, nil } } for _, size := range sizes { id, err := strconv.Atoi(slug_or_name_or_id) if err == nil { if size.Id == uint(id) { return size, nil } } } err = errors.New(fmt.Sprintf("Unknown size '%v'", slug_or_name_or_id)) return Size{}, err }
func (d *WordDecoder) convert(buf *bytes.Buffer, charset string, content []byte) error { switch { case strings.EqualFold("utf-8", charset): buf.Write(content) case strings.EqualFold("iso-8859-1", charset): for _, c := range content { buf.WriteRune(rune(c)) } case strings.EqualFold("us-ascii", charset): for _, c := range content { if c >= utf8.RuneSelf { buf.WriteRune(unicode.ReplacementChar) } else { buf.WriteByte(c) } } default: if d.CharsetReader == nil { return fmt.Errorf("mime: unhandled charset %q", charset) } r, err := d.CharsetReader(strings.ToLower(charset), bytes.NewReader(content)) if err != nil { return err } if _, err = buf.ReadFrom(r); err != nil { return err } } return nil }
func (fc *TtfFonts) Select(family, weight, style string, ranges []string) (fontMetrics font.FontMetrics, err error) { var ws string if weight != "" && style != "" { ws = weight + " " + style } else if weight == "" && style == "" { ws = "Regular" } else if style == "" { ws = weight } else if weight == "" { ws = style } if fc.fonts == nil { fc.fonts = make(map[string]*ttf.Font) } search: for _, f := range fc.FontInfos { if strings.EqualFold(f.Family(), family) && strings.EqualFold(f.Style(), ws) { for _, r := range ranges { cpr, ok := ttf.CodepointRangesByName[r] if !ok || !f.CharRanges().IsSet(int(cpr.Bit)) { continue search } } font := fc.fonts[f.Filename] if font == nil { font, err = ttf.LoadFont(f.Filename) fc.fonts[f.Filename] = font } fontMetrics = font return } } err = fmt.Errorf("Font %s %s not found", family, ws) return }
func (self *CutHandler) Base(w http.ResponseWriter, r *http.Request, g kernel.G, text string, mode string) { type Value struct { Text string `json:"text"` Pos string `json:"pos"` } segmenter, _ := g.DIY["seg"].(search.SearchSegmenter) //通用处理方法 if text == "" || (!strings.EqualFold(mode, "1") && !strings.EqualFold(mode, "0")) { self.JsonResponse(w, nil, 401) } else { //整理为输出格式 s := []*Value{} //开始分词 func() { for _, seg := range segmenter.Cut([]byte(text), func() bool { if mode == "1" { return true } else { return false } }()) { s = append(s, &Value{ Text: seg.GetToken().GetText(), Pos: seg.GetToken().GetPos(), }) } }() self.JsonResponse(w, s, 200) } }
func getUpdateColumns(t table.Table, assignList []expression.Assignment, isMultipleTable bool, tblAliasMap map[string]string) ([]*column.Col, []expression.Assignment, error) { // TODO: We should check the validate if assignList in somewhere else. Maybe in building plan. // TODO: We should use field.GetFieldIndex to replace this function. tcols := make([]*column.Col, 0, len(assignList)) tAsgns := make([]expression.Assignment, 0, len(assignList)) tname := t.TableName() for _, asgn := range assignList { if isMultipleTable { if tblAliasMap != nil { if alias, ok := tblAliasMap[asgn.TableName]; ok { if !strings.EqualFold(tname.O, alias) { continue } } } else if !strings.EqualFold(tname.O, asgn.TableName) { continue } } col := column.FindCol(t.Cols(), asgn.ColName) if col == nil { if isMultipleTable { continue } return nil, nil, errors.Errorf("UPDATE: unknown column %s", asgn.ColName) } tcols = append(tcols, col) tAsgns = append(tAsgns, asgn) } return tcols, tAsgns, nil }