Ejemplo n.º 1
0
func (bnd *bndBool) bind(value bool, position int, c StmtCfg, stmt *Stmt) (err error) {
	//Log.Infof("%s.bind(%t, %d)", bnd, value, position)
	bnd.stmt = stmt
	var str string
	if value {
		str, err = strconv.Unquote(strconv.QuoteRune(c.TrueRune))
	} else {
		str, err = strconv.Unquote(strconv.QuoteRune(c.FalseRune))
	}
	if err != nil {
		return err
	}
	bnd.cString = C.CString(str)
	r := C.OCIBINDBYPOS(
		bnd.stmt.ocistmt,            //OCIStmt      *stmtp,
		(**C.OCIBind)(&bnd.ocibnd),  //OCIBind      **bindpp,
		bnd.stmt.ses.srv.env.ocierr, //OCIError     *errhp,
		C.ub4(position),             //ub4          position,
		unsafe.Pointer(bnd.cString), //void         *valuep,
		C.LENGTH_TYPE(1),            //sb8          value_sz,
		C.SQLT_AFC,                  //ub2          dty,
		nil,                         //void         *indp,
		nil,                         //ub2          *alenp,
		nil,                         //ub2          *rcodep,
		0,                           //ub4          maxarr_len,
		nil,                         //ub4          *curelep,
		C.OCI_DEFAULT)               //ub4          mode );
	if r == C.OCI_ERROR {
		return bnd.stmt.ses.srv.env.ociError()
	}
	return nil
}
Ejemplo n.º 2
0
// validateProjectTaskIdsAndTags ensures that task tags and ids only contain valid characters
func validateProjectTaskIdsAndTags(project *model.Project) []ValidationError {
	errs := []ValidationError{}
	// create a map to hold the task names
	for _, task := range project.Tasks {
		// check task name
		if i := strings.IndexAny(task.Name, model.InvalidCriterionRunes); i == 0 {
			errs = append(errs, ValidationError{
				Message: fmt.Sprintf("task '%v' has invalid name: starts with invalid character %v",
					task.Name, strconv.QuoteRune(rune(task.Name[0])))})
		}
		// check tag names
		for _, tag := range task.Tags {
			if i := strings.IndexAny(tag, model.InvalidCriterionRunes); i == 0 {
				errs = append(errs, ValidationError{
					Message: fmt.Sprintf("task '%v' has invalid tag '%v': starts with invalid character %v",
						task.Name, tag, strconv.QuoteRune(rune(tag[0])))})
			}
			if i := util.IndexWhiteSpace(tag); i != -1 {
				errs = append(errs, ValidationError{
					Message: fmt.Sprintf("task '%v' has invalid tag '%v': tag contains white space",
						task.Name, tag)})
			}
		}
	}
	return errs
}
Ejemplo n.º 3
0
func Test한글(t *testing.T) {
	h := "한글"
	assert.Equal(t, 6, len(h))
	assert.Equal(t, 2, utf8.RuneCountInString(h))
	assert.Equal(t, []string{"한", "글"}, strings.Split(h, ""))
	assert.True(t, strings.Contains(h, "한"))
	assert.True(t, strings.Contains(h, "글"))
	assert.True(t, strings.ContainsRune(h, '한'))
	assert.True(t, strings.ContainsRune(h, '글'))
	runes := []rune(h)
	assert.Equal(t, []int32{54620, 44544}, runes)
	assert.Equal(t, "[]int32", reflect.TypeOf(runes).String())
	assert.Equal(t, "int32", reflect.TypeOf(runes[0]).String())
	r := reflect.ValueOf(runes[0])
	assert.Equal(t, "reflect.Value", reflect.TypeOf(r).String())
	assert.Equal(t, "int32", r.Type().String())
	assert.Equal(t, reflect.Int32, r.Kind())
	for i, c := range h {
		assert.True(t, strings.Contains(h, string(c)))
		assert.True(t, strings.ContainsRune(h, c))
		assert.Equal(t, "int32", reflect.TypeOf(c).String())
		assert.Equal(t, "int32", reflect.TypeOf(rune(c)).String())
		assert.Equal(t, "string", reflect.TypeOf(strconv.QuoteRune(c)).String())
		if 0 == i {
			assert.True(t, 54620 == c)
			assert.Equal(t, "한", string(c))
			assert.Equal(t, "'한'", strconv.QuoteRune(c))
		}
	}
}
Ejemplo n.º 4
0
func init() {
	for k, v := range xc.PrintHooks {
		printHooks[k] = v
	}
	lcRT := reflect.TypeOf(lex.Char{})
	lcH := func(f strutil.Formatter, v interface{}, prefix, suffix string) {
		c := v.(lex.Char)
		r := c.Rune
		s := yySymName(int(r))
		if x := s[0]; x >= '0' && x <= '9' {
			s = strconv.QuoteRune(r)
		}
		f.Format("%s%v: %s"+suffix, prefix, xc.FileSet.Position(c.Pos()), s)
	}
	printHooks[lcRT] = lcH
	printHooks[reflect.TypeOf(xc.Token{})] = func(f strutil.Formatter, v interface{}, prefix, suffix string) {
		t := v.(xc.Token)
		if !t.Pos().IsValid() {
			return
		}

		lcH(f, t.Char, prefix, "")
		if s := xc.Dict.S(t.Val); len(s) != 0 {
			f.Format(" %q", s)
		}
		f.Format(suffix)
	}
}
Ejemplo n.º 5
0
Archivo: dump.go Proyecto: h12w/gombi
func escapeCharset(r rune) string {
	switch r {
	case '[', ']', '-':
		return `\` + string(r)
	}
	return strings.Trim(strconv.QuoteRune(r), `'`)
}
Ejemplo n.º 6
0
Archivo: dump.go Proyecto: h12w/gombi
func escapeLiteral(r rune) string {
	switch r {
	case '(', ')', '[', ']', '-', '{', '}', '+', '*', '?':
		return `\` + string(r)
	}
	return strings.Trim(strconv.QuoteRune(r), `'`)
}
Ejemplo n.º 7
0
func TestParseToInvocation(t *testing.T) {
	ti := time.Time{}
	sync := strconv.QuoteRune(Syncd)

	sample := sync + "" + ti.Format(time.UnixDate) +
		"sorenlaptopbash/home/soren/src/project" +
		"git log --graph --abbrev-commit --decorate --date=relative --all" +
		"[git log graph]0\n"

	expect := IndexEntry{}
	expect.User = "******"
	expect.Host = "laptop"
	expect.Shell = "bash"
	expect.Timestamp = ti
	expect.Directory = "/home/soren/src/project"
	expect.Command = "git log --graph --abbrev-commit --decorate --date=relative --all"
	expect.Tags = []string{"git", "log", "graph"}
	expect.Status = 0
	expect.HasStatus = true
	expect.IsSynced = true

	res, err := parseToEntry(sample)
	if err != nil {
		t.Fail()
	}

	expectedStr := fmt.Sprint(expect)
	resultStr := fmt.Sprint(res)

	if expectedStr != resultStr {
		t.Fail()
	}

}
Ejemplo n.º 8
0
func ExampleQuoteRune() {
	s := strconv.QuoteRune('☺')
	fmt.Println(s)

	// Output:
	// '☺'
}
Ejemplo n.º 9
0
func (j *job) str(expr ebnf.Expression) (s string) {
	switch x := expr.(type) {
	case nil:
		return "/* EMPTY */"
	case *ebnf.Name:
		switch name := x.String; ast.IsExported(name) {
		case true:
			return name
		default:
			return j.term2name[name]
		}
	case ebnf.Sequence:
		a := []string{}
		for _, v := range x {
			a = append(a, j.str(v))
		}
		return strings.Join(a, " ")
	case *ebnf.Token:
		switch s := x.String; len(s) {
		case 1:
			return strconv.QuoteRune(rune(s[0]))
		default:
			hint := ""
			if _, ok := j.rep.Literals[s]; ok && toAscii(s) == "" {
				hint = fmt.Sprintf(" /* %q */", s)
			}
			return fmt.Sprintf("%s%s", j.term2name[s], hint)
		}
	default:
		log.Fatalf("%T(%#v)", x, x)
		panic("unreachable")
	}
}
Ejemplo n.º 10
0
//  cprotect returns its argument if printable, else a backslash form.
func cprotect(r rune) string {
	if strconv.IsPrint(r) {
		return string(r)
	} else {
		s := strconv.QuoteRune(r)
		return s[1 : len(s)-1]
	}
}
Ejemplo n.º 11
0
// aborts the attempt if a desired character is not a valid base32 digit
func checkPlausible() {
	for _, r := range prefix {
		if !strings.ContainsRune(alphabet, r) {
			fmt.Printf("Invalid prefix: %s is not in the base32 alphabet\n", strconv.QuoteRune(r))
			os.Exit(1)
		}
	}
}
Ejemplo n.º 12
0
func main() {
	filename := "C-large-practice.in"
	lines, err := readLines(filename)
	if err != nil {
		log.Fatalf("readLines: %s", err)
	}
	keyOf := map[string]string{
		"a": "2",
		"b": "22",
		"c": "222",
		"d": "3",
		"e": "33",
		"f": "333",
		"g": "4",
		"h": "44",
		"i": "444",
		"j": "5",
		"k": "55",
		"l": "555",
		"m": "6",
		"n": "66",
		"o": "666",
		"p": "7",
		"q": "77",
		"r": "777",
		"s": "7777",
		"t": "8",
		"u": "88",
		"v": "888",
		"w": "9",
		"x": "99",
		"y": "999",
		"z": "9999",
		" ": "0",
	}

	testCases, err := strconv.Atoi(lines[0])
	var s []string
	ans, pre := "", ""

	for i := 1; i <= testCases; i++ {
		pre, ans = "", ""
		for _, rune := range lines[i] {
			indx, _ := strconv.Unquote(strconv.QuoteRune(rune))
			letterKey := keyOf[indx]
			if pre == strconv.Itoa(int(letterKey[0])) {
				ans += " "
			}
			ans += letterKey
			pre = strconv.Itoa(int(letterKey[0]))
		}
		s = append(s, "Case #"+strconv.Itoa(i)+": "+ans)
	}

	if err := writeLines(s, "C-small-practice.out"); err != nil {
		log.Fatalf("Error!", err)
	}
}
Ejemplo n.º 13
0
// fmt_qc formats the integer as a single-quoted, escaped Go character constant.
// If the character is not valid Unicode, it will print '\ufffd'.
func (f *fmt) fmt_qc(c int64) {
	var quoted string
	if f.plus {
		quoted = strconv.QuoteRuneToASCII(int(c))
	} else {
		quoted = strconv.QuoteRune(int(c))
	}
	f.padString(quoted)
}
Ejemplo n.º 14
0
Archivo: dump.go Proyecto: h12w/dfa
func quote(b byte) string {
	switch b {
	case '\'', '"', '`':
		return string(rune(b))
	}
	if b < utf8.RuneSelf && strconv.IsPrint(rune(b)) {
		return strconv.QuoteRune(rune(b))
	}
	return fmt.Sprintf(`%.2x`, b)
}
Ejemplo n.º 15
0
// trimHash slices a hash # from the link
func trimHash(l string) string {
	if strings.Contains(l, "#") {
		var index int
		for n, str := range l {
			if strconv.QuoteRune(str) == "'#'" {
				index = n
				break
			}
		}
		return l[:index]
	}
	return l
}
Ejemplo n.º 16
0
Archivo: link.go Proyecto: rakoo/psgb
func nextParams(toParse *bufio.Reader) (key, value string, endOfParams bool, err error) {

	endOfParams = false

	var paramKey bytes.Buffer
	for {
		r, _, err := toParse.ReadRune()
		if err != nil {
			return "", "", true, err
		}
		if strconv.QuoteRune(r) == "'='" {
			break
		}
		paramKey.WriteRune(r)
	}
	key = strings.Trim(paramKey.String(), "\" ")

	var paramValue bytes.Buffer
	for {
		r, _, err := toParse.ReadRune()
		if err != nil {
			if err != io.EOF {
				return "", "", true, err
			}
		}
		if strconv.QuoteRune(r) == "','" {
			endOfParams = true
		}

		if strconv.QuoteRune(r) == "';'" || strconv.QuoteRune(r) == "','" || err == io.EOF {
			break
		}

		paramValue.WriteRune(r)
	}
	value = strings.Trim(paramValue.String(), "\" ")

	return
}
Ejemplo n.º 17
0
func oneSkinke(condition int, word string) string {
	switch condition {
	case scFullUpper:
		word = strings.ToUpper(word)
	case scCapitalised:
		// Get first rune
		r, s := utf8.DecodeRuneInString(word)
		rs := strconv.QuoteRune(unicode.ToUpper(r))
		// And put it together with the word.
		word = rs[1:len(rs)-1] + word[s:]
	}
	return word
}
Ejemplo n.º 18
0
func getEscapedRuneIfValid(element rune) rune {
	allEscapeChars := map[string]rune{"t": '\t', "n": '\n'}
	elementToStr, err := strconv.Unquote(strconv.QuoteRune(element))
	if err != nil {
		return element
	}
	for key, val := range allEscapeChars {
		if key == elementToStr {
			return val
		}
	}
	return element
}
Ejemplo n.º 19
0
func init() {
	var driverOption DriverOption
	flag.BoolVar(&driverOption.ShouldStart, "glow", false, "start in driver mode")
	flag.StringVar(&driverOption.Leader, "glow.leader", "localhost:8930", "leader server")
	flag.StringVar(&driverOption.DataCenter, "glow.dataCenter", "", "preferred data center name")
	flag.StringVar(&driverOption.Rack, "glow.rack", "", "preferred rack name")
	flag.IntVar(&driverOption.TaskMemoryMB, "glow.task.memoryMB", 64, "request one task memory size in MB")
	flag.Float64Var(&driverOption.FlowBid, "glow.flow.bid", 100.0, "total bid price in a flow to compete for resources")
	flag.BoolVar(&driverOption.PlotOutput, "glow.flow.plot", false, "print out task group flow in graphviz dot format")
	flag.StringVar(&driverOption.Module, "glow.module", "", "a name to group related jobs together on agent")
	flag.StringVar(&driverOption.RelatedFiles, "glow.related.files", "", strconv.QuoteRune(os.PathListSeparator)+" separated list of files")

	flow.RegisterContextRunner(NewFlowContextDriver(&driverOption))
}
Ejemplo n.º 20
0
// rewrite rewrites a subname to having only printable characters and no white
// space.
func rewrite(s string) string {
	b := []byte{}
	for _, r := range s {
		switch {
		case isSpace(r):
			b = append(b, '_')
		case !strconv.IsPrint(r):
			s := strconv.QuoteRune(r)
			b = append(b, s[1:len(s)-1]...)
		default:
			b = append(b, string(r)...)
		}
	}
	return string(b)
}
Ejemplo n.º 21
0
//listUsables lists all the items that have an effect, and prompts the user to use one.
func (g *Game) listUsables() {
	letter := 'a'
	listText, _ := sf.NewText(Font)
	listText.SetCharacterSize(12)
	listText.SetPosition(sf.Vector2f{12, 12})
	usables := make(map[rune]*Item)
	names := make(map[*Item]string)
	for k, i := range g.player.inventory {
		if i.effect != nil {
			appendString(listText, strconv.QuoteRune(letter)+" - "+k+" x"+strconv.Itoa(i.stack))
			usables[letter] = i
			names[i] = k
			letter++
		}
	}

listLoop:
	for g.window.IsOpen() {
		for event := g.window.PollEvent(); event != nil; event = g.window.PollEvent() {
			switch et := event.(type) {
			case sf.EventTextEntered:
				done, used := g.inventoryInput(et.Char, usables, names)
				if used != "" {
					usedI := g.player.inventory[used]
					if usedI.stack > 1 {
						usedI.stack--
						break listLoop
					}
					delete(g.player.inventory, used)
					break listLoop
				}
				if done {
					break listLoop
				}
			}
		}
		g.window.Clear(sf.ColorBlack())

		g.window.SetView(g.logView)
		g.drawLog()
		g.window.SetView(g.gameView)
		listText.Draw(g.window, sf.DefaultRenderStates())
		g.window.Display()
	}

	g.state = PLAY
}
Ejemplo n.º 22
0
// Lookup prints the decimal code at pressing a key.
func Lookup() {
	ter, err := term.New()
	if err != nil {
		log.Print(err)
		return
	}
	defer func() {
		if err = ter.Restore(); err != nil {
			log.Print(err)
		}
	}()

	if err = ter.RawMode(); err != nil {
		log.Print(err)
		return
	} else {
		buf := bufio.NewReader(term.Input)
		runes := make([]int32, 0)
		chars := make([]string, 0)

		fmt.Print("[Press Enter to exit]\r\n")
		fmt.Print("> ")

	L:
		for {
			rune_, _, err := buf.ReadRune()
			if err != nil {
				log.Print(err)
				continue
			}

			switch rune_ {
			default:
				fmt.Print(rune_, " ")
				runes = append(runes, rune_)
				char := strconv.QuoteRune(rune_)
				chars = append(chars, char[1:len(char)-1])
				continue

			case 13:
				fmt.Printf("\r\n\r\n%v\r\n\"%s\"\r\n", runes, strings.Join(chars, " "))
				break L
			}
		}
	}
}
Ejemplo n.º 23
0
func StringToDirsString(width int, s string) (string, error) {
	if width < 1 {
		return "", errors.New("Width cannot be less than zero")
	}
	dirs := ""
	for i, c := range s {
		if i != 0 && i%width == 0 {
			dirs += SLASH
		}
		ch, err := strconv.Unquote(strconv.QuoteRune(c))
		if err != nil {
			return "", err
		}
		dirs += ch
	}
	dirs += SLASH
	return filepath.FromSlash(dirs), nil
}
Ejemplo n.º 24
0
func init() {
	flag.BoolVar(&driverOption.ShouldStart, "glow", false, "start in driver mode")
	flag.StringVar(&driverOption.Leader, "glow.leader", "localhost:8930", "leader server")
	flag.StringVar(&driverOption.DataCenter, "glow.dataCenter", "", "preferred data center name")
	flag.StringVar(&driverOption.Rack, "glow.rack", "", "preferred rack name")
	flag.IntVar(&driverOption.TaskMemoryMB, "glow.task.memoryMB", 64, "request one task memory size in MB")
	flag.Float64Var(&driverOption.FlowBid, "glow.flow.bid", 100.0, "total bid price in a flow to compete for resources")
	flag.BoolVar(&driverOption.PlotOutput, "glow.flow.plot", false, "print out task group flow in graphviz dot format")
	flag.StringVar(&driverOption.Module, "glow.module", "", "a name to group related jobs together on agent")
	flag.StringVar(&driverOption.RelatedFiles, "glow.related.files", "", strconv.QuoteRune(os.PathListSeparator)+" separated list of files")
	flag.BoolVar(&driverOption.ShowFlowStats, "glow.flow.stat", false, "show flow details at the end of execution")
	flag.StringVar(&driverOption.Host, "glow.driver.host", "", "driver runs on this host address. Required in 2-way SSL mode.")
	flag.IntVar(&driverOption.Port, "glow.driver.port", 0, "driver listens on this port to copy files to agents. Required to specify and open this port.")
	flag.StringVar(&driverOption.CertFiles.CertFile, "cert.file", "", "A PEM eoncoded certificate file")
	flag.StringVar(&driverOption.CertFiles.KeyFile, "key.file", "", "A PEM encoded private key file")
	flag.StringVar(&driverOption.CertFiles.CaFile, "ca.file", "", "A PEM eoncoded CA's certificate file")

	flow.RegisterContextRunner(NewFlowContextDriver(&driverOption))
}
Ejemplo n.º 25
0
func (l *lexer) tokenBuilder(buf *bytes.Buffer) {
	in := l.Token()
	switch r := in[0].Rune; {
	case r == '\'':
		r := in[1].Rune
		if r == '\\' {
			l.byteValue(buf, in[1:], '"')
			return
		}

		if r == '\'' {
			l.errChar(in[1], "empty character literal or unescaped ' in character literal")
		}
		buf.WriteString(strconv.QuoteRune(r))
	default:
		for _, c := range in {
			buf.WriteRune(c.Rune)
		}
	}
}
Ejemplo n.º 26
0
func parseToEntry(line string) (e IndexEntry, err error) {
	tokens := strings.FieldsFunc(line, func(c rune) bool {
		return c == D
	})

	e = IndexEntry{}
	if tokens[0] == strconv.QuoteRune(Syncd) {
		e.IsSynced = true
	} else if tokens[0] == "U" {
		e.IsSynced = false
	} else {
		errstr := "Your gohst index file appears malformed with line:\n" + line
		return IndexEntry{}, errors.New(errstr)
	}

	e.Timestamp, err = time.Parse(UnixDate, tokens[1])
	if err != nil {
		return
	}
	e.User = tokens[2]
	e.Host = tokens[3]
	e.Shell = tokens[4]
	e.Directory = tokens[5]
	e.Command = tokens[6]
	e.Tags = strings.Fields(tokens[7][1 : len(tokens[7])-1])
	// if we have a command with no exit code, it means the shell probably
	// exited between logging context and logging exit code. This could happen
	// if the command was, for example, 'exit'. We assume it returned 0
	var exitcode int
	if len(tokens) < 9 {
		exitcode = 0
	} else {
		exitcode, err = strconv.Atoi(tokens[8])
		if err != nil {
			return
		}
	}
	e.Status = int8(exitcode)
	e.HasStatus = true
	return
}
Ejemplo n.º 27
0
// TestLookup prints the decimal code at pressing a key.
func TestLookup(t *testing.T) {
	term, err := terminal.New(InputFd)
	if err != nil {
		t.Fatal(err)
	}
	defer term.Restore()

	if err = term.MakeRaw(); err != nil {
		t.Error(err)
	} else {
		buf := bufio.NewReader(Input)
		runes := make([]int32, 0)
		chars := make([]string, 0)

		fmt.Print("[Press Enter to exit]\r\n")
		fmt.Print("> ")

	L:
		for {
			rune, _, err := buf.ReadRune()
			if err != nil {
				t.Error(err)
				continue
			}

			switch rune {
			default:
				fmt.Print(rune)
				runes = append(runes, rune)
				char := strconv.QuoteRune(rune)
				chars = append(chars, char[1:len(char)-1])
				continue

			case 13:
				fmt.Printf("\r\n\r\n%v\r\n\"%s\"\r\n\r\n", runes, strings.Join(chars, " "))
				break L
			}
		}
	}
}
Ejemplo n.º 28
0
Archivo: kv.go Proyecto: Alekc/log
func stringify(data interface{}) string {
	value := ""
	switch t := data.(type) {
	case bool:
		value = strconv.FormatBool(t)
	case rune:
		value = strconv.QuoteRune(t)
	case time.Time:
		value = t.UTC().Format(time.RFC3339)
	case int:
		value = strconv.Itoa(int(t))
	case fmt.Stringer:
		value = t.String()
	case string:
		value = strconv.Quote(t)
	case []string:
		value = strconv.Quote(strings.Join(t, ";"))
	default:
		value = "n/a"
	}
	return value
}
Ejemplo n.º 29
0
Archivo: lexer.go Proyecto: hansdude/di
func (self *lexerStuff) Next() Token {
	self.value = ""
	tok := self.s.Scan()
	if self.error != nil {
		return EOFTok
	}
	switch tok {
	case scanner.Ident:
		value := self.s.TokenText()
		self.current = identToToken(value)
		if self.current == IdentTok {
			self.value = value
		}

	case scanner.String:
		self.value = self.s.TokenText()
		self.current = StringTok

	case ',':
		self.current = CommaTok
	case '(':
		self.current = OpenParenTok
	case ')':
		self.current = CloseParenTok
	case '.':
		self.current = PeriodTok

	case scanner.EOF:
		self.current = EOFTok

	default:
		self.error = fmt.Errorf("Invalid token %s", strconv.QuoteRune(tok))
		self.current = EOFTok
	}
	return self.current
}
Ejemplo n.º 30
0
// RecordedKeyText returns a message indicating the key pressed, it's hz value and a timestamp of when it was received.
func RecordedKeyText(key rune, seconds int) string {
	return fmt.Sprintf("Recorded %v (%.2fhz) on %v \"%v\"", strconv.QuoteRune(key), CurrentHz(seconds), FormatTimer(seconds), Labels[key])
}