_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q19400 | CreateDispTypeInfo | train | func CreateDispTypeInfo(idata *INTERFACEDATA) (pptinfo *IUnknown, err error) {
hr, _, _ := procCreateDispTypeInfo.Call(
uintptr(unsafe.Pointer(idata)),
uintptr(GetUserDefaultLCID()),
uintptr(unsafe.Pointer(&pptinfo)))
if hr != 0 {
err = NewError(hr)
}
return
} | go | {
"resource": ""
} |
q19401 | copyMemory | train | func copyMemory(dest unsafe.Pointer, src unsafe.Pointer, length uint32) {
procCopyMemory.Call(uintptr(dest), uintptr(src), uintptr(length))
} | go | {
"resource": ""
} |
q19402 | GetUserDefaultLCID | train | func GetUserDefaultLCID() (lcid uint32) {
ret, _, _ := procGetUserDefaultLCID.Call()
lcid = uint32(ret)
return
} | go | {
"resource": ""
} |
q19403 | DispatchMessage | train | func DispatchMessage(msg *Msg) (ret int32) {
r0, _, _ := procDispatchMessageW.Call(uintptr(unsafe.Pointer(msg)))
ret = int32(r0)
return
} | go | {
"resource": ""
} |
q19404 | GetVariantDate | train | func GetVariantDate(value uint64) (time.Time, error) {
var st syscall.Systemtime
r, _, _ := procVariantTimeToSystemTime.Call(uintptr(value), uintptr(unsafe.Pointer(&st)))
if r != 0 {
return time.Date(int(st.Year), time.Month(st.Month), int(st.Day), int(st.Hour), int(st.Minute), int(st.Second), int(st.Milliseconds/1000), time.UTC), nil
}
return time.Now(), errors.New("Could not convert to time, passing current time.")
} | go | {
"resource": ""
} |
q19405 | String | train | func (e EXCEPINFO) String() string {
var src, desc, hlp string
if e.bstrSource == nil {
src = "<nil>"
} else {
src = BstrToString(e.bstrSource)
}
if e.bstrDescription == nil {
desc = "<nil>"
} else {
desc = BstrToString(e.bstrDescription)
}
if e.bstrHelpFile == nil {
hlp = "<nil>"
} else {
hlp = BstrToString(e.bstrHelpFile)
}
return fmt.Sprintf(
"wCode: %#x, bstrSource: %v, bstrDescription: %v, bstrHelpFile: %v, dwHelpContext: %#x, scode: %#x",
e.wCode, src, desc, hlp, e.dwHelpContext, e.scode,
)
} | go | {
"resource": ""
} |
q19406 | Error | train | func (e EXCEPINFO) Error() string {
if e.bstrDescription != nil {
return strings.TrimSpace(BstrToString(e.bstrDescription))
}
src := "Unknown"
if e.bstrSource != nil {
src = BstrToString(e.bstrSource)
}
code := e.scode
if e.wCode != 0 {
code = uint32(e.wCode)
}
return fmt.Sprintf("%v: %#x", src, code)
} | go | {
"resource": ""
} |
q19407 | GetSingleIDOfName | train | func (v *IDispatch) GetSingleIDOfName(name string) (displayID int32, err error) {
var displayIDs []int32
displayIDs, err = v.GetIDsOfName([]string{name})
if err != nil {
return
}
displayID = displayIDs[0]
return
} | go | {
"resource": ""
} |
q19408 | InvokeWithOptionalArgs | train | func (v *IDispatch) InvokeWithOptionalArgs(name string, dispatch int16, params []interface{}) (result *VARIANT, err error) {
displayID, err := v.GetSingleIDOfName(name)
if err != nil {
return
}
if len(params) < 1 {
result, err = v.Invoke(displayID, dispatch)
} else {
result, err = v.Invoke(displayID, dispatch, params...)
}
return
} | go | {
"resource": ""
} |
q19409 | CallMethod | train | func (v *IDispatch) CallMethod(name string, params ...interface{}) (*VARIANT, error) {
return v.InvokeWithOptionalArgs(name, DISPATCH_METHOD, params)
} | go | {
"resource": ""
} |
q19410 | GetProperty | train | func (v *IDispatch) GetProperty(name string, params ...interface{}) (*VARIANT, error) {
return v.InvokeWithOptionalArgs(name, DISPATCH_PROPERTYGET, params)
} | go | {
"resource": ""
} |
q19411 | PutProperty | train | func (v *IDispatch) PutProperty(name string, params ...interface{}) (*VARIANT, error) {
return v.InvokeWithOptionalArgs(name, DISPATCH_PROPERTYPUT, params)
} | go | {
"resource": ""
} |
q19412 | Create | train | func (c *Connection) Create(progId string) (err error) {
var clsid *GUID
clsid, err = CLSIDFromProgID(progId)
if err != nil {
clsid, err = CLSIDFromString(progId)
if err != nil {
return
}
}
unknown, err := CreateInstance(clsid, IID_IUnknown)
if err != nil {
return
}
c.Object = unknown
return
} | go | {
"resource": ""
} |
q19413 | Load | train | func (c *Connection) Load(names ...string) (errors []error) {
var tempErrors []error = make([]error, len(names))
var numErrors int = 0
for _, name := range names {
err := c.Create(name)
if err != nil {
tempErrors = append(tempErrors, err)
numErrors += 1
continue
}
break
}
copy(errors, tempErrors[0:numErrors])
return
} | go | {
"resource": ""
} |
q19414 | Dispatch | train | func (c *Connection) Dispatch() (object *Dispatch, err error) {
dispatch, err := c.Object.QueryInterface(IID_IDispatch)
if err != nil {
return
}
object = &Dispatch{dispatch}
return
} | go | {
"resource": ""
} |
q19415 | Call | train | func (d *Dispatch) Call(method string, params ...interface{}) (result *VARIANT, err error) {
id, err := d.GetId(method)
if err != nil {
return
}
result, err = d.Invoke(id, DISPATCH_METHOD, params)
return
} | go | {
"resource": ""
} |
q19416 | MustCall | train | func (d *Dispatch) MustCall(method string, params ...interface{}) (result *VARIANT) {
id, err := d.GetId(method)
if err != nil {
panic(err)
}
result, err = d.Invoke(id, DISPATCH_METHOD, params)
if err != nil {
panic(err)
}
return
} | go | {
"resource": ""
} |
q19417 | Get | train | func (d *Dispatch) Get(name string, params ...interface{}) (result *VARIANT, err error) {
id, err := d.GetId(name)
if err != nil {
return
}
result, err = d.Invoke(id, DISPATCH_PROPERTYGET, params)
return
} | go | {
"resource": ""
} |
q19418 | MustGet | train | func (d *Dispatch) MustGet(name string, params ...interface{}) (result *VARIANT) {
id, err := d.GetId(name)
if err != nil {
panic(err)
}
result, err = d.Invoke(id, DISPATCH_PROPERTYGET, params)
if err != nil {
panic(err)
}
return
} | go | {
"resource": ""
} |
q19419 | Set | train | func (d *Dispatch) Set(name string, params ...interface{}) (result *VARIANT, err error) {
id, err := d.GetId(name)
if err != nil {
return
}
result, err = d.Invoke(id, DISPATCH_PROPERTYPUT, params)
return
} | go | {
"resource": ""
} |
q19420 | MustSet | train | func (d *Dispatch) MustSet(name string, params ...interface{}) (result *VARIANT) {
id, err := d.GetId(name)
if err != nil {
panic(err)
}
result, err = d.Invoke(id, DISPATCH_PROPERTYPUT, params)
if err != nil {
panic(err)
}
return
} | go | {
"resource": ""
} |
q19421 | GetId | train | func (d *Dispatch) GetId(name string) (id int32, err error) {
var dispid []int32
dispid, err = d.Object.GetIDsOfName([]string{name})
if err != nil {
return
}
id = dispid[0]
return
} | go | {
"resource": ""
} |
q19422 | GetIds | train | func (d *Dispatch) GetIds(names ...string) (dispid []int32, err error) {
dispid, err = d.Object.GetIDsOfName(names)
return
} | go | {
"resource": ""
} |
q19423 | Invoke | train | func (d *Dispatch) Invoke(id int32, dispatch int16, params []interface{}) (result *VARIANT, err error) {
if len(params) < 1 {
result, err = d.Object.Invoke(id, dispatch)
} else {
result, err = d.Object.Invoke(id, dispatch, params...)
}
return
} | go | {
"resource": ""
} |
q19424 | Connect | train | func Connect(names ...string) (connection *Connection) {
connection.Initialize()
connection.Load(names...)
return
} | go | {
"resource": ""
} |
q19425 | safeArrayGetElementString | train | func safeArrayGetElementString(safearray *SafeArray, index int32) (str string, err error) {
var element *int16
err = convertHresultToError(
procSafeArrayGetElement.Call(
uintptr(unsafe.Pointer(safearray)),
uintptr(unsafe.Pointer(&index)),
uintptr(unsafe.Pointer(&element))))
str = BstrToString(*(**uint16)(unsafe.Pointer(&element)))
SysFreeString(element)
return
} | go | {
"resource": ""
} |
q19426 | ClassIDFrom | train | func ClassIDFrom(programID string) (classID *GUID, err error) {
classID, err = CLSIDFromProgID(programID)
if err != nil {
classID, err = CLSIDFromString(programID)
if err != nil {
return
}
}
return
} | go | {
"resource": ""
} |
q19427 | BytePtrToString | train | func BytePtrToString(p *byte) string {
a := (*[10000]uint8)(unsafe.Pointer(p))
i := 0
for a[i] != 0 {
i++
}
return string(a[:i])
} | go | {
"resource": ""
} |
q19428 | LpOleStrToString | train | func LpOleStrToString(p *uint16) string {
if p == nil {
return ""
}
length := lpOleStrLen(p)
a := make([]uint16, length)
ptr := unsafe.Pointer(p)
for i := 0; i < int(length); i++ {
a[i] = *(*uint16)(ptr)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
}
return string(utf16.Decode(a))
} | go | {
"resource": ""
} |
q19429 | BstrToString | train | func BstrToString(p *uint16) string {
if p == nil {
return ""
}
length := SysStringLen((*int16)(unsafe.Pointer(p)))
a := make([]uint16, length)
ptr := unsafe.Pointer(p)
for i := 0; i < int(length); i++ {
a[i] = *(*uint16)(ptr)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
}
return string(utf16.Decode(a))
} | go | {
"resource": ""
} |
q19430 | lpOleStrLen | train | func lpOleStrLen(p *uint16) (length int64) {
if p == nil {
return 0
}
ptr := unsafe.Pointer(p)
for i := 0; ; i++ {
if 0 == *(*uint16)(ptr) {
length = int64(i)
break
}
ptr = unsafe.Pointer(uintptr(ptr) + 2)
}
return
} | go | {
"resource": ""
} |
q19431 | convertHresultToError | train | func convertHresultToError(hr uintptr, r2 uintptr, ignore error) (err error) {
if hr != 0 {
err = NewError(hr)
}
return
} | go | {
"resource": ""
} |
q19432 | errstr | train | func errstr(errno int) string {
// ask windows for the remaining errors
var flags uint32 = syscall.FORMAT_MESSAGE_FROM_SYSTEM | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS
b := make([]uint16, 300)
n, err := syscall.FormatMessage(flags, 0, uint32(errno), 0, b, nil)
if err != nil {
return fmt.Sprintf("error %d (FormatMessage failed with: %v)", errno, err)
}
// trim terminating \r and \n
for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {
}
return string(utf16.Decode(b[:n]))
} | go | {
"resource": ""
} |
q19433 | LOGetCellString | train | func LOGetCellString(cell *ole.IDispatch) (value string) {
return oleutil.MustGetProperty(cell, "string").ToString()
} | go | {
"resource": ""
} |
q19434 | LOSetCellString | train | func LOSetCellString(cell *ole.IDispatch, text string) {
oleutil.MustPutProperty(cell, "string", text)
} | go | {
"resource": ""
} |
q19435 | LOSetCellValue | train | func LOSetCellValue(cell *ole.IDispatch, value float64) {
oleutil.MustPutProperty(cell, "value", value)
} | go | {
"resource": ""
} |
q19436 | LONewSpreadsheet | train | func LONewSpreadsheet(desktop *ole.IDispatch) (document *ole.IDispatch) {
var args = []string{}
document = oleutil.MustCallMethod(desktop,
"loadComponentFromURL", "private:factory/scalc", // alternative: private:factory/swriter
"_blank", 0, args).ToIDispatch()
return
} | go | {
"resource": ""
} |
q19437 | main | train | func main() {
ole.CoInitialize(0)
unknown, errCreate := oleutil.CreateObject("com.sun.star.ServiceManager")
checkError(errCreate, "Couldn't create a OLE connection to LibreOffice")
ServiceManager, errSM := unknown.QueryInterface(ole.IID_IDispatch)
checkError(errSM, "Couldn't start a LibreOffice instance")
desktop := oleutil.MustCallMethod(ServiceManager,
"createInstance", "com.sun.star.frame.Desktop").ToIDispatch()
document := LONewSpreadsheet(desktop)
sheet0 := LOGetWorksheet(document, 0)
cell1_1 := LOGetCell(sheet0, 1, 1) // cell B2
cell1_2 := LOGetCell(sheet0, 1, 2) // cell B3
cell1_3 := LOGetCell(sheet0, 1, 3) // cell B4
cell1_4 := LOGetCell(sheet0, 1, 4) // cell B5
LOSetCellString(cell1_1, "Hello World")
LOSetCellValue(cell1_2, 33.45)
LOSetCellFormula(cell1_3, "=B3+5")
b4Value := LOGetCellString(cell1_3)
LOSetCellString(cell1_4, b4Value)
// set background color yellow:
oleutil.MustPutProperty(cell1_1, "cellbackcolor", 0xFFFF00)
fmt.Printf("Press [ENTER] to exit")
fmt.Scanf("%s")
ServiceManager.Release()
ole.CoUninitialize()
} | go | {
"resource": ""
} |
q19438 | NewErrorWithDescription | train | func NewErrorWithDescription(hr uintptr, description string) *OleError {
return &OleError{hr: hr, description: description}
} | go | {
"resource": ""
} |
q19439 | NewErrorWithSubError | train | func NewErrorWithSubError(hr uintptr, description string, err error) *OleError {
return &OleError{hr: hr, description: description, subError: err}
} | go | {
"resource": ""
} |
q19440 | String | train | func (v *OleError) String() string {
if v.description != "" {
return errstr(int(v.hr)) + " (" + v.description + ")"
}
return errstr(int(v.hr))
} | go | {
"resource": ""
} |
q19441 | DeleteHString | train | func DeleteHString(hstring HString) (err error) {
hr, _, _ := procWindowsDeleteString.Call(uintptr(hstring))
if hr != 0 {
err = NewError(hr)
}
return
} | go | {
"resource": ""
} |
q19442 | String | train | func (h HString) String() string {
var u16buf uintptr
var u16len uint32
u16buf, _, _ = procWindowsGetStringRawBuffer.Call(
uintptr(h),
uintptr(unsafe.Pointer(&u16len)))
u16hdr := reflect.SliceHeader{Data: u16buf, Len: int(u16len), Cap: int(u16len)}
u16 := *(*[]uint16)(unsafe.Pointer(&u16hdr))
return syscall.UTF16ToString(u16)
} | go | {
"resource": ""
} |
q19443 | ClassIDFrom | train | func ClassIDFrom(programID string) (classID *ole.GUID, err error) {
return ole.ClassIDFrom(programID)
} | go | {
"resource": ""
} |
q19444 | CreateObject | train | func CreateObject(programID string) (unknown *ole.IUnknown, err error) {
classID, err := ole.ClassIDFrom(programID)
if err != nil {
return
}
unknown, err = ole.CreateInstance(classID, ole.IID_IUnknown)
if err != nil {
return
}
return
} | go | {
"resource": ""
} |
q19445 | GetActiveObject | train | func GetActiveObject(programID string) (unknown *ole.IUnknown, err error) {
classID, err := ole.ClassIDFrom(programID)
if err != nil {
return
}
unknown, err = ole.GetActiveObject(classID, ole.IID_IUnknown)
if err != nil {
return
}
return
} | go | {
"resource": ""
} |
q19446 | CallMethod | train | func CallMethod(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_METHOD, params)
} | go | {
"resource": ""
} |
q19447 | MustCallMethod | train | func MustCallMethod(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
r, err := CallMethod(disp, name, params...)
if err != nil {
panic(err.Error())
}
return r
} | go | {
"resource": ""
} |
q19448 | GetProperty | train | func GetProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_PROPERTYGET, params)
} | go | {
"resource": ""
} |
q19449 | MustGetProperty | train | func MustGetProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
r, err := GetProperty(disp, name, params...)
if err != nil {
panic(err.Error())
}
return r
} | go | {
"resource": ""
} |
q19450 | PutProperty | train | func PutProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_PROPERTYPUT, params)
} | go | {
"resource": ""
} |
q19451 | MustPutProperty | train | func MustPutProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
r, err := PutProperty(disp, name, params...)
if err != nil {
panic(err.Error())
}
return r
} | go | {
"resource": ""
} |
q19452 | PutPropertyRef | train | func PutPropertyRef(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_PROPERTYPUTREF, params)
} | go | {
"resource": ""
} |
q19453 | MustPutPropertyRef | train | func MustPutPropertyRef(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
r, err := PutPropertyRef(disp, name, params...)
if err != nil {
panic(err.Error())
}
return r
} | go | {
"resource": ""
} |
q19454 | drawOver | train | func (p *GIFPrinter) drawOver(target *image.Paletted, source image.Image) {
bounds := source.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
c := source.At(x, y)
if c == color.Transparent {
continue
}
target.Set(x, y, c)
}
}
} | go | {
"resource": ""
} |
q19455 | drawExact | train | func (p *GIFPrinter) drawExact(target *image.Paletted, source image.Image) {
bounds := source.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
target.Set(x, y, source.At(x, y))
}
}
} | go | {
"resource": ""
} |
q19456 | resetCursor | train | func resetCursor(w io.Writer, rows int) {
w.Write([]byte(fmt.Sprintf("\033[999D\033[%dA", rows)))
} | go | {
"resource": ""
} |
q19457 | NewPrinter | train | func NewPrinter(w io.Writer, c *Config) *Printer {
return &Printer{
w: w,
c: mergeConfig(c),
}
} | go | {
"resource": ""
} |
q19458 | EncodeJSON | train | func EncodeJSON(w io.Writer, i *Iterator) error {
r := make(Record)
// Open paren.
if _, err := w.Write([]byte{'['}); err != nil {
return err
}
var c int
enc := json.NewEncoder(w)
delim := []byte{',', '\n'}
for i.Next() {
if c > 0 {
if _, err := w.Write(delim); err != nil {
return err
}
}
c++
if err := i.Scan(r); err != nil {
return err
}
if err := enc.Encode(r); err != nil {
return err
}
}
// Close paren.
if _, err := w.Write([]byte{']'}); err != nil {
return err
}
return nil
} | go | {
"resource": ""
} |
q19459 | EncodeLDJSON | train | func EncodeLDJSON(w io.Writer, i *Iterator) error {
r := make(Record)
enc := json.NewEncoder(w)
for i.Next() {
if err := i.Scan(r); err != nil {
return err
}
if err := enc.Encode(r); err != nil {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q19460 | cleanParams | train | func cleanParams(p map[string]interface{}) map[string]interface{} {
c := make(map[string]interface{})
for k, v := range p {
switch x := v.(type) {
case string:
if x == "" {
continue
}
}
c[k] = v
}
return c
} | go | {
"resource": ""
} |
q19461 | Scan | train | func (i *Iterator) Scan(r Record) error {
if err := i.rows.MapScan(r); err != nil {
return err
}
mapBytesToString(r)
return nil
} | go | {
"resource": ""
} |
q19462 | Connect | train | func Connect(driver string, params map[string]interface{}) (*sqlx.DB, error) {
// Select the driver.
driver, ok := Drivers[driver]
if !ok {
return nil, ErrUnknownDriver
}
// Connect to the database.
connector := connectors[driver]
params = cleanParams(params)
dsn, ok := params["dsn"].(string)
if !ok {
dsn = connector(params)
}
return sqlx.Connect(driver, dsn)
} | go | {
"resource": ""
} |
q19463 | Execute | train | func Execute(db *sqlx.DB, sql string, params map[string]interface{}) (*Iterator, error) {
var (
err error
rows *sqlx.Rows
)
// Execute the query.
if params != nil && len(params) > 0 {
rows, err = db.NamedQuery(sql, params)
} else {
rows, err = db.Queryx(sql)
}
if err != nil {
return nil, err
}
cols, err := rows.Columns()
if err != nil {
return nil, err
}
return &Iterator{
Cols: cols,
rows: rows,
}, nil
} | go | {
"resource": ""
} |
q19464 | Shutdown | train | func Shutdown() {
connMapMutex.Lock()
for _, db := range connMap {
db.Close()
}
connMapMutex.Unlock()
} | go | {
"resource": ""
} |
q19465 | parseMimetype | train | func parseMimetype(mimetype string) string {
mimetype, params, err := mime.ParseMediaType(mimetype)
if err != nil {
return ""
}
// No Accept header passed.
if mimetype == "" {
return defaultMimetype
}
switch mimetype {
case "application/json":
if params["boundary"] == "NL" {
return "application/x-ldjson"
}
default:
if _, ok := mimetypeFormats[mimetype]; !ok {
return ""
}
}
return mimetype
} | go | {
"resource": ""
} |
q19466 | MatchFold | train | func MatchFold(source, target string) bool {
return match(source, target, unicode.ToLower)
} | go | {
"resource": ""
} |
q19467 | Find | train | func Find(source string, targets []string) []string {
return find(source, targets, noop)
} | go | {
"resource": ""
} |
q19468 | FindFold | train | func FindFold(source string, targets []string) []string {
return find(source, targets, unicode.ToLower)
} | go | {
"resource": ""
} |
q19469 | RankMatchFold | train | func RankMatchFold(source, target string) int {
return rank(source, target, unicode.ToLower)
} | go | {
"resource": ""
} |
q19470 | RankFind | train | func RankFind(source string, targets []string) Ranks {
var r Ranks
for index, target := range targets {
if match(source, target, noop) {
distance := LevenshteinDistance(source, target)
r = append(r, Rank{source, target, distance, index})
}
}
return r
} | go | {
"resource": ""
} |
q19471 | RankFindFold | train | func RankFindFold(source string, targets []string) Ranks {
var r Ranks
for index, target := range targets {
if match(source, target, unicode.ToLower) {
distance := LevenshteinDistance(source, target)
r = append(r, Rank{source, target, distance, index})
}
}
return r
} | go | {
"resource": ""
} |
q19472 | TranslateRune | train | func (tr *Translator) TranslateRune(r rune) (result rune, translated bool) {
switch {
case tr.quickDict != nil:
if r <= unicode.MaxASCII {
result = tr.quickDict.Dict[r]
if result != 0 {
translated = true
if tr.mappedRune >= 0 {
result = tr.mappedRune
}
break
}
}
fallthrough
case tr.runeMap != nil:
var ok bool
if result, ok = tr.runeMap[r]; ok {
translated = true
if tr.mappedRune >= 0 {
result = tr.mappedRune
}
break
}
fallthrough
default:
var rrm *runeRangeMap
ranges := tr.ranges
for i := len(ranges) - 1; i >= 0; i-- {
rrm = ranges[i]
if rrm.FromLo <= r && r <= rrm.FromHi {
translated = true
if tr.mappedRune >= 0 {
result = tr.mappedRune
break
}
if rrm.ToLo < rrm.ToHi {
result = rrm.ToLo + r - rrm.FromLo
} else if rrm.ToLo > rrm.ToHi {
// ToHi can be smaller than ToLo if range is from higher to lower.
result = rrm.ToLo - r + rrm.FromLo
} else {
result = rrm.ToLo
}
break
}
}
}
if tr.reverted {
if !translated {
result = tr.mappedRune
}
translated = !translated
}
if !translated {
result = r
}
return
} | go | {
"resource": ""
} |
q19473 | WordCount | train | func WordCount(str string) int {
var r rune
var size, n int
inWord := false
for len(str) > 0 {
r, size = utf8.DecodeRuneInString(str)
switch {
case isAlphabet(r):
if !inWord {
inWord = true
n++
}
case inWord && (r == '\'' || r == '-'):
// Still in word.
default:
inWord = false
}
str = str[size:]
}
return n
} | go | {
"resource": ""
} |
q19474 | isAlphabet | train | func isAlphabet(r rune) bool {
if !unicode.IsLetter(r) {
return false
}
switch {
// Quick check for non-CJK character.
case r < minCJKCharacter:
return true
// Common CJK characters.
case r >= '\u4E00' && r <= '\u9FCC':
return false
// Rare CJK characters.
case r >= '\u3400' && r <= '\u4D85':
return false
// Rare and historic CJK characters.
case r >= '\U00020000' && r <= '\U0002B81D':
return false
}
return true
} | go | {
"resource": ""
} |
q19475 | SwapCase | train | func SwapCase(str string) string {
var r rune
var size int
buf := &bytes.Buffer{}
for len(str) > 0 {
r, size = utf8.DecodeRuneInString(str)
switch {
case unicode.IsUpper(r):
buf.WriteRune(unicode.ToLower(r))
case unicode.IsLower(r):
buf.WriteRune(unicode.ToUpper(r))
default:
buf.WriteRune(r)
}
str = str[size:]
}
return buf.String()
} | go | {
"resource": ""
} |
q19476 | FirstRuneToUpper | train | func FirstRuneToUpper(str string) string {
if str == "" {
return str
}
r, size := utf8.DecodeRuneInString(str)
if !unicode.IsLower(r) {
return str
}
buf := &bytes.Buffer{}
buf.WriteRune(unicode.ToUpper(r))
buf.WriteString(str[size:])
return buf.String()
} | go | {
"resource": ""
} |
q19477 | FirstRuneToLower | train | func FirstRuneToLower(str string) string {
if str == "" {
return str
}
r, size := utf8.DecodeRuneInString(str)
if !unicode.IsUpper(r) {
return str
}
buf := &bytes.Buffer{}
buf.WriteRune(unicode.ToLower(r))
buf.WriteString(str[size:])
return buf.String()
} | go | {
"resource": ""
} |
q19478 | ShuffleSource | train | func ShuffleSource(str string, src rand.Source) string {
if str == "" {
return str
}
runes := []rune(str)
index := 0
r := rand.New(src)
for i := len(runes) - 1; i > 0; i-- {
index = r.Intn(i + 1)
if i != index {
runes[i], runes[index] = runes[index], runes[i]
}
}
return string(runes)
} | go | {
"resource": ""
} |
q19479 | Reverse | train | func Reverse(str string) string {
var size int
tail := len(str)
buf := make([]byte, tail)
s := buf
for len(str) > 0 {
_, size = utf8.DecodeRuneInString(str)
tail -= size
s = append(s[:tail], []byte(str[:size])...)
str = str[size:]
}
return string(buf)
} | go | {
"resource": ""
} |
q19480 | Partition | train | func Partition(str, sep string) (head, match, tail string) {
index := strings.Index(str, sep)
if index == -1 {
head = str
return
}
head = str[:index]
match = str[index : index+len(sep)]
tail = str[index+len(sep):]
return
} | go | {
"resource": ""
} |
q19481 | LastPartition | train | func LastPartition(str, sep string) (head, match, tail string) {
index := strings.LastIndex(str, sep)
if index == -1 {
tail = str
return
}
head = str[:index]
match = str[index : index+len(sep)]
tail = str[index+len(sep):]
return
} | go | {
"resource": ""
} |
q19482 | Insert | train | func Insert(dst, src string, index int) string {
return Slice(dst, 0, index) + src + Slice(dst, index, -1)
} | go | {
"resource": ""
} |
q19483 | Scrub | train | func Scrub(str, repl string) string {
var buf *bytes.Buffer
var r rune
var size, pos int
var hasError bool
origin := str
for len(str) > 0 {
r, size = utf8.DecodeRuneInString(str)
if r == utf8.RuneError {
if !hasError {
if buf == nil {
buf = &bytes.Buffer{}
}
buf.WriteString(origin[:pos])
hasError = true
}
} else if hasError {
hasError = false
buf.WriteString(repl)
origin = origin[pos:]
pos = 0
}
pos += size
str = str[size:]
}
if buf != nil {
buf.WriteString(origin)
return buf.String()
}
// No invalid byte.
return origin
} | go | {
"resource": ""
} |
q19484 | WordSplit | train | func WordSplit(str string) []string {
var word string
var words []string
var r rune
var size, pos int
inWord := false
for len(str) > 0 {
r, size = utf8.DecodeRuneInString(str)
switch {
case isAlphabet(r):
if !inWord {
inWord = true
word = str
pos = 0
}
case inWord && (r == '\'' || r == '-'):
// Still in word.
default:
if inWord {
inWord = false
words = append(words, word[:pos])
}
}
pos += size
str = str[size:]
}
if inWord {
words = append(words, word[:pos])
}
return words
} | go | {
"resource": ""
} |
q19485 | allocBuffer | train | func allocBuffer(orig, cur string) *bytes.Buffer {
output := &bytes.Buffer{}
maxSize := len(orig) * 4
// Avoid to reserve too much memory at once.
if maxSize > bufferMaxInitGrowSize {
maxSize = bufferMaxInitGrowSize
}
output.Grow(maxSize)
output.WriteString(orig[:len(orig)-len(cur)])
return output
} | go | {
"resource": ""
} |
q19486 | Run | train | func Run(c Component) Wait {
wait := make(Wait)
go func() {
c.Process()
wait <- Done{}
}()
return wait
} | go | {
"resource": ""
} |
q19487 | NewInputGuard | train | func NewInputGuard(ports ...string) *InputGuard {
portMap := make(map[string]bool, len(ports))
for _, p := range ports {
portMap[p] = false
}
return &InputGuard{portMap, 0}
} | go | {
"resource": ""
} |
q19488 | Complete | train | func (g *InputGuard) Complete(port string) bool {
if !g.ports[port] {
g.ports[port] = true
g.complete++
}
return g.complete >= len(g.ports)
} | go | {
"resource": ""
} |
q19489 | ParseJSON | train | func ParseJSON(js []byte) *Graph {
// Parse JSON into Go struct
var descr graphDescription
err := json.Unmarshal(js, &descr)
if err != nil {
return nil
}
// fmt.Printf("%+v\n", descr)
constructor := func() interface{} {
// Create a new Graph
net := new(Graph)
net.InitGraphState()
// Add processes to the network
for procName, procValue := range descr.Processes {
net.AddNew(procValue.Component, procName)
// Process mode detection
if procValue.Metadata.PoolSize > 0 {
proc := net.Get(procName).(*Component)
proc.Mode = ComponentModePool
proc.PoolSize = uint8(procValue.Metadata.PoolSize)
} else if procValue.Metadata.Sync {
proc := net.Get(procName).(*Component)
proc.Mode = ComponentModeSync
}
}
// Add connections
for _, conn := range descr.Connections {
// Check if it is an IIP or actual connection
if conn.Data == nil {
// Add a connection
net.ConnectBuf(conn.Src.Process, conn.Src.Port, conn.Tgt.Process, conn.Tgt.Port, conn.Metadata.Buffer)
} else {
// Add an IIP
net.AddIIP(conn.Data, conn.Tgt.Process, conn.Tgt.Port)
}
}
// Add port exports
for _, export := range descr.Exports {
// Split private into proc.port
procName := export.Private[:strings.Index(export.Private, ".")]
procPort := export.Private[strings.Index(export.Private, ".")+1:]
// Try to detect port direction using reflection
procType := reflect.TypeOf(net.Get(procName)).Elem()
field, fieldFound := procType.FieldByName(procPort)
if !fieldFound {
panic("Private port '" + export.Private + "' not found")
}
if field.Type.Kind() == reflect.Chan && (field.Type.ChanDir()&reflect.RecvDir) != 0 {
// It's an inport
net.MapInPort(export.Public, procName, procPort)
} else if field.Type.Kind() == reflect.Chan && (field.Type.ChanDir()&reflect.SendDir) != 0 {
// It's an outport
net.MapOutPort(export.Public, procName, procPort)
} else {
// It's not a proper port
panic("Private port '" + export.Private + "' is not a valid channel")
}
// TODO add support for subgraphs
}
return net
}
// Register a component to be reused
if descr.Properties.Name != "" {
Register(descr.Properties.Name, constructor)
}
return constructor().(*Graph)
} | go | {
"resource": ""
} |
q19490 | LoadJSON | train | func LoadJSON(filename string) *Graph {
js, err := ioutil.ReadFile(filename)
if err != nil {
return nil
}
return ParseJSON(js)
} | go | {
"resource": ""
} |
q19491 | RegisterJSON | train | func RegisterJSON(componentName, filePath string) bool {
var constructor ComponentConstructor
constructor = func() interface{} {
return LoadJSON(filePath)
}
return Register(componentName, constructor)
} | go | {
"resource": ""
} |
q19492 | NewFactory | train | func NewFactory(config ...FactoryConfig) *Factory {
conf := defaultFactoryConfig()
if len(config) == 1 {
conf = config[0]
}
return &Factory{
registry: make(map[string]registryEntry, conf.RegistryCapacity),
}
} | go | {
"resource": ""
} |
q19493 | Register | train | func (f *Factory) Register(componentName string, constructor Constructor) error {
if _, exists := f.registry[componentName]; exists {
return fmt.Errorf("Registry error: component '%s' already registered", componentName)
}
f.registry[componentName] = registryEntry{
Constructor: constructor,
Info: ComponentInfo{
Name: componentName,
},
}
return nil
} | go | {
"resource": ""
} |
q19494 | Annotate | train | func (f *Factory) Annotate(componentName string, annotation Annotation) error {
if _, exists := f.registry[componentName]; !exists {
return fmt.Errorf("Registry annotation error: component '%s' is not registered", componentName)
}
entry := f.registry[componentName]
entry.Info.Description = annotation.Description
entry.Info.Icon = annotation.Icon
f.registry[componentName] = entry
return nil
} | go | {
"resource": ""
} |
q19495 | Unregister | train | func (f *Factory) Unregister(componentName string) error {
if _, exists := f.registry[componentName]; exists {
delete(f.registry, componentName)
return nil
}
return fmt.Errorf("Registry error: component '%s' is not registered", componentName)
} | go | {
"resource": ""
} |
q19496 | Create | train | func (f *Factory) Create(componentName string) (interface{}, error) {
if info, exists := f.registry[componentName]; exists {
return info.Constructor()
}
return nil, fmt.Errorf("Factory error: component '%s' does not exist", componentName)
} | go | {
"resource": ""
} |
q19497 | ConnectBuf | train | func (n *Graph) ConnectBuf(senderName, senderPort, receiverName, receiverPort string, bufferSize int) error {
senderPortVal, err := n.getProcPort(senderName, senderPort, reflect.SendDir)
if err != nil {
return err
}
receiverPortVal, err := n.getProcPort(receiverName, receiverPort, reflect.RecvDir)
if err != nil {
return err
}
// Try to get an existing channel
var channel reflect.Value
if !receiverPortVal.IsNil() {
// Find existing channel attached to the receiver
channel = n.findExistingChan(receiverName, receiverPort, reflect.RecvDir)
}
sndPortType := senderPortVal.Type()
if !senderPortVal.IsNil() {
// If both ports are already busy, we cannot connect them
if channel.IsValid() && senderPortVal.Addr() != receiverPortVal.Addr() {
return fmt.Errorf("'%s.%s' cannot be connected to '%s.%s': both ports already in use", receiverName, receiverPort, senderName, senderPort)
}
// Find an existing channel attached to sender
// Receiver channel takes priority if exists
if !channel.IsValid() {
channel = n.findExistingChan(senderName, senderPort, reflect.SendDir)
}
}
// Create a new channel if none of the existing channles found
if !channel.IsValid() {
// Make a channel of an appropriate type
chanType := reflect.ChanOf(reflect.BothDir, sndPortType.Elem())
channel = reflect.MakeChan(chanType, bufferSize)
}
// Set the channels
// TODO fix rewiring a graph without disconnecting ports
if senderPortVal.IsNil() {
senderPortVal.Set(channel)
n.incSendChanRefCount(channel)
}
if receiverPortVal.IsNil() {
receiverPortVal.Set(channel)
}
// Add connection info
n.connections = append(n.connections, connection{
src: portName{proc: senderName,
port: senderPort},
tgt: portName{proc: receiverName,
port: receiverPort},
channel: channel,
buffer: bufferSize})
return nil
} | go | {
"resource": ""
} |
q19498 | getProcPort | train | func (n *Graph) getProcPort(procName, portName string, dir reflect.ChanDir) (reflect.Value, error) {
nilValue := reflect.ValueOf(nil)
// Ensure process exists
proc, ok := n.procs[procName]
if !ok {
return nilValue, fmt.Errorf("Connect error: process '%s' not found", procName)
}
// Ensure sender is settable
val := reflect.ValueOf(proc)
if val.Kind() == reflect.Ptr && val.IsValid() {
val = val.Elem()
}
if !val.CanSet() {
return nilValue, fmt.Errorf("Connect error: process '%s' is not settable", procName)
}
// Get the port value
var portVal reflect.Value
var err error
// Check if sender is a net
net, ok := val.Interface().(Graph)
if ok {
// Sender is a net
if dir == reflect.SendDir {
portVal, err = net.getOutPort(portName)
} else {
portVal, err = net.getInPort(portName)
}
} else {
// Sender is a proc
portVal = val.FieldByName(portName)
if !portVal.IsValid() {
err = errors.New("")
}
}
if err != nil {
return nilValue, fmt.Errorf("Connect error: process '%s' does not have port '%s'", procName, portName)
}
// Validate port type
portType := portVal.Type()
// Sender port can be an array port
if dir == reflect.SendDir && portType.Kind() == reflect.Slice {
portType = portType.Elem()
}
// Validate
if portType.Kind() != reflect.Chan || portType.ChanDir()&dir == 0 {
return nilValue, fmt.Errorf("Connect error: '%s.%s' is not of the correct chan type", procName, portName)
}
// Check assignability
if !portVal.CanSet() {
return nilValue, fmt.Errorf("'%s.%s' is not assignable", procName, portName)
}
return portVal, nil
} | go | {
"resource": ""
} |
q19499 | findExistingChan | train | func (n *Graph) findExistingChan(proc, procPort string, dir reflect.ChanDir) reflect.Value {
var channel reflect.Value
// Find existing channel attached to the receiver
for _, conn := range n.connections {
var p portName
if dir == reflect.SendDir {
p = conn.src
} else {
p = conn.tgt
}
if p.port == procPort && p.proc == proc {
channel = conn.channel
break
}
}
return channel
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.